1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.7.11.  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/*
310** Include standard header files as necessary
311*/
312#ifdef HAVE_STDINT_H
313#include <stdint.h>
314#endif
315#ifdef HAVE_INTTYPES_H
316#include <inttypes.h>
317#endif
318
319/*
320** The following macros are used to cast pointers to integers and
321** integers to pointers.  The way you do this varies from one compiler
322** to the next, so we have developed the following set of #if statements
323** to generate appropriate macros for a wide range of compilers.
324**
325** The correct "ANSI" way to do this is to use the intptr_t type.
326** Unfortunately, that typedef is not available on all compilers, or
327** if it is available, it requires an #include of specific headers
328** that vary from one machine to the next.
329**
330** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
331** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
332** So we have to define the macros in different ways depending on the
333** compiler.
334*/
335#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
336# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
337# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
338#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
339# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
340# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
341#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
342# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
343# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
344#else                          /* Generates a warning - but it always works */
345# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
346# define SQLITE_PTR_TO_INT(X)  ((int)(X))
347#endif
348
349/*
350** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
351** 0 means mutexes are permanently disable and the library is never
352** threadsafe.  1 means the library is serialized which is the highest
353** level of threadsafety.  2 means the libary is multithreaded - multiple
354** threads can use SQLite as long as no two threads try to use the same
355** database connection at the same time.
356**
357** Older versions of SQLite used an optional THREADSAFE macro.
358** We support that for legacy.
359*/
360#if !defined(SQLITE_THREADSAFE)
361#if defined(THREADSAFE)
362# define SQLITE_THREADSAFE THREADSAFE
363#else
364# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
365#endif
366#endif
367
368/*
369** Powersafe overwrite is on by default.  But can be turned off using
370** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
371*/
372#ifndef SQLITE_POWERSAFE_OVERWRITE
373# define SQLITE_POWERSAFE_OVERWRITE 1
374#endif
375
376/*
377** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
378** It determines whether or not the features related to
379** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
380** be overridden at runtime using the sqlite3_config() API.
381*/
382#if !defined(SQLITE_DEFAULT_MEMSTATUS)
383# define SQLITE_DEFAULT_MEMSTATUS 1
384#endif
385
386/*
387** Exactly one of the following macros must be defined in order to
388** specify which memory allocation subsystem to use.
389**
390**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
391**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
392**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
393**
394** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
395** assert() macro is enabled, each call into the Win32 native heap subsystem
396** will cause HeapValidate to be called.  If heap validation should fail, an
397** assertion will be triggered.
398**
399** (Historical note:  There used to be several other options, but we've
400** pared it down to just these three.)
401**
402** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
403** the default.
404*/
405#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)>1
406# error "At most one of the following compile-time configuration options\
407 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG"
408#endif
409#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)==0
410# define SQLITE_SYSTEM_MALLOC 1
411#endif
412
413/*
414** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
415** sizes of memory allocations below this value where possible.
416*/
417#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
418# define SQLITE_MALLOC_SOFT_LIMIT 1024
419#endif
420
421/*
422** We need to define _XOPEN_SOURCE as follows in order to enable
423** recursive mutexes on most Unix systems.  But Mac OS X is different.
424** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
425** so it is omitted there.  See ticket #2673.
426**
427** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
428** implemented on some systems.  So we avoid defining it at all
429** if it is already defined or if it is unneeded because we are
430** not doing a threadsafe build.  Ticket #2681.
431**
432** See also ticket #2741.
433*/
434#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
435#  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
436#endif
437
438/*
439** The TCL headers are only needed when compiling the TCL bindings.
440*/
441#if defined(SQLITE_TCL) || defined(TCLSH)
442# include <tcl.h>
443#endif
444
445/*
446** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
447** Setting NDEBUG makes the code smaller and run faster.  So the following
448** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
449** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
450** feature.
451*/
452#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
453# define NDEBUG 1
454#endif
455
456/*
457** The testcase() macro is used to aid in coverage testing.  When
458** doing coverage testing, the condition inside the argument to
459** testcase() must be evaluated both true and false in order to
460** get full branch coverage.  The testcase() macro is inserted
461** to help ensure adequate test coverage in places where simple
462** condition/decision coverage is inadequate.  For example, testcase()
463** can be used to make sure boundary values are tested.  For
464** bitmask tests, testcase() can be used to make sure each bit
465** is significant and used at least once.  On switch statements
466** where multiple cases go to the same block of code, testcase()
467** can insure that all cases are evaluated.
468**
469*/
470#ifdef SQLITE_COVERAGE_TEST
471SQLITE_PRIVATE   void sqlite3Coverage(int);
472# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
473#else
474# define testcase(X)
475#endif
476
477/*
478** The TESTONLY macro is used to enclose variable declarations or
479** other bits of code that are needed to support the arguments
480** within testcase() and assert() macros.
481*/
482#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
483# define TESTONLY(X)  X
484#else
485# define TESTONLY(X)
486#endif
487
488/*
489** Sometimes we need a small amount of code such as a variable initialization
490** to setup for a later assert() statement.  We do not want this code to
491** appear when assert() is disabled.  The following macro is therefore
492** used to contain that setup code.  The "VVA" acronym stands for
493** "Verification, Validation, and Accreditation".  In other words, the
494** code within VVA_ONLY() will only run during verification processes.
495*/
496#ifndef NDEBUG
497# define VVA_ONLY(X)  X
498#else
499# define VVA_ONLY(X)
500#endif
501
502/*
503** The ALWAYS and NEVER macros surround boolean expressions which
504** are intended to always be true or false, respectively.  Such
505** expressions could be omitted from the code completely.  But they
506** are included in a few cases in order to enhance the resilience
507** of SQLite to unexpected behavior - to make the code "self-healing"
508** or "ductile" rather than being "brittle" and crashing at the first
509** hint of unplanned behavior.
510**
511** In other words, ALWAYS and NEVER are added for defensive code.
512**
513** When doing coverage testing ALWAYS and NEVER are hard-coded to
514** be true and false so that the unreachable code then specify will
515** not be counted as untested code.
516*/
517#if defined(SQLITE_COVERAGE_TEST)
518# define ALWAYS(X)      (1)
519# define NEVER(X)       (0)
520#elif !defined(NDEBUG)
521# define ALWAYS(X)      ((X)?1:(assert(0),0))
522# define NEVER(X)       ((X)?(assert(0),1):0)
523#else
524# define ALWAYS(X)      (X)
525# define NEVER(X)       (X)
526#endif
527
528/*
529** Return true (non-zero) if the input is a integer that is too large
530** to fit in 32-bits.  This macro is used inside of various testcase()
531** macros to verify that we have tested SQLite for large-file support.
532*/
533#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
534
535/*
536** The macro unlikely() is a hint that surrounds a boolean
537** expression that is usually false.  Macro likely() surrounds
538** a boolean expression that is usually true.  GCC is able to
539** use these hints to generate better code, sometimes.
540*/
541#if defined(__GNUC__) && 0
542# define likely(X)    __builtin_expect((X),1)
543# define unlikely(X)  __builtin_expect((X),0)
544#else
545# define likely(X)    !!(X)
546# define unlikely(X)  !!(X)
547#endif
548
549/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
550/************** Begin file sqlite3.h *****************************************/
551/*
552** 2001 September 15
553**
554** The author disclaims copyright to this source code.  In place of
555** a legal notice, here is a blessing:
556**
557**    May you do good and not evil.
558**    May you find forgiveness for yourself and forgive others.
559**    May you share freely, never taking more than you give.
560**
561*************************************************************************
562** This header file defines the interface that the SQLite library
563** presents to client programs.  If a C-function, structure, datatype,
564** or constant definition does not appear in this file, then it is
565** not a published API of SQLite, is subject to change without
566** notice, and should not be referenced by programs that use SQLite.
567**
568** Some of the definitions that are in this file are marked as
569** "experimental".  Experimental interfaces are normally new
570** features recently added to SQLite.  We do not anticipate changes
571** to experimental interfaces but reserve the right to make minor changes
572** if experience from use "in the wild" suggest such changes are prudent.
573**
574** The official C-language API documentation for SQLite is derived
575** from comments in this file.  This file is the authoritative source
576** on how SQLite interfaces are suppose to operate.
577**
578** The name of this file under configuration management is "sqlite.h.in".
579** The makefile makes some minor changes to this file (such as inserting
580** the version number) and changes its name to "sqlite3.h" as
581** part of the build process.
582*/
583#ifndef _SQLITE3_H_
584#define _SQLITE3_H_
585#include <stdarg.h>     /* Needed for the definition of va_list */
586
587/*
588** Make sure we can call this stuff from C++.
589*/
590#if 0
591extern "C" {
592#endif
593
594
595/*
596** Add the ability to override 'extern'
597*/
598#ifndef SQLITE_EXTERN
599# define SQLITE_EXTERN extern
600#endif
601
602#ifndef SQLITE_API
603# define SQLITE_API
604#endif
605
606
607/*
608** These no-op macros are used in front of interfaces to mark those
609** interfaces as either deprecated or experimental.  New applications
610** should not use deprecated interfaces - they are support for backwards
611** compatibility only.  Application writers should be aware that
612** experimental interfaces are subject to change in point releases.
613**
614** These macros used to resolve to various kinds of compiler magic that
615** would generate warning messages when they were used.  But that
616** compiler magic ended up generating such a flurry of bug reports
617** that we have taken it all out and gone back to using simple
618** noop macros.
619*/
620#define SQLITE_DEPRECATED
621#define SQLITE_EXPERIMENTAL
622
623/*
624** Ensure these symbols were not defined by some previous header file.
625*/
626#ifdef SQLITE_VERSION
627# undef SQLITE_VERSION
628#endif
629#ifdef SQLITE_VERSION_NUMBER
630# undef SQLITE_VERSION_NUMBER
631#endif
632
633/*
634** CAPI3REF: Compile-Time Library Version Numbers
635**
636** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
637** evaluates to a string literal that is the SQLite version in the
638** format "X.Y.Z" where X is the major version number (always 3 for
639** SQLite3) and Y is the minor version number and Z is the release number.)^
640** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
641** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
642** numbers used in [SQLITE_VERSION].)^
643** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
644** be larger than the release from which it is derived.  Either Y will
645** be held constant and Z will be incremented or else Y will be incremented
646** and Z will be reset to zero.
647**
648** Since version 3.6.18, SQLite source code has been stored in the
649** <a href="http://www.fossil-scm.org/">Fossil configuration management
650** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
651** a string which identifies a particular check-in of SQLite
652** within its configuration management system.  ^The SQLITE_SOURCE_ID
653** string contains the date and time of the check-in (UTC) and an SHA1
654** hash of the entire source tree.
655**
656** See also: [sqlite3_libversion()],
657** [sqlite3_libversion_number()], [sqlite3_sourceid()],
658** [sqlite_version()] and [sqlite_source_id()].
659*/
660#define SQLITE_VERSION        "3.7.11"
661#define SQLITE_VERSION_NUMBER 3007011
662#define SQLITE_SOURCE_ID      "2012-03-20 11:35:50 00bb9c9ce4f465e6ac321ced2a9d0062dc364669"
663
664/*
665** CAPI3REF: Run-Time Library Version Numbers
666** KEYWORDS: sqlite3_version, sqlite3_sourceid
667**
668** These interfaces provide the same information as the [SQLITE_VERSION],
669** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
670** but are associated with the library instead of the header file.  ^(Cautious
671** programmers might include assert() statements in their application to
672** verify that values returned by these interfaces match the macros in
673** the header, and thus insure that the application is
674** compiled with matching library and header files.
675**
676** <blockquote><pre>
677** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
678** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
679** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
680** </pre></blockquote>)^
681**
682** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
683** macro.  ^The sqlite3_libversion() function returns a pointer to the
684** to the sqlite3_version[] string constant.  The sqlite3_libversion()
685** function is provided for use in DLLs since DLL users usually do not have
686** direct access to string constants within the DLL.  ^The
687** sqlite3_libversion_number() function returns an integer equal to
688** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
689** a pointer to a string constant whose value is the same as the
690** [SQLITE_SOURCE_ID] C preprocessor macro.
691**
692** See also: [sqlite_version()] and [sqlite_source_id()].
693*/
694SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
695SQLITE_API const char *sqlite3_libversion(void);
696SQLITE_API const char *sqlite3_sourceid(void);
697SQLITE_API int sqlite3_libversion_number(void);
698
699/*
700** CAPI3REF: Run-Time Library Compilation Options Diagnostics
701**
702** ^The sqlite3_compileoption_used() function returns 0 or 1
703** indicating whether the specified option was defined at
704** compile time.  ^The SQLITE_ prefix may be omitted from the
705** option name passed to sqlite3_compileoption_used().
706**
707** ^The sqlite3_compileoption_get() function allows iterating
708** over the list of options that were defined at compile time by
709** returning the N-th compile time option string.  ^If N is out of range,
710** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
711** prefix is omitted from any strings returned by
712** sqlite3_compileoption_get().
713**
714** ^Support for the diagnostic functions sqlite3_compileoption_used()
715** and sqlite3_compileoption_get() may be omitted by specifying the
716** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
717**
718** See also: SQL functions [sqlite_compileoption_used()] and
719** [sqlite_compileoption_get()] and the [compile_options pragma].
720*/
721#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
722SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
723SQLITE_API const char *sqlite3_compileoption_get(int N);
724#endif
725
726/*
727** CAPI3REF: Test To See If The Library Is Threadsafe
728**
729** ^The sqlite3_threadsafe() function returns zero if and only if
730** SQLite was compiled with mutexing code omitted due to the
731** [SQLITE_THREADSAFE] compile-time option being set to 0.
732**
733** SQLite can be compiled with or without mutexes.  When
734** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
735** are enabled and SQLite is threadsafe.  When the
736** [SQLITE_THREADSAFE] macro is 0,
737** the mutexes are omitted.  Without the mutexes, it is not safe
738** to use SQLite concurrently from more than one thread.
739**
740** Enabling mutexes incurs a measurable performance penalty.
741** So if speed is of utmost importance, it makes sense to disable
742** the mutexes.  But for maximum safety, mutexes should be enabled.
743** ^The default behavior is for mutexes to be enabled.
744**
745** This interface can be used by an application to make sure that the
746** version of SQLite that it is linking against was compiled with
747** the desired setting of the [SQLITE_THREADSAFE] macro.
748**
749** This interface only reports on the compile-time mutex setting
750** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
751** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
752** can be fully or partially disabled using a call to [sqlite3_config()]
753** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
754** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
755** sqlite3_threadsafe() function shows only the compile-time setting of
756** thread safety, not any run-time changes to that setting made by
757** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
758** is unchanged by calls to sqlite3_config().)^
759**
760** See the [threading mode] documentation for additional information.
761*/
762SQLITE_API int sqlite3_threadsafe(void);
763
764/*
765** CAPI3REF: Database Connection Handle
766** KEYWORDS: {database connection} {database connections}
767**
768** Each open SQLite database is represented by a pointer to an instance of
769** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
770** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
771** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
772** is its destructor.  There are many other interfaces (such as
773** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
774** [sqlite3_busy_timeout()] to name but three) that are methods on an
775** sqlite3 object.
776*/
777typedef struct sqlite3 sqlite3;
778
779/*
780** CAPI3REF: 64-Bit Integer Types
781** KEYWORDS: sqlite_int64 sqlite_uint64
782**
783** Because there is no cross-platform way to specify 64-bit integer types
784** SQLite includes typedefs for 64-bit signed and unsigned integers.
785**
786** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
787** The sqlite_int64 and sqlite_uint64 types are supported for backwards
788** compatibility only.
789**
790** ^The sqlite3_int64 and sqlite_int64 types can store integer values
791** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
792** sqlite3_uint64 and sqlite_uint64 types can store integer values
793** between 0 and +18446744073709551615 inclusive.
794*/
795#ifdef SQLITE_INT64_TYPE
796  typedef SQLITE_INT64_TYPE sqlite_int64;
797  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
798#elif defined(_MSC_VER) || defined(__BORLANDC__)
799  typedef __int64 sqlite_int64;
800  typedef unsigned __int64 sqlite_uint64;
801#else
802  typedef long long int sqlite_int64;
803  typedef unsigned long long int sqlite_uint64;
804#endif
805typedef sqlite_int64 sqlite3_int64;
806typedef sqlite_uint64 sqlite3_uint64;
807
808/*
809** If compiling for a processor that lacks floating point support,
810** substitute integer for floating-point.
811*/
812#ifdef SQLITE_OMIT_FLOATING_POINT
813# define double sqlite3_int64
814#endif
815
816/*
817** CAPI3REF: Closing A Database Connection
818**
819** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
820** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
821** successfully destroyed and all associated resources are deallocated.
822**
823** Applications must [sqlite3_finalize | finalize] all [prepared statements]
824** and [sqlite3_blob_close | close] all [BLOB handles] associated with
825** the [sqlite3] object prior to attempting to close the object.  ^If
826** sqlite3_close() is called on a [database connection] that still has
827** outstanding [prepared statements] or [BLOB handles], then it returns
828** SQLITE_BUSY.
829**
830** ^If [sqlite3_close()] is invoked while a transaction is open,
831** the transaction is automatically rolled back.
832**
833** The C parameter to [sqlite3_close(C)] must be either a NULL
834** pointer or an [sqlite3] object pointer obtained
835** from [sqlite3_open()], [sqlite3_open16()], or
836** [sqlite3_open_v2()], and not previously closed.
837** ^Calling sqlite3_close() with a NULL pointer argument is a
838** harmless no-op.
839*/
840SQLITE_API int sqlite3_close(sqlite3 *);
841
842/*
843** The type for a callback function.
844** This is legacy and deprecated.  It is included for historical
845** compatibility and is not documented.
846*/
847typedef int (*sqlite3_callback)(void*,int,char**, char**);
848
849/*
850** CAPI3REF: One-Step Query Execution Interface
851**
852** The sqlite3_exec() interface is a convenience wrapper around
853** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
854** that allows an application to run multiple statements of SQL
855** without having to use a lot of C code.
856**
857** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
858** semicolon-separate SQL statements passed into its 2nd argument,
859** in the context of the [database connection] passed in as its 1st
860** argument.  ^If the callback function of the 3rd argument to
861** sqlite3_exec() is not NULL, then it is invoked for each result row
862** coming out of the evaluated SQL statements.  ^The 4th argument to
863** sqlite3_exec() is relayed through to the 1st argument of each
864** callback invocation.  ^If the callback pointer to sqlite3_exec()
865** is NULL, then no callback is ever invoked and result rows are
866** ignored.
867**
868** ^If an error occurs while evaluating the SQL statements passed into
869** sqlite3_exec(), then execution of the current statement stops and
870** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
871** is not NULL then any error message is written into memory obtained
872** from [sqlite3_malloc()] and passed back through the 5th parameter.
873** To avoid memory leaks, the application should invoke [sqlite3_free()]
874** on error message strings returned through the 5th parameter of
875** of sqlite3_exec() after the error message string is no longer needed.
876** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
877** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
878** NULL before returning.
879**
880** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
881** routine returns SQLITE_ABORT without invoking the callback again and
882** without running any subsequent SQL statements.
883**
884** ^The 2nd argument to the sqlite3_exec() callback function is the
885** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
886** callback is an array of pointers to strings obtained as if from
887** [sqlite3_column_text()], one for each column.  ^If an element of a
888** result row is NULL then the corresponding string pointer for the
889** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
890** sqlite3_exec() callback is an array of pointers to strings where each
891** entry represents the name of corresponding result column as obtained
892** from [sqlite3_column_name()].
893**
894** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
895** to an empty string, or a pointer that contains only whitespace and/or
896** SQL comments, then no SQL statements are evaluated and the database
897** is not changed.
898**
899** Restrictions:
900**
901** <ul>
902** <li> The application must insure that the 1st parameter to sqlite3_exec()
903**      is a valid and open [database connection].
904** <li> The application must not close [database connection] specified by
905**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
906** <li> The application must not modify the SQL statement text passed into
907**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
908** </ul>
909*/
910SQLITE_API int sqlite3_exec(
911  sqlite3*,                                  /* An open database */
912  const char *sql,                           /* SQL to be evaluated */
913  int (*callback)(void*,int,char**,char**),  /* Callback function */
914  void *,                                    /* 1st argument to callback */
915  char **errmsg                              /* Error msg written here */
916);
917
918/*
919** CAPI3REF: Result Codes
920** KEYWORDS: SQLITE_OK {error code} {error codes}
921** KEYWORDS: {result code} {result codes}
922**
923** Many SQLite functions return an integer result code from the set shown
924** here in order to indicate success or failure.
925**
926** New error codes may be added in future versions of SQLite.
927**
928** See also: [SQLITE_IOERR_READ | extended result codes],
929** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
930*/
931#define SQLITE_OK           0   /* Successful result */
932/* beginning-of-error-codes */
933#define SQLITE_ERROR        1   /* SQL error or missing database */
934#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
935#define SQLITE_PERM         3   /* Access permission denied */
936#define SQLITE_ABORT        4   /* Callback routine requested an abort */
937#define SQLITE_BUSY         5   /* The database file is locked */
938#define SQLITE_LOCKED       6   /* A table in the database is locked */
939#define SQLITE_NOMEM        7   /* A malloc() failed */
940#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
941#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
942#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
943#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
944#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
945#define SQLITE_FULL        13   /* Insertion failed because database is full */
946#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
947#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
948#define SQLITE_EMPTY       16   /* Database is empty */
949#define SQLITE_SCHEMA      17   /* The database schema changed */
950#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
951#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
952#define SQLITE_MISMATCH    20   /* Data type mismatch */
953#define SQLITE_MISUSE      21   /* Library used incorrectly */
954#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
955#define SQLITE_AUTH        23   /* Authorization denied */
956#define SQLITE_FORMAT      24   /* Auxiliary database format error */
957#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
958#define SQLITE_NOTADB      26   /* File opened that is not a database file */
959#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
960#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
961/* end-of-error-codes */
962
963/*
964** CAPI3REF: Extended Result Codes
965** KEYWORDS: {extended error code} {extended error codes}
966** KEYWORDS: {extended result code} {extended result codes}
967**
968** In its default configuration, SQLite API routines return one of 26 integer
969** [SQLITE_OK | result codes].  However, experience has shown that many of
970** these result codes are too coarse-grained.  They do not provide as
971** much information about problems as programmers might like.  In an effort to
972** address this, newer versions of SQLite (version 3.3.8 and later) include
973** support for additional result codes that provide more detailed information
974** about errors. The extended result codes are enabled or disabled
975** on a per database connection basis using the
976** [sqlite3_extended_result_codes()] API.
977**
978** Some of the available extended result codes are listed here.
979** One may expect the number of extended result codes will be expand
980** over time.  Software that uses extended result codes should expect
981** to see new result codes in future releases of SQLite.
982**
983** The SQLITE_OK result code will never be extended.  It will always
984** be exactly zero.
985*/
986#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
987#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
988#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
989#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
990#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
991#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
992#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
993#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
994#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
995#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
996#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
997#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
998#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
999#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1000#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1001#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1002#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1003#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
1004#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
1005#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
1006#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1007#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1008#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1009#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1010#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1011#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1012#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1013#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1014#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
1015
1016/*
1017** CAPI3REF: Flags For File Open Operations
1018**
1019** These bit values are intended for use in the
1020** 3rd parameter to the [sqlite3_open_v2()] interface and
1021** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1022*/
1023#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1024#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1025#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1026#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1027#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1028#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1029#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1030#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1031#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1032#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1033#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1034#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1035#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1036#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1037#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1038#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1039#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1040#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1041#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1042
1043/* Reserved:                         0x00F00000 */
1044
1045/*
1046** CAPI3REF: Device Characteristics
1047**
1048** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1049** object returns an integer which is a vector of the these
1050** bit values expressing I/O characteristics of the mass storage
1051** device that holds the file that the [sqlite3_io_methods]
1052** refers to.
1053**
1054** The SQLITE_IOCAP_ATOMIC property means that all writes of
1055** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1056** mean that writes of blocks that are nnn bytes in size and
1057** are aligned to an address which is an integer multiple of
1058** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1059** that when data is appended to a file, the data is appended
1060** first then the size of the file is extended, never the other
1061** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1062** information is written to disk in the same order as calls
1063** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1064** after reboot following a crash or power loss, the only bytes in a
1065** file that were written at the application level might have changed
1066** and that adjacent bytes, even bytes within the same sector are
1067** guaranteed to be unchanged.
1068*/
1069#define SQLITE_IOCAP_ATOMIC                 0x00000001
1070#define SQLITE_IOCAP_ATOMIC512              0x00000002
1071#define SQLITE_IOCAP_ATOMIC1K               0x00000004
1072#define SQLITE_IOCAP_ATOMIC2K               0x00000008
1073#define SQLITE_IOCAP_ATOMIC4K               0x00000010
1074#define SQLITE_IOCAP_ATOMIC8K               0x00000020
1075#define SQLITE_IOCAP_ATOMIC16K              0x00000040
1076#define SQLITE_IOCAP_ATOMIC32K              0x00000080
1077#define SQLITE_IOCAP_ATOMIC64K              0x00000100
1078#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1079#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1080#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1081#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
1082
1083/*
1084** CAPI3REF: File Locking Levels
1085**
1086** SQLite uses one of these integer values as the second
1087** argument to calls it makes to the xLock() and xUnlock() methods
1088** of an [sqlite3_io_methods] object.
1089*/
1090#define SQLITE_LOCK_NONE          0
1091#define SQLITE_LOCK_SHARED        1
1092#define SQLITE_LOCK_RESERVED      2
1093#define SQLITE_LOCK_PENDING       3
1094#define SQLITE_LOCK_EXCLUSIVE     4
1095
1096/*
1097** CAPI3REF: Synchronization Type Flags
1098**
1099** When SQLite invokes the xSync() method of an
1100** [sqlite3_io_methods] object it uses a combination of
1101** these integer values as the second argument.
1102**
1103** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1104** sync operation only needs to flush data to mass storage.  Inode
1105** information need not be flushed. If the lower four bits of the flag
1106** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1107** If the lower four bits equal SQLITE_SYNC_FULL, that means
1108** to use Mac OS X style fullsync instead of fsync().
1109**
1110** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1111** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1112** settings.  The [synchronous pragma] determines when calls to the
1113** xSync VFS method occur and applies uniformly across all platforms.
1114** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1115** energetic or rigorous or forceful the sync operations are and
1116** only make a difference on Mac OSX for the default SQLite code.
1117** (Third-party VFS implementations might also make the distinction
1118** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1119** operating systems natively supported by SQLite, only Mac OSX
1120** cares about the difference.)
1121*/
1122#define SQLITE_SYNC_NORMAL        0x00002
1123#define SQLITE_SYNC_FULL          0x00003
1124#define SQLITE_SYNC_DATAONLY      0x00010
1125
1126/*
1127** CAPI3REF: OS Interface Open File Handle
1128**
1129** An [sqlite3_file] object represents an open file in the
1130** [sqlite3_vfs | OS interface layer].  Individual OS interface
1131** implementations will
1132** want to subclass this object by appending additional fields
1133** for their own use.  The pMethods entry is a pointer to an
1134** [sqlite3_io_methods] object that defines methods for performing
1135** I/O operations on the open file.
1136*/
1137typedef struct sqlite3_file sqlite3_file;
1138struct sqlite3_file {
1139  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1140};
1141
1142/*
1143** CAPI3REF: OS Interface File Virtual Methods Object
1144**
1145** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1146** [sqlite3_file] object (or, more commonly, a subclass of the
1147** [sqlite3_file] object) with a pointer to an instance of this object.
1148** This object defines the methods used to perform various operations
1149** against the open file represented by the [sqlite3_file] object.
1150**
1151** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1152** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1153** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1154** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1155** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1156** to NULL.
1157**
1158** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1159** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1160** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1161** flag may be ORed in to indicate that only the data of the file
1162** and not its inode needs to be synced.
1163**
1164** The integer values to xLock() and xUnlock() are one of
1165** <ul>
1166** <li> [SQLITE_LOCK_NONE],
1167** <li> [SQLITE_LOCK_SHARED],
1168** <li> [SQLITE_LOCK_RESERVED],
1169** <li> [SQLITE_LOCK_PENDING], or
1170** <li> [SQLITE_LOCK_EXCLUSIVE].
1171** </ul>
1172** xLock() increases the lock. xUnlock() decreases the lock.
1173** The xCheckReservedLock() method checks whether any database connection,
1174** either in this process or in some other process, is holding a RESERVED,
1175** PENDING, or EXCLUSIVE lock on the file.  It returns true
1176** if such a lock exists and false otherwise.
1177**
1178** The xFileControl() method is a generic interface that allows custom
1179** VFS implementations to directly control an open file using the
1180** [sqlite3_file_control()] interface.  The second "op" argument is an
1181** integer opcode.  The third argument is a generic pointer intended to
1182** point to a structure that may contain arguments or space in which to
1183** write return values.  Potential uses for xFileControl() might be
1184** functions to enable blocking locks with timeouts, to change the
1185** locking strategy (for example to use dot-file locks), to inquire
1186** about the status of a lock, or to break stale locks.  The SQLite
1187** core reserves all opcodes less than 100 for its own use.
1188** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1189** Applications that define a custom xFileControl method should use opcodes
1190** greater than 100 to avoid conflicts.  VFS implementations should
1191** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1192** recognize.
1193**
1194** The xSectorSize() method returns the sector size of the
1195** device that underlies the file.  The sector size is the
1196** minimum write that can be performed without disturbing
1197** other bytes in the file.  The xDeviceCharacteristics()
1198** method returns a bit vector describing behaviors of the
1199** underlying device:
1200**
1201** <ul>
1202** <li> [SQLITE_IOCAP_ATOMIC]
1203** <li> [SQLITE_IOCAP_ATOMIC512]
1204** <li> [SQLITE_IOCAP_ATOMIC1K]
1205** <li> [SQLITE_IOCAP_ATOMIC2K]
1206** <li> [SQLITE_IOCAP_ATOMIC4K]
1207** <li> [SQLITE_IOCAP_ATOMIC8K]
1208** <li> [SQLITE_IOCAP_ATOMIC16K]
1209** <li> [SQLITE_IOCAP_ATOMIC32K]
1210** <li> [SQLITE_IOCAP_ATOMIC64K]
1211** <li> [SQLITE_IOCAP_SAFE_APPEND]
1212** <li> [SQLITE_IOCAP_SEQUENTIAL]
1213** </ul>
1214**
1215** The SQLITE_IOCAP_ATOMIC property means that all writes of
1216** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1217** mean that writes of blocks that are nnn bytes in size and
1218** are aligned to an address which is an integer multiple of
1219** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1220** that when data is appended to a file, the data is appended
1221** first then the size of the file is extended, never the other
1222** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1223** information is written to disk in the same order as calls
1224** to xWrite().
1225**
1226** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1227** in the unread portions of the buffer with zeros.  A VFS that
1228** fails to zero-fill short reads might seem to work.  However,
1229** failure to zero-fill short reads will eventually lead to
1230** database corruption.
1231*/
1232typedef struct sqlite3_io_methods sqlite3_io_methods;
1233struct sqlite3_io_methods {
1234  int iVersion;
1235  int (*xClose)(sqlite3_file*);
1236  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1237  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1238  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1239  int (*xSync)(sqlite3_file*, int flags);
1240  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1241  int (*xLock)(sqlite3_file*, int);
1242  int (*xUnlock)(sqlite3_file*, int);
1243  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1244  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1245  int (*xSectorSize)(sqlite3_file*);
1246  int (*xDeviceCharacteristics)(sqlite3_file*);
1247  /* Methods above are valid for version 1 */
1248  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1249  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1250  void (*xShmBarrier)(sqlite3_file*);
1251  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1252  /* Methods above are valid for version 2 */
1253  /* Additional methods may be added in future releases */
1254};
1255
1256/*
1257** CAPI3REF: Standard File Control Opcodes
1258**
1259** These integer constants are opcodes for the xFileControl method
1260** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1261** interface.
1262**
1263** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1264** opcode causes the xFileControl method to write the current state of
1265** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1266** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1267** into an integer that the pArg argument points to. This capability
1268** is used during testing and only needs to be supported when SQLITE_TEST
1269** is defined.
1270** <ul>
1271** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1272** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1273** layer a hint of how large the database file will grow to be during the
1274** current transaction.  This hint is not guaranteed to be accurate but it
1275** is often close.  The underlying VFS might choose to preallocate database
1276** file space based on this hint in order to help writes to the database
1277** file run faster.
1278**
1279** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1280** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1281** extends and truncates the database file in chunks of a size specified
1282** by the user. The fourth argument to [sqlite3_file_control()] should
1283** point to an integer (type int) containing the new chunk-size to use
1284** for the nominated database. Allocating database file space in large
1285** chunks (say 1MB at a time), may reduce file-system fragmentation and
1286** improve performance on some systems.
1287**
1288** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1289** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1290** to the [sqlite3_file] object associated with a particular database
1291** connection.  See the [sqlite3_file_control()] documentation for
1292** additional information.
1293**
1294** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1295** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1296** SQLite and sent to all VFSes in place of a call to the xSync method
1297** when the database connection has [PRAGMA synchronous] set to OFF.)^
1298** Some specialized VFSes need this signal in order to operate correctly
1299** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
1300** VFSes do not need this signal and should silently ignore this opcode.
1301** Applications should not call [sqlite3_file_control()] with this
1302** opcode as doing so may disrupt the operation of the specialized VFSes
1303** that do require it.
1304**
1305** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1306** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1307** retry counts and intervals for certain disk I/O operations for the
1308** windows [VFS] in order to provide robustness in the presence of
1309** anti-virus programs.  By default, the windows VFS will retry file read,
1310** file write, and file delete operations up to 10 times, with a delay
1311** of 25 milliseconds before the first retry and with the delay increasing
1312** by an additional 25 milliseconds with each subsequent retry.  This
1313** opcode allows these two values (10 retries and 25 milliseconds of delay)
1314** to be adjusted.  The values are changed for all database connections
1315** within the same process.  The argument is a pointer to an array of two
1316** integers where the first integer i the new retry count and the second
1317** integer is the delay.  If either integer is negative, then the setting
1318** is not changed but instead the prior value of that setting is written
1319** into the array entry, allowing the current retry settings to be
1320** interrogated.  The zDbName parameter is ignored.
1321**
1322** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1323** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1324** persistent [WAL | Write AHead Log] setting.  By default, the auxiliary
1325** write ahead log and shared memory files used for transaction control
1326** are automatically deleted when the latest connection to the database
1327** closes.  Setting persistent WAL mode causes those files to persist after
1328** close.  Persisting the files is useful when other processes that do not
1329** have write permission on the directory containing the database file want
1330** to read the database file, as the WAL and shared memory files must exist
1331** in order for the database to be readable.  The fourth parameter to
1332** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1333** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1334** WAL mode.  If the integer is -1, then it is overwritten with the current
1335** WAL persistence setting.
1336**
1337** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1338** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1339** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1340** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1341** xDeviceCharacteristics methods. The fourth parameter to
1342** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1343** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1344** mode.  If the integer is -1, then it is overwritten with the current
1345** zero-damage mode setting.
1346**
1347** <li>[[SQLITE_FCNTL_OVERWRITE]]
1348** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1349** a write transaction to indicate that, unless it is rolled back for some
1350** reason, the entire database file will be overwritten by the current
1351** transaction. This is used by VACUUM operations.
1352**
1353** <li>[[SQLITE_FCNTL_VFSNAME]]
1354** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1355** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1356** final bottom-level VFS are written into memory obtained from
1357** [sqlite3_malloc()] and the result is stored in the char* variable
1358** that the fourth parameter of [sqlite3_file_control()] points to.
1359** The caller is responsible for freeing the memory when done.  As with
1360** all file-control actions, there is no guarantee that this will actually
1361** do anything.  Callers should initialize the char* variable to a NULL
1362** pointer in case this file-control is not implemented.  This file-control
1363** is intended for diagnostic use only.
1364**
1365** <li>[[SQLITE_FCNTL_PRAGMA]]
1366** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1367** file control is sent to the open [sqlite3_file] object corresponding
1368** to the database file to which the pragma statement refers. ^The argument
1369** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1370** pointers to strings (char**) in which the second element of the array
1371** is the name of the pragma and the third element is the argument to the
1372** pragma or NULL if the pragma has no argument.  ^The handler for an
1373** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1374** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1375** or the equivalent and that string will become the result of the pragma or
1376** the error message if the pragma fails. ^If the
1377** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1378** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1379** file control returns [SQLITE_OK], then the parser assumes that the
1380** VFS has handled the PRAGMA itself and the parser generates a no-op
1381** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1382** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1383** that the VFS encountered an error while handling the [PRAGMA] and the
1384** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1385** file control occurs at the beginning of pragma statement analysis and so
1386** it is able to override built-in [PRAGMA] statements.
1387** </ul>
1388*/
1389#define SQLITE_FCNTL_LOCKSTATE               1
1390#define SQLITE_GET_LOCKPROXYFILE             2
1391#define SQLITE_SET_LOCKPROXYFILE             3
1392#define SQLITE_LAST_ERRNO                    4
1393#define SQLITE_FCNTL_SIZE_HINT               5
1394#define SQLITE_FCNTL_CHUNK_SIZE              6
1395#define SQLITE_FCNTL_FILE_POINTER            7
1396#define SQLITE_FCNTL_SYNC_OMITTED            8
1397#define SQLITE_FCNTL_WIN32_AV_RETRY          9
1398#define SQLITE_FCNTL_PERSIST_WAL            10
1399#define SQLITE_FCNTL_OVERWRITE              11
1400#define SQLITE_FCNTL_VFSNAME                12
1401#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1402#define SQLITE_FCNTL_PRAGMA                 14
1403
1404/*
1405** CAPI3REF: Mutex Handle
1406**
1407** The mutex module within SQLite defines [sqlite3_mutex] to be an
1408** abstract type for a mutex object.  The SQLite core never looks
1409** at the internal representation of an [sqlite3_mutex].  It only
1410** deals with pointers to the [sqlite3_mutex] object.
1411**
1412** Mutexes are created using [sqlite3_mutex_alloc()].
1413*/
1414typedef struct sqlite3_mutex sqlite3_mutex;
1415
1416/*
1417** CAPI3REF: OS Interface Object
1418**
1419** An instance of the sqlite3_vfs object defines the interface between
1420** the SQLite core and the underlying operating system.  The "vfs"
1421** in the name of the object stands for "virtual file system".  See
1422** the [VFS | VFS documentation] for further information.
1423**
1424** The value of the iVersion field is initially 1 but may be larger in
1425** future versions of SQLite.  Additional fields may be appended to this
1426** object when the iVersion value is increased.  Note that the structure
1427** of the sqlite3_vfs object changes in the transaction between
1428** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1429** modified.
1430**
1431** The szOsFile field is the size of the subclassed [sqlite3_file]
1432** structure used by this VFS.  mxPathname is the maximum length of
1433** a pathname in this VFS.
1434**
1435** Registered sqlite3_vfs objects are kept on a linked list formed by
1436** the pNext pointer.  The [sqlite3_vfs_register()]
1437** and [sqlite3_vfs_unregister()] interfaces manage this list
1438** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1439** searches the list.  Neither the application code nor the VFS
1440** implementation should use the pNext pointer.
1441**
1442** The pNext field is the only field in the sqlite3_vfs
1443** structure that SQLite will ever modify.  SQLite will only access
1444** or modify this field while holding a particular static mutex.
1445** The application should never modify anything within the sqlite3_vfs
1446** object once the object has been registered.
1447**
1448** The zName field holds the name of the VFS module.  The name must
1449** be unique across all VFS modules.
1450**
1451** [[sqlite3_vfs.xOpen]]
1452** ^SQLite guarantees that the zFilename parameter to xOpen
1453** is either a NULL pointer or string obtained
1454** from xFullPathname() with an optional suffix added.
1455** ^If a suffix is added to the zFilename parameter, it will
1456** consist of a single "-" character followed by no more than
1457** 11 alphanumeric and/or "-" characters.
1458** ^SQLite further guarantees that
1459** the string will be valid and unchanged until xClose() is
1460** called. Because of the previous sentence,
1461** the [sqlite3_file] can safely store a pointer to the
1462** filename if it needs to remember the filename for some reason.
1463** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1464** must invent its own temporary name for the file.  ^Whenever the
1465** xFilename parameter is NULL it will also be the case that the
1466** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1467**
1468** The flags argument to xOpen() includes all bits set in
1469** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1470** or [sqlite3_open16()] is used, then flags includes at least
1471** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1472** If xOpen() opens a file read-only then it sets *pOutFlags to
1473** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1474**
1475** ^(SQLite will also add one of the following flags to the xOpen()
1476** call, depending on the object being opened:
1477**
1478** <ul>
1479** <li>  [SQLITE_OPEN_MAIN_DB]
1480** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1481** <li>  [SQLITE_OPEN_TEMP_DB]
1482** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1483** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1484** <li>  [SQLITE_OPEN_SUBJOURNAL]
1485** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1486** <li>  [SQLITE_OPEN_WAL]
1487** </ul>)^
1488**
1489** The file I/O implementation can use the object type flags to
1490** change the way it deals with files.  For example, an application
1491** that does not care about crash recovery or rollback might make
1492** the open of a journal file a no-op.  Writes to this journal would
1493** also be no-ops, and any attempt to read the journal would return
1494** SQLITE_IOERR.  Or the implementation might recognize that a database
1495** file will be doing page-aligned sector reads and writes in a random
1496** order and set up its I/O subsystem accordingly.
1497**
1498** SQLite might also add one of the following flags to the xOpen method:
1499**
1500** <ul>
1501** <li> [SQLITE_OPEN_DELETEONCLOSE]
1502** <li> [SQLITE_OPEN_EXCLUSIVE]
1503** </ul>
1504**
1505** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1506** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1507** will be set for TEMP databases and their journals, transient
1508** databases, and subjournals.
1509**
1510** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1511** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1512** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1513** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1514** SQLITE_OPEN_CREATE, is used to indicate that file should always
1515** be created, and that it is an error if it already exists.
1516** It is <i>not</i> used to indicate the file should be opened
1517** for exclusive access.
1518**
1519** ^At least szOsFile bytes of memory are allocated by SQLite
1520** to hold the  [sqlite3_file] structure passed as the third
1521** argument to xOpen.  The xOpen method does not have to
1522** allocate the structure; it should just fill it in.  Note that
1523** the xOpen method must set the sqlite3_file.pMethods to either
1524** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1525** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1526** element will be valid after xOpen returns regardless of the success
1527** or failure of the xOpen call.
1528**
1529** [[sqlite3_vfs.xAccess]]
1530** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1531** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1532** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1533** to test whether a file is at least readable.   The file can be a
1534** directory.
1535**
1536** ^SQLite will always allocate at least mxPathname+1 bytes for the
1537** output buffer xFullPathname.  The exact size of the output buffer
1538** is also passed as a parameter to both  methods. If the output buffer
1539** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1540** handled as a fatal error by SQLite, vfs implementations should endeavor
1541** to prevent this by setting mxPathname to a sufficiently large value.
1542**
1543** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1544** interfaces are not strictly a part of the filesystem, but they are
1545** included in the VFS structure for completeness.
1546** The xRandomness() function attempts to return nBytes bytes
1547** of good-quality randomness into zOut.  The return value is
1548** the actual number of bytes of randomness obtained.
1549** The xSleep() method causes the calling thread to sleep for at
1550** least the number of microseconds given.  ^The xCurrentTime()
1551** method returns a Julian Day Number for the current date and time as
1552** a floating point value.
1553** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1554** Day Number multiplied by 86400000 (the number of milliseconds in
1555** a 24-hour day).
1556** ^SQLite will use the xCurrentTimeInt64() method to get the current
1557** date and time if that method is available (if iVersion is 2 or
1558** greater and the function pointer is not NULL) and will fall back
1559** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1560**
1561** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1562** are not used by the SQLite core.  These optional interfaces are provided
1563** by some VFSes to facilitate testing of the VFS code. By overriding
1564** system calls with functions under its control, a test program can
1565** simulate faults and error conditions that would otherwise be difficult
1566** or impossible to induce.  The set of system calls that can be overridden
1567** varies from one VFS to another, and from one version of the same VFS to the
1568** next.  Applications that use these interfaces must be prepared for any
1569** or all of these interfaces to be NULL or for their behavior to change
1570** from one release to the next.  Applications must not attempt to access
1571** any of these methods if the iVersion of the VFS is less than 3.
1572*/
1573typedef struct sqlite3_vfs sqlite3_vfs;
1574typedef void (*sqlite3_syscall_ptr)(void);
1575struct sqlite3_vfs {
1576  int iVersion;            /* Structure version number (currently 3) */
1577  int szOsFile;            /* Size of subclassed sqlite3_file */
1578  int mxPathname;          /* Maximum file pathname length */
1579  sqlite3_vfs *pNext;      /* Next registered VFS */
1580  const char *zName;       /* Name of this virtual file system */
1581  void *pAppData;          /* Pointer to application-specific data */
1582  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1583               int flags, int *pOutFlags);
1584  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1585  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1586  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1587  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1588  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1589  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1590  void (*xDlClose)(sqlite3_vfs*, void*);
1591  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1592  int (*xSleep)(sqlite3_vfs*, int microseconds);
1593  int (*xCurrentTime)(sqlite3_vfs*, double*);
1594  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1595  /*
1596  ** The methods above are in version 1 of the sqlite_vfs object
1597  ** definition.  Those that follow are added in version 2 or later
1598  */
1599  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1600  /*
1601  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1602  ** Those below are for version 3 and greater.
1603  */
1604  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1605  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1606  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1607  /*
1608  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1609  ** New fields may be appended in figure versions.  The iVersion
1610  ** value will increment whenever this happens.
1611  */
1612};
1613
1614/*
1615** CAPI3REF: Flags for the xAccess VFS method
1616**
1617** These integer constants can be used as the third parameter to
1618** the xAccess method of an [sqlite3_vfs] object.  They determine
1619** what kind of permissions the xAccess method is looking for.
1620** With SQLITE_ACCESS_EXISTS, the xAccess method
1621** simply checks whether the file exists.
1622** With SQLITE_ACCESS_READWRITE, the xAccess method
1623** checks whether the named directory is both readable and writable
1624** (in other words, if files can be added, removed, and renamed within
1625** the directory).
1626** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1627** [temp_store_directory pragma], though this could change in a future
1628** release of SQLite.
1629** With SQLITE_ACCESS_READ, the xAccess method
1630** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1631** currently unused, though it might be used in a future release of
1632** SQLite.
1633*/
1634#define SQLITE_ACCESS_EXISTS    0
1635#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1636#define SQLITE_ACCESS_READ      2   /* Unused */
1637
1638/*
1639** CAPI3REF: Flags for the xShmLock VFS method
1640**
1641** These integer constants define the various locking operations
1642** allowed by the xShmLock method of [sqlite3_io_methods].  The
1643** following are the only legal combinations of flags to the
1644** xShmLock method:
1645**
1646** <ul>
1647** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1648** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1649** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1650** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1651** </ul>
1652**
1653** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1654** was given no the corresponding lock.
1655**
1656** The xShmLock method can transition between unlocked and SHARED or
1657** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1658** and EXCLUSIVE.
1659*/
1660#define SQLITE_SHM_UNLOCK       1
1661#define SQLITE_SHM_LOCK         2
1662#define SQLITE_SHM_SHARED       4
1663#define SQLITE_SHM_EXCLUSIVE    8
1664
1665/*
1666** CAPI3REF: Maximum xShmLock index
1667**
1668** The xShmLock method on [sqlite3_io_methods] may use values
1669** between 0 and this upper bound as its "offset" argument.
1670** The SQLite core will never attempt to acquire or release a
1671** lock outside of this range
1672*/
1673#define SQLITE_SHM_NLOCK        8
1674
1675
1676/*
1677** CAPI3REF: Initialize The SQLite Library
1678**
1679** ^The sqlite3_initialize() routine initializes the
1680** SQLite library.  ^The sqlite3_shutdown() routine
1681** deallocates any resources that were allocated by sqlite3_initialize().
1682** These routines are designed to aid in process initialization and
1683** shutdown on embedded systems.  Workstation applications using
1684** SQLite normally do not need to invoke either of these routines.
1685**
1686** A call to sqlite3_initialize() is an "effective" call if it is
1687** the first time sqlite3_initialize() is invoked during the lifetime of
1688** the process, or if it is the first time sqlite3_initialize() is invoked
1689** following a call to sqlite3_shutdown().  ^(Only an effective call
1690** of sqlite3_initialize() does any initialization.  All other calls
1691** are harmless no-ops.)^
1692**
1693** A call to sqlite3_shutdown() is an "effective" call if it is the first
1694** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1695** an effective call to sqlite3_shutdown() does any deinitialization.
1696** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1697**
1698** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1699** is not.  The sqlite3_shutdown() interface must only be called from a
1700** single thread.  All open [database connections] must be closed and all
1701** other SQLite resources must be deallocated prior to invoking
1702** sqlite3_shutdown().
1703**
1704** Among other things, ^sqlite3_initialize() will invoke
1705** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1706** will invoke sqlite3_os_end().
1707**
1708** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1709** ^If for some reason, sqlite3_initialize() is unable to initialize
1710** the library (perhaps it is unable to allocate a needed resource such
1711** as a mutex) it returns an [error code] other than [SQLITE_OK].
1712**
1713** ^The sqlite3_initialize() routine is called internally by many other
1714** SQLite interfaces so that an application usually does not need to
1715** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1716** calls sqlite3_initialize() so the SQLite library will be automatically
1717** initialized when [sqlite3_open()] is called if it has not be initialized
1718** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1719** compile-time option, then the automatic calls to sqlite3_initialize()
1720** are omitted and the application must call sqlite3_initialize() directly
1721** prior to using any other SQLite interface.  For maximum portability,
1722** it is recommended that applications always invoke sqlite3_initialize()
1723** directly prior to using any other SQLite interface.  Future releases
1724** of SQLite may require this.  In other words, the behavior exhibited
1725** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1726** default behavior in some future release of SQLite.
1727**
1728** The sqlite3_os_init() routine does operating-system specific
1729** initialization of the SQLite library.  The sqlite3_os_end()
1730** routine undoes the effect of sqlite3_os_init().  Typical tasks
1731** performed by these routines include allocation or deallocation
1732** of static resources, initialization of global variables,
1733** setting up a default [sqlite3_vfs] module, or setting up
1734** a default configuration using [sqlite3_config()].
1735**
1736** The application should never invoke either sqlite3_os_init()
1737** or sqlite3_os_end() directly.  The application should only invoke
1738** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1739** interface is called automatically by sqlite3_initialize() and
1740** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1741** implementations for sqlite3_os_init() and sqlite3_os_end()
1742** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1743** When [custom builds | built for other platforms]
1744** (using the [SQLITE_OS_OTHER=1] compile-time
1745** option) the application must supply a suitable implementation for
1746** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1747** implementation of sqlite3_os_init() or sqlite3_os_end()
1748** must return [SQLITE_OK] on success and some other [error code] upon
1749** failure.
1750*/
1751SQLITE_API int sqlite3_initialize(void);
1752SQLITE_API int sqlite3_shutdown(void);
1753SQLITE_API int sqlite3_os_init(void);
1754SQLITE_API int sqlite3_os_end(void);
1755
1756/*
1757** CAPI3REF: Configuring The SQLite Library
1758**
1759** The sqlite3_config() interface is used to make global configuration
1760** changes to SQLite in order to tune SQLite to the specific needs of
1761** the application.  The default configuration is recommended for most
1762** applications and so this routine is usually not necessary.  It is
1763** provided to support rare applications with unusual needs.
1764**
1765** The sqlite3_config() interface is not threadsafe.  The application
1766** must insure that no other SQLite interfaces are invoked by other
1767** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1768** may only be invoked prior to library initialization using
1769** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1770** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1771** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1772** Note, however, that ^sqlite3_config() can be called as part of the
1773** implementation of an application-defined [sqlite3_os_init()].
1774**
1775** The first argument to sqlite3_config() is an integer
1776** [configuration option] that determines
1777** what property of SQLite is to be configured.  Subsequent arguments
1778** vary depending on the [configuration option]
1779** in the first argument.
1780**
1781** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1782** ^If the option is unknown or SQLite is unable to set the option
1783** then this routine returns a non-zero [error code].
1784*/
1785SQLITE_API int sqlite3_config(int, ...);
1786
1787/*
1788** CAPI3REF: Configure database connections
1789**
1790** The sqlite3_db_config() interface is used to make configuration
1791** changes to a [database connection].  The interface is similar to
1792** [sqlite3_config()] except that the changes apply to a single
1793** [database connection] (specified in the first argument).
1794**
1795** The second argument to sqlite3_db_config(D,V,...)  is the
1796** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1797** that indicates what aspect of the [database connection] is being configured.
1798** Subsequent arguments vary depending on the configuration verb.
1799**
1800** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1801** the call is considered successful.
1802*/
1803SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1804
1805/*
1806** CAPI3REF: Memory Allocation Routines
1807**
1808** An instance of this object defines the interface between SQLite
1809** and low-level memory allocation routines.
1810**
1811** This object is used in only one place in the SQLite interface.
1812** A pointer to an instance of this object is the argument to
1813** [sqlite3_config()] when the configuration option is
1814** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1815** By creating an instance of this object
1816** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1817** during configuration, an application can specify an alternative
1818** memory allocation subsystem for SQLite to use for all of its
1819** dynamic memory needs.
1820**
1821** Note that SQLite comes with several [built-in memory allocators]
1822** that are perfectly adequate for the overwhelming majority of applications
1823** and that this object is only useful to a tiny minority of applications
1824** with specialized memory allocation requirements.  This object is
1825** also used during testing of SQLite in order to specify an alternative
1826** memory allocator that simulates memory out-of-memory conditions in
1827** order to verify that SQLite recovers gracefully from such
1828** conditions.
1829**
1830** The xMalloc, xRealloc, and xFree methods must work like the
1831** malloc(), realloc() and free() functions from the standard C library.
1832** ^SQLite guarantees that the second argument to
1833** xRealloc is always a value returned by a prior call to xRoundup.
1834**
1835** xSize should return the allocated size of a memory allocation
1836** previously obtained from xMalloc or xRealloc.  The allocated size
1837** is always at least as big as the requested size but may be larger.
1838**
1839** The xRoundup method returns what would be the allocated size of
1840** a memory allocation given a particular requested size.  Most memory
1841** allocators round up memory allocations at least to the next multiple
1842** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1843** Every memory allocation request coming in through [sqlite3_malloc()]
1844** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1845** that causes the corresponding memory allocation to fail.
1846**
1847** The xInit method initializes the memory allocator.  (For example,
1848** it might allocate any require mutexes or initialize internal data
1849** structures.  The xShutdown method is invoked (indirectly) by
1850** [sqlite3_shutdown()] and should deallocate any resources acquired
1851** by xInit.  The pAppData pointer is used as the only parameter to
1852** xInit and xShutdown.
1853**
1854** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1855** the xInit method, so the xInit method need not be threadsafe.  The
1856** xShutdown method is only called from [sqlite3_shutdown()] so it does
1857** not need to be threadsafe either.  For all other methods, SQLite
1858** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1859** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1860** it is by default) and so the methods are automatically serialized.
1861** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1862** methods must be threadsafe or else make their own arrangements for
1863** serialization.
1864**
1865** SQLite will never invoke xInit() more than once without an intervening
1866** call to xShutdown().
1867*/
1868typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1869struct sqlite3_mem_methods {
1870  void *(*xMalloc)(int);         /* Memory allocation function */
1871  void (*xFree)(void*);          /* Free a prior allocation */
1872  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1873  int (*xSize)(void*);           /* Return the size of an allocation */
1874  int (*xRoundup)(int);          /* Round up request size to allocation size */
1875  int (*xInit)(void*);           /* Initialize the memory allocator */
1876  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1877  void *pAppData;                /* Argument to xInit() and xShutdown() */
1878};
1879
1880/*
1881** CAPI3REF: Configuration Options
1882** KEYWORDS: {configuration option}
1883**
1884** These constants are the available integer configuration options that
1885** can be passed as the first argument to the [sqlite3_config()] interface.
1886**
1887** New configuration options may be added in future releases of SQLite.
1888** Existing configuration options might be discontinued.  Applications
1889** should check the return code from [sqlite3_config()] to make sure that
1890** the call worked.  The [sqlite3_config()] interface will return a
1891** non-zero [error code] if a discontinued or unsupported configuration option
1892** is invoked.
1893**
1894** <dl>
1895** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1896** <dd>There are no arguments to this option.  ^This option sets the
1897** [threading mode] to Single-thread.  In other words, it disables
1898** all mutexing and puts SQLite into a mode where it can only be used
1899** by a single thread.   ^If SQLite is compiled with
1900** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1901** it is not possible to change the [threading mode] from its default
1902** value of Single-thread and so [sqlite3_config()] will return
1903** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1904** configuration option.</dd>
1905**
1906** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1907** <dd>There are no arguments to this option.  ^This option sets the
1908** [threading mode] to Multi-thread.  In other words, it disables
1909** mutexing on [database connection] and [prepared statement] objects.
1910** The application is responsible for serializing access to
1911** [database connections] and [prepared statements].  But other mutexes
1912** are enabled so that SQLite will be safe to use in a multi-threaded
1913** environment as long as no two threads attempt to use the same
1914** [database connection] at the same time.  ^If SQLite is compiled with
1915** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1916** it is not possible to set the Multi-thread [threading mode] and
1917** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1918** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1919**
1920** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1921** <dd>There are no arguments to this option.  ^This option sets the
1922** [threading mode] to Serialized. In other words, this option enables
1923** all mutexes including the recursive
1924** mutexes on [database connection] and [prepared statement] objects.
1925** In this mode (which is the default when SQLite is compiled with
1926** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1927** to [database connections] and [prepared statements] so that the
1928** application is free to use the same [database connection] or the
1929** same [prepared statement] in different threads at the same time.
1930** ^If SQLite is compiled with
1931** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1932** it is not possible to set the Serialized [threading mode] and
1933** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1934** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1935**
1936** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1937** <dd> ^(This option takes a single argument which is a pointer to an
1938** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1939** alternative low-level memory allocation routines to be used in place of
1940** the memory allocation routines built into SQLite.)^ ^SQLite makes
1941** its own private copy of the content of the [sqlite3_mem_methods] structure
1942** before the [sqlite3_config()] call returns.</dd>
1943**
1944** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1945** <dd> ^(This option takes a single argument which is a pointer to an
1946** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1947** structure is filled with the currently defined memory allocation routines.)^
1948** This option can be used to overload the default memory allocation
1949** routines with a wrapper that simulations memory allocation failure or
1950** tracks memory usage, for example. </dd>
1951**
1952** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1953** <dd> ^This option takes single argument of type int, interpreted as a
1954** boolean, which enables or disables the collection of memory allocation
1955** statistics. ^(When memory allocation statistics are disabled, the
1956** following SQLite interfaces become non-operational:
1957**   <ul>
1958**   <li> [sqlite3_memory_used()]
1959**   <li> [sqlite3_memory_highwater()]
1960**   <li> [sqlite3_soft_heap_limit64()]
1961**   <li> [sqlite3_status()]
1962**   </ul>)^
1963** ^Memory allocation statistics are enabled by default unless SQLite is
1964** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1965** allocation statistics are disabled by default.
1966** </dd>
1967**
1968** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1969** <dd> ^This option specifies a static memory buffer that SQLite can use for
1970** scratch memory.  There are three arguments:  A pointer an 8-byte
1971** aligned memory buffer from which the scratch allocations will be
1972** drawn, the size of each scratch allocation (sz),
1973** and the maximum number of scratch allocations (N).  The sz
1974** argument must be a multiple of 16.
1975** The first argument must be a pointer to an 8-byte aligned buffer
1976** of at least sz*N bytes of memory.
1977** ^SQLite will use no more than two scratch buffers per thread.  So
1978** N should be set to twice the expected maximum number of threads.
1979** ^SQLite will never require a scratch buffer that is more than 6
1980** times the database page size. ^If SQLite needs needs additional
1981** scratch memory beyond what is provided by this configuration option, then
1982** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1983**
1984** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1985** <dd> ^This option specifies a static memory buffer that SQLite can use for
1986** the database page cache with the default page cache implementation.
1987** This configuration should not be used if an application-define page
1988** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
1989** There are three arguments to this option: A pointer to 8-byte aligned
1990** memory, the size of each page buffer (sz), and the number of pages (N).
1991** The sz argument should be the size of the largest database page
1992** (a power of two between 512 and 32768) plus a little extra for each
1993** page header.  ^The page header size is 20 to 40 bytes depending on
1994** the host architecture.  ^It is harmless, apart from the wasted memory,
1995** to make sz a little too large.  The first
1996** argument should point to an allocation of at least sz*N bytes of memory.
1997** ^SQLite will use the memory provided by the first argument to satisfy its
1998** memory needs for the first N pages that it adds to cache.  ^If additional
1999** page cache memory is needed beyond what is provided by this option, then
2000** SQLite goes to [sqlite3_malloc()] for the additional storage space.
2001** The pointer in the first argument must
2002** be aligned to an 8-byte boundary or subsequent behavior of SQLite
2003** will be undefined.</dd>
2004**
2005** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2006** <dd> ^This option specifies a static memory buffer that SQLite will use
2007** for all of its dynamic memory allocation needs beyond those provided
2008** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
2009** There are three arguments: An 8-byte aligned pointer to the memory,
2010** the number of bytes in the memory buffer, and the minimum allocation size.
2011** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2012** to using its default memory allocator (the system malloc() implementation),
2013** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
2014** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
2015** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
2016** allocator is engaged to handle all of SQLites memory allocation needs.
2017** The first pointer (the memory pointer) must be aligned to an 8-byte
2018** boundary or subsequent behavior of SQLite will be undefined.
2019** The minimum allocation size is capped at 2**12. Reasonable values
2020** for the minimum allocation size are 2**5 through 2**8.</dd>
2021**
2022** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2023** <dd> ^(This option takes a single argument which is a pointer to an
2024** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
2025** alternative low-level mutex routines to be used in place
2026** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
2027** content of the [sqlite3_mutex_methods] structure before the call to
2028** [sqlite3_config()] returns. ^If SQLite is compiled with
2029** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2030** the entire mutexing subsystem is omitted from the build and hence calls to
2031** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2032** return [SQLITE_ERROR].</dd>
2033**
2034** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2035** <dd> ^(This option takes a single argument which is a pointer to an
2036** instance of the [sqlite3_mutex_methods] structure.  The
2037** [sqlite3_mutex_methods]
2038** structure is filled with the currently defined mutex routines.)^
2039** This option can be used to overload the default mutex allocation
2040** routines with a wrapper used to track mutex usage for performance
2041** profiling or testing, for example.   ^If SQLite is compiled with
2042** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2043** the entire mutexing subsystem is omitted from the build and hence calls to
2044** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2045** return [SQLITE_ERROR].</dd>
2046**
2047** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2048** <dd> ^(This option takes two arguments that determine the default
2049** memory allocation for the lookaside memory allocator on each
2050** [database connection].  The first argument is the
2051** size of each lookaside buffer slot and the second is the number of
2052** slots allocated to each database connection.)^  ^(This option sets the
2053** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2054** verb to [sqlite3_db_config()] can be used to change the lookaside
2055** configuration on individual connections.)^ </dd>
2056**
2057** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2058** <dd> ^(This option takes a single argument which is a pointer to
2059** an [sqlite3_pcache_methods2] object.  This object specifies the interface
2060** to a custom page cache implementation.)^  ^SQLite makes a copy of the
2061** object and uses it for page cache memory allocations.</dd>
2062**
2063** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2064** <dd> ^(This option takes a single argument which is a pointer to an
2065** [sqlite3_pcache_methods2] object.  SQLite copies of the current
2066** page cache implementation into that object.)^ </dd>
2067**
2068** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2069** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2070** function with a call signature of void(*)(void*,int,const char*),
2071** and a pointer to void. ^If the function pointer is not NULL, it is
2072** invoked by [sqlite3_log()] to process each logging event.  ^If the
2073** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2074** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2075** passed through as the first parameter to the application-defined logger
2076** function whenever that function is invoked.  ^The second parameter to
2077** the logger function is a copy of the first parameter to the corresponding
2078** [sqlite3_log()] call and is intended to be a [result code] or an
2079** [extended result code].  ^The third parameter passed to the logger is
2080** log message after formatting via [sqlite3_snprintf()].
2081** The SQLite logging interface is not reentrant; the logger function
2082** supplied by the application must not invoke any SQLite interface.
2083** In a multi-threaded application, the application-defined logger
2084** function must be threadsafe. </dd>
2085**
2086** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2087** <dd> This option takes a single argument of type int. If non-zero, then
2088** URI handling is globally enabled. If the parameter is zero, then URI handling
2089** is globally disabled. If URI handling is globally enabled, all filenames
2090** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2091** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2092** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2093** connection is opened. If it is globally disabled, filenames are
2094** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2095** database connection is opened. By default, URI handling is globally
2096** disabled. The default value may be changed by compiling with the
2097** [SQLITE_USE_URI] symbol defined.
2098**
2099** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2100** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFNIG_GETPCACHE
2101** <dd> These options are obsolete and should not be used by new code.
2102** They are retained for backwards compatibility but are now no-ops.
2103** </dl>
2104*/
2105#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2106#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2107#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2108#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2109#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2110#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2111#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2112#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2113#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2114#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2115#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2116/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2117#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2118#define SQLITE_CONFIG_PCACHE       14  /* no-op */
2119#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2120#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2121#define SQLITE_CONFIG_URI          17  /* int */
2122#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2123#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2124
2125/*
2126** CAPI3REF: Database Connection Configuration Options
2127**
2128** These constants are the available integer configuration options that
2129** can be passed as the second argument to the [sqlite3_db_config()] interface.
2130**
2131** New configuration options may be added in future releases of SQLite.
2132** Existing configuration options might be discontinued.  Applications
2133** should check the return code from [sqlite3_db_config()] to make sure that
2134** the call worked.  ^The [sqlite3_db_config()] interface will return a
2135** non-zero [error code] if a discontinued or unsupported configuration option
2136** is invoked.
2137**
2138** <dl>
2139** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2140** <dd> ^This option takes three additional arguments that determine the
2141** [lookaside memory allocator] configuration for the [database connection].
2142** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2143** pointer to a memory buffer to use for lookaside memory.
2144** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2145** may be NULL in which case SQLite will allocate the
2146** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2147** size of each lookaside buffer slot.  ^The third argument is the number of
2148** slots.  The size of the buffer in the first argument must be greater than
2149** or equal to the product of the second and third arguments.  The buffer
2150** must be aligned to an 8-byte boundary.  ^If the second argument to
2151** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2152** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2153** configuration for a database connection can only be changed when that
2154** connection is not currently using lookaside memory, or in other words
2155** when the "current value" returned by
2156** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2157** Any attempt to change the lookaside memory configuration when lookaside
2158** memory is in use leaves the configuration unchanged and returns
2159** [SQLITE_BUSY].)^</dd>
2160**
2161** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2162** <dd> ^This option is used to enable or disable the enforcement of
2163** [foreign key constraints].  There should be two additional arguments.
2164** The first argument is an integer which is 0 to disable FK enforcement,
2165** positive to enable FK enforcement or negative to leave FK enforcement
2166** unchanged.  The second parameter is a pointer to an integer into which
2167** is written 0 or 1 to indicate whether FK enforcement is off or on
2168** following this call.  The second parameter may be a NULL pointer, in
2169** which case the FK enforcement setting is not reported back. </dd>
2170**
2171** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2172** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2173** There should be two additional arguments.
2174** The first argument is an integer which is 0 to disable triggers,
2175** positive to enable triggers or negative to leave the setting unchanged.
2176** The second parameter is a pointer to an integer into which
2177** is written 0 or 1 to indicate whether triggers are disabled or enabled
2178** following this call.  The second parameter may be a NULL pointer, in
2179** which case the trigger setting is not reported back. </dd>
2180**
2181** </dl>
2182*/
2183#define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2184#define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2185#define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2186
2187
2188/*
2189** CAPI3REF: Enable Or Disable Extended Result Codes
2190**
2191** ^The sqlite3_extended_result_codes() routine enables or disables the
2192** [extended result codes] feature of SQLite. ^The extended result
2193** codes are disabled by default for historical compatibility.
2194*/
2195SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2196
2197/*
2198** CAPI3REF: Last Insert Rowid
2199**
2200** ^Each entry in an SQLite table has a unique 64-bit signed
2201** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2202** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2203** names are not also used by explicitly declared columns. ^If
2204** the table has a column of type [INTEGER PRIMARY KEY] then that column
2205** is another alias for the rowid.
2206**
2207** ^This routine returns the [rowid] of the most recent
2208** successful [INSERT] into the database from the [database connection]
2209** in the first argument.  ^As of SQLite version 3.7.7, this routines
2210** records the last insert rowid of both ordinary tables and [virtual tables].
2211** ^If no successful [INSERT]s
2212** have ever occurred on that database connection, zero is returned.
2213**
2214** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2215** method, then this routine will return the [rowid] of the inserted
2216** row as long as the trigger or virtual table method is running.
2217** But once the trigger or virtual table method ends, the value returned
2218** by this routine reverts to what it was before the trigger or virtual
2219** table method began.)^
2220**
2221** ^An [INSERT] that fails due to a constraint violation is not a
2222** successful [INSERT] and does not change the value returned by this
2223** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2224** and INSERT OR ABORT make no changes to the return value of this
2225** routine when their insertion fails.  ^(When INSERT OR REPLACE
2226** encounters a constraint violation, it does not fail.  The
2227** INSERT continues to completion after deleting rows that caused
2228** the constraint problem so INSERT OR REPLACE will always change
2229** the return value of this interface.)^
2230**
2231** ^For the purposes of this routine, an [INSERT] is considered to
2232** be successful even if it is subsequently rolled back.
2233**
2234** This function is accessible to SQL statements via the
2235** [last_insert_rowid() SQL function].
2236**
2237** If a separate thread performs a new [INSERT] on the same
2238** database connection while the [sqlite3_last_insert_rowid()]
2239** function is running and thus changes the last insert [rowid],
2240** then the value returned by [sqlite3_last_insert_rowid()] is
2241** unpredictable and might not equal either the old or the new
2242** last insert [rowid].
2243*/
2244SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2245
2246/*
2247** CAPI3REF: Count The Number Of Rows Modified
2248**
2249** ^This function returns the number of database rows that were changed
2250** or inserted or deleted by the most recently completed SQL statement
2251** on the [database connection] specified by the first parameter.
2252** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2253** or [DELETE] statement are counted.  Auxiliary changes caused by
2254** triggers or [foreign key actions] are not counted.)^ Use the
2255** [sqlite3_total_changes()] function to find the total number of changes
2256** including changes caused by triggers and foreign key actions.
2257**
2258** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2259** are not counted.  Only real table changes are counted.
2260**
2261** ^(A "row change" is a change to a single row of a single table
2262** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2263** are changed as side effects of [REPLACE] constraint resolution,
2264** rollback, ABORT processing, [DROP TABLE], or by any other
2265** mechanisms do not count as direct row changes.)^
2266**
2267** A "trigger context" is a scope of execution that begins and
2268** ends with the script of a [CREATE TRIGGER | trigger].
2269** Most SQL statements are
2270** evaluated outside of any trigger.  This is the "top level"
2271** trigger context.  If a trigger fires from the top level, a
2272** new trigger context is entered for the duration of that one
2273** trigger.  Subtriggers create subcontexts for their duration.
2274**
2275** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2276** not create a new trigger context.
2277**
2278** ^This function returns the number of direct row changes in the
2279** most recent INSERT, UPDATE, or DELETE statement within the same
2280** trigger context.
2281**
2282** ^Thus, when called from the top level, this function returns the
2283** number of changes in the most recent INSERT, UPDATE, or DELETE
2284** that also occurred at the top level.  ^(Within the body of a trigger,
2285** the sqlite3_changes() interface can be called to find the number of
2286** changes in the most recently completed INSERT, UPDATE, or DELETE
2287** statement within the body of the same trigger.
2288** However, the number returned does not include changes
2289** caused by subtriggers since those have their own context.)^
2290**
2291** See also the [sqlite3_total_changes()] interface, the
2292** [count_changes pragma], and the [changes() SQL function].
2293**
2294** If a separate thread makes changes on the same database connection
2295** while [sqlite3_changes()] is running then the value returned
2296** is unpredictable and not meaningful.
2297*/
2298SQLITE_API int sqlite3_changes(sqlite3*);
2299
2300/*
2301** CAPI3REF: Total Number Of Rows Modified
2302**
2303** ^This function returns the number of row changes caused by [INSERT],
2304** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2305** ^(The count returned by sqlite3_total_changes() includes all changes
2306** from all [CREATE TRIGGER | trigger] contexts and changes made by
2307** [foreign key actions]. However,
2308** the count does not include changes used to implement [REPLACE] constraints,
2309** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2310** count does not include rows of views that fire an [INSTEAD OF trigger],
2311** though if the INSTEAD OF trigger makes changes of its own, those changes
2312** are counted.)^
2313** ^The sqlite3_total_changes() function counts the changes as soon as
2314** the statement that makes them is completed (when the statement handle
2315** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2316**
2317** See also the [sqlite3_changes()] interface, the
2318** [count_changes pragma], and the [total_changes() SQL function].
2319**
2320** If a separate thread makes changes on the same database connection
2321** while [sqlite3_total_changes()] is running then the value
2322** returned is unpredictable and not meaningful.
2323*/
2324SQLITE_API int sqlite3_total_changes(sqlite3*);
2325
2326/*
2327** CAPI3REF: Interrupt A Long-Running Query
2328**
2329** ^This function causes any pending database operation to abort and
2330** return at its earliest opportunity. This routine is typically
2331** called in response to a user action such as pressing "Cancel"
2332** or Ctrl-C where the user wants a long query operation to halt
2333** immediately.
2334**
2335** ^It is safe to call this routine from a thread different from the
2336** thread that is currently running the database operation.  But it
2337** is not safe to call this routine with a [database connection] that
2338** is closed or might close before sqlite3_interrupt() returns.
2339**
2340** ^If an SQL operation is very nearly finished at the time when
2341** sqlite3_interrupt() is called, then it might not have an opportunity
2342** to be interrupted and might continue to completion.
2343**
2344** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2345** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2346** that is inside an explicit transaction, then the entire transaction
2347** will be rolled back automatically.
2348**
2349** ^The sqlite3_interrupt(D) call is in effect until all currently running
2350** SQL statements on [database connection] D complete.  ^Any new SQL statements
2351** that are started after the sqlite3_interrupt() call and before the
2352** running statements reaches zero are interrupted as if they had been
2353** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2354** that are started after the running statement count reaches zero are
2355** not effected by the sqlite3_interrupt().
2356** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2357** SQL statements is a no-op and has no effect on SQL statements
2358** that are started after the sqlite3_interrupt() call returns.
2359**
2360** If the database connection closes while [sqlite3_interrupt()]
2361** is running then bad things will likely happen.
2362*/
2363SQLITE_API void sqlite3_interrupt(sqlite3*);
2364
2365/*
2366** CAPI3REF: Determine If An SQL Statement Is Complete
2367**
2368** These routines are useful during command-line input to determine if the
2369** currently entered text seems to form a complete SQL statement or
2370** if additional input is needed before sending the text into
2371** SQLite for parsing.  ^These routines return 1 if the input string
2372** appears to be a complete SQL statement.  ^A statement is judged to be
2373** complete if it ends with a semicolon token and is not a prefix of a
2374** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2375** string literals or quoted identifier names or comments are not
2376** independent tokens (they are part of the token in which they are
2377** embedded) and thus do not count as a statement terminator.  ^Whitespace
2378** and comments that follow the final semicolon are ignored.
2379**
2380** ^These routines return 0 if the statement is incomplete.  ^If a
2381** memory allocation fails, then SQLITE_NOMEM is returned.
2382**
2383** ^These routines do not parse the SQL statements thus
2384** will not detect syntactically incorrect SQL.
2385**
2386** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2387** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2388** automatically by sqlite3_complete16().  If that initialization fails,
2389** then the return value from sqlite3_complete16() will be non-zero
2390** regardless of whether or not the input SQL is complete.)^
2391**
2392** The input to [sqlite3_complete()] must be a zero-terminated
2393** UTF-8 string.
2394**
2395** The input to [sqlite3_complete16()] must be a zero-terminated
2396** UTF-16 string in native byte order.
2397*/
2398SQLITE_API int sqlite3_complete(const char *sql);
2399SQLITE_API int sqlite3_complete16(const void *sql);
2400
2401/*
2402** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2403**
2404** ^This routine sets a callback function that might be invoked whenever
2405** an attempt is made to open a database table that another thread
2406** or process has locked.
2407**
2408** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2409** is returned immediately upon encountering the lock.  ^If the busy callback
2410** is not NULL, then the callback might be invoked with two arguments.
2411**
2412** ^The first argument to the busy handler is a copy of the void* pointer which
2413** is the third argument to sqlite3_busy_handler().  ^The second argument to
2414** the busy handler callback is the number of times that the busy handler has
2415** been invoked for this locking event.  ^If the
2416** busy callback returns 0, then no additional attempts are made to
2417** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2418** ^If the callback returns non-zero, then another attempt
2419** is made to open the database for reading and the cycle repeats.
2420**
2421** The presence of a busy handler does not guarantee that it will be invoked
2422** when there is lock contention. ^If SQLite determines that invoking the busy
2423** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2424** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2425** Consider a scenario where one process is holding a read lock that
2426** it is trying to promote to a reserved lock and
2427** a second process is holding a reserved lock that it is trying
2428** to promote to an exclusive lock.  The first process cannot proceed
2429** because it is blocked by the second and the second process cannot
2430** proceed because it is blocked by the first.  If both processes
2431** invoke the busy handlers, neither will make any progress.  Therefore,
2432** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2433** will induce the first process to release its read lock and allow
2434** the second process to proceed.
2435**
2436** ^The default busy callback is NULL.
2437**
2438** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2439** when SQLite is in the middle of a large transaction where all the
2440** changes will not fit into the in-memory cache.  SQLite will
2441** already hold a RESERVED lock on the database file, but it needs
2442** to promote this lock to EXCLUSIVE so that it can spill cache
2443** pages into the database file without harm to concurrent
2444** readers.  ^If it is unable to promote the lock, then the in-memory
2445** cache will be left in an inconsistent state and so the error
2446** code is promoted from the relatively benign [SQLITE_BUSY] to
2447** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2448** forces an automatic rollback of the changes.  See the
2449** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2450** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2451** this is important.
2452**
2453** ^(There can only be a single busy handler defined for each
2454** [database connection].  Setting a new busy handler clears any
2455** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2456** will also set or clear the busy handler.
2457**
2458** The busy callback should not take any actions which modify the
2459** database connection that invoked the busy handler.  Any such actions
2460** result in undefined behavior.
2461**
2462** A busy handler must not close the database connection
2463** or [prepared statement] that invoked the busy handler.
2464*/
2465SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2466
2467/*
2468** CAPI3REF: Set A Busy Timeout
2469**
2470** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2471** for a specified amount of time when a table is locked.  ^The handler
2472** will sleep multiple times until at least "ms" milliseconds of sleeping
2473** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2474** the handler returns 0 which causes [sqlite3_step()] to return
2475** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2476**
2477** ^Calling this routine with an argument less than or equal to zero
2478** turns off all busy handlers.
2479**
2480** ^(There can only be a single busy handler for a particular
2481** [database connection] any any given moment.  If another busy handler
2482** was defined  (using [sqlite3_busy_handler()]) prior to calling
2483** this routine, that other busy handler is cleared.)^
2484*/
2485SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2486
2487/*
2488** CAPI3REF: Convenience Routines For Running Queries
2489**
2490** This is a legacy interface that is preserved for backwards compatibility.
2491** Use of this interface is not recommended.
2492**
2493** Definition: A <b>result table</b> is memory data structure created by the
2494** [sqlite3_get_table()] interface.  A result table records the
2495** complete query results from one or more queries.
2496**
2497** The table conceptually has a number of rows and columns.  But
2498** these numbers are not part of the result table itself.  These
2499** numbers are obtained separately.  Let N be the number of rows
2500** and M be the number of columns.
2501**
2502** A result table is an array of pointers to zero-terminated UTF-8 strings.
2503** There are (N+1)*M elements in the array.  The first M pointers point
2504** to zero-terminated strings that  contain the names of the columns.
2505** The remaining entries all point to query results.  NULL values result
2506** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2507** string representation as returned by [sqlite3_column_text()].
2508**
2509** A result table might consist of one or more memory allocations.
2510** It is not safe to pass a result table directly to [sqlite3_free()].
2511** A result table should be deallocated using [sqlite3_free_table()].
2512**
2513** ^(As an example of the result table format, suppose a query result
2514** is as follows:
2515**
2516** <blockquote><pre>
2517**        Name        | Age
2518**        -----------------------
2519**        Alice       | 43
2520**        Bob         | 28
2521**        Cindy       | 21
2522** </pre></blockquote>
2523**
2524** There are two column (M==2) and three rows (N==3).  Thus the
2525** result table has 8 entries.  Suppose the result table is stored
2526** in an array names azResult.  Then azResult holds this content:
2527**
2528** <blockquote><pre>
2529**        azResult&#91;0] = "Name";
2530**        azResult&#91;1] = "Age";
2531**        azResult&#91;2] = "Alice";
2532**        azResult&#91;3] = "43";
2533**        azResult&#91;4] = "Bob";
2534**        azResult&#91;5] = "28";
2535**        azResult&#91;6] = "Cindy";
2536**        azResult&#91;7] = "21";
2537** </pre></blockquote>)^
2538**
2539** ^The sqlite3_get_table() function evaluates one or more
2540** semicolon-separated SQL statements in the zero-terminated UTF-8
2541** string of its 2nd parameter and returns a result table to the
2542** pointer given in its 3rd parameter.
2543**
2544** After the application has finished with the result from sqlite3_get_table(),
2545** it must pass the result table pointer to sqlite3_free_table() in order to
2546** release the memory that was malloced.  Because of the way the
2547** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2548** function must not try to call [sqlite3_free()] directly.  Only
2549** [sqlite3_free_table()] is able to release the memory properly and safely.
2550**
2551** The sqlite3_get_table() interface is implemented as a wrapper around
2552** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2553** to any internal data structures of SQLite.  It uses only the public
2554** interface defined here.  As a consequence, errors that occur in the
2555** wrapper layer outside of the internal [sqlite3_exec()] call are not
2556** reflected in subsequent calls to [sqlite3_errcode()] or
2557** [sqlite3_errmsg()].
2558*/
2559SQLITE_API int sqlite3_get_table(
2560  sqlite3 *db,          /* An open database */
2561  const char *zSql,     /* SQL to be evaluated */
2562  char ***pazResult,    /* Results of the query */
2563  int *pnRow,           /* Number of result rows written here */
2564  int *pnColumn,        /* Number of result columns written here */
2565  char **pzErrmsg       /* Error msg written here */
2566);
2567SQLITE_API void sqlite3_free_table(char **result);
2568
2569/*
2570** CAPI3REF: Formatted String Printing Functions
2571**
2572** These routines are work-alikes of the "printf()" family of functions
2573** from the standard C library.
2574**
2575** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2576** results into memory obtained from [sqlite3_malloc()].
2577** The strings returned by these two routines should be
2578** released by [sqlite3_free()].  ^Both routines return a
2579** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2580** memory to hold the resulting string.
2581**
2582** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2583** the standard C library.  The result is written into the
2584** buffer supplied as the second parameter whose size is given by
2585** the first parameter. Note that the order of the
2586** first two parameters is reversed from snprintf().)^  This is an
2587** historical accident that cannot be fixed without breaking
2588** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2589** returns a pointer to its buffer instead of the number of
2590** characters actually written into the buffer.)^  We admit that
2591** the number of characters written would be a more useful return
2592** value but we cannot change the implementation of sqlite3_snprintf()
2593** now without breaking compatibility.
2594**
2595** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2596** guarantees that the buffer is always zero-terminated.  ^The first
2597** parameter "n" is the total size of the buffer, including space for
2598** the zero terminator.  So the longest string that can be completely
2599** written will be n-1 characters.
2600**
2601** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2602**
2603** These routines all implement some additional formatting
2604** options that are useful for constructing SQL statements.
2605** All of the usual printf() formatting options apply.  In addition, there
2606** is are "%q", "%Q", and "%z" options.
2607**
2608** ^(The %q option works like %s in that it substitutes a nul-terminated
2609** string from the argument list.  But %q also doubles every '\'' character.
2610** %q is designed for use inside a string literal.)^  By doubling each '\''
2611** character it escapes that character and allows it to be inserted into
2612** the string.
2613**
2614** For example, assume the string variable zText contains text as follows:
2615**
2616** <blockquote><pre>
2617**  char *zText = "It's a happy day!";
2618** </pre></blockquote>
2619**
2620** One can use this text in an SQL statement as follows:
2621**
2622** <blockquote><pre>
2623**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2624**  sqlite3_exec(db, zSQL, 0, 0, 0);
2625**  sqlite3_free(zSQL);
2626** </pre></blockquote>
2627**
2628** Because the %q format string is used, the '\'' character in zText
2629** is escaped and the SQL generated is as follows:
2630**
2631** <blockquote><pre>
2632**  INSERT INTO table1 VALUES('It''s a happy day!')
2633** </pre></blockquote>
2634**
2635** This is correct.  Had we used %s instead of %q, the generated SQL
2636** would have looked like this:
2637**
2638** <blockquote><pre>
2639**  INSERT INTO table1 VALUES('It's a happy day!');
2640** </pre></blockquote>
2641**
2642** This second example is an SQL syntax error.  As a general rule you should
2643** always use %q instead of %s when inserting text into a string literal.
2644**
2645** ^(The %Q option works like %q except it also adds single quotes around
2646** the outside of the total string.  Additionally, if the parameter in the
2647** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2648** single quotes).)^  So, for example, one could say:
2649**
2650** <blockquote><pre>
2651**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2652**  sqlite3_exec(db, zSQL, 0, 0, 0);
2653**  sqlite3_free(zSQL);
2654** </pre></blockquote>
2655**
2656** The code above will render a correct SQL statement in the zSQL
2657** variable even if the zText variable is a NULL pointer.
2658**
2659** ^(The "%z" formatting option works like "%s" but with the
2660** addition that after the string has been read and copied into
2661** the result, [sqlite3_free()] is called on the input string.)^
2662*/
2663SQLITE_API char *sqlite3_mprintf(const char*,...);
2664SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2665SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2666SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2667
2668/*
2669** CAPI3REF: Memory Allocation Subsystem
2670**
2671** The SQLite core uses these three routines for all of its own
2672** internal memory allocation needs. "Core" in the previous sentence
2673** does not include operating-system specific VFS implementation.  The
2674** Windows VFS uses native malloc() and free() for some operations.
2675**
2676** ^The sqlite3_malloc() routine returns a pointer to a block
2677** of memory at least N bytes in length, where N is the parameter.
2678** ^If sqlite3_malloc() is unable to obtain sufficient free
2679** memory, it returns a NULL pointer.  ^If the parameter N to
2680** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2681** a NULL pointer.
2682**
2683** ^Calling sqlite3_free() with a pointer previously returned
2684** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2685** that it might be reused.  ^The sqlite3_free() routine is
2686** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2687** to sqlite3_free() is harmless.  After being freed, memory
2688** should neither be read nor written.  Even reading previously freed
2689** memory might result in a segmentation fault or other severe error.
2690** Memory corruption, a segmentation fault, or other severe error
2691** might result if sqlite3_free() is called with a non-NULL pointer that
2692** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2693**
2694** ^(The sqlite3_realloc() interface attempts to resize a
2695** prior memory allocation to be at least N bytes, where N is the
2696** second parameter.  The memory allocation to be resized is the first
2697** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2698** is a NULL pointer then its behavior is identical to calling
2699** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2700** ^If the second parameter to sqlite3_realloc() is zero or
2701** negative then the behavior is exactly the same as calling
2702** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2703** ^sqlite3_realloc() returns a pointer to a memory allocation
2704** of at least N bytes in size or NULL if sufficient memory is unavailable.
2705** ^If M is the size of the prior allocation, then min(N,M) bytes
2706** of the prior allocation are copied into the beginning of buffer returned
2707** by sqlite3_realloc() and the prior allocation is freed.
2708** ^If sqlite3_realloc() returns NULL, then the prior allocation
2709** is not freed.
2710**
2711** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2712** is always aligned to at least an 8 byte boundary, or to a
2713** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2714** option is used.
2715**
2716** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2717** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2718** implementation of these routines to be omitted.  That capability
2719** is no longer provided.  Only built-in memory allocators can be used.
2720**
2721** The Windows OS interface layer calls
2722** the system malloc() and free() directly when converting
2723** filenames between the UTF-8 encoding used by SQLite
2724** and whatever filename encoding is used by the particular Windows
2725** installation.  Memory allocation errors are detected, but
2726** they are reported back as [SQLITE_CANTOPEN] or
2727** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2728**
2729** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2730** must be either NULL or else pointers obtained from a prior
2731** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2732** not yet been released.
2733**
2734** The application must not read or write any part of
2735** a block of memory after it has been released using
2736** [sqlite3_free()] or [sqlite3_realloc()].
2737*/
2738SQLITE_API void *sqlite3_malloc(int);
2739SQLITE_API void *sqlite3_realloc(void*, int);
2740SQLITE_API void sqlite3_free(void*);
2741
2742/*
2743** CAPI3REF: Memory Allocator Statistics
2744**
2745** SQLite provides these two interfaces for reporting on the status
2746** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2747** routines, which form the built-in memory allocation subsystem.
2748**
2749** ^The [sqlite3_memory_used()] routine returns the number of bytes
2750** of memory currently outstanding (malloced but not freed).
2751** ^The [sqlite3_memory_highwater()] routine returns the maximum
2752** value of [sqlite3_memory_used()] since the high-water mark
2753** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2754** [sqlite3_memory_highwater()] include any overhead
2755** added by SQLite in its implementation of [sqlite3_malloc()],
2756** but not overhead added by the any underlying system library
2757** routines that [sqlite3_malloc()] may call.
2758**
2759** ^The memory high-water mark is reset to the current value of
2760** [sqlite3_memory_used()] if and only if the parameter to
2761** [sqlite3_memory_highwater()] is true.  ^The value returned
2762** by [sqlite3_memory_highwater(1)] is the high-water mark
2763** prior to the reset.
2764*/
2765SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2766SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2767
2768/*
2769** CAPI3REF: Pseudo-Random Number Generator
2770**
2771** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2772** select random [ROWID | ROWIDs] when inserting new records into a table that
2773** already uses the largest possible [ROWID].  The PRNG is also used for
2774** the build-in random() and randomblob() SQL functions.  This interface allows
2775** applications to access the same PRNG for other purposes.
2776**
2777** ^A call to this routine stores N bytes of randomness into buffer P.
2778**
2779** ^The first time this routine is invoked (either internally or by
2780** the application) the PRNG is seeded using randomness obtained
2781** from the xRandomness method of the default [sqlite3_vfs] object.
2782** ^On all subsequent invocations, the pseudo-randomness is generated
2783** internally and without recourse to the [sqlite3_vfs] xRandomness
2784** method.
2785*/
2786SQLITE_API void sqlite3_randomness(int N, void *P);
2787
2788/*
2789** CAPI3REF: Compile-Time Authorization Callbacks
2790**
2791** ^This routine registers an authorizer callback with a particular
2792** [database connection], supplied in the first argument.
2793** ^The authorizer callback is invoked as SQL statements are being compiled
2794** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2795** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2796** points during the compilation process, as logic is being created
2797** to perform various actions, the authorizer callback is invoked to
2798** see if those actions are allowed.  ^The authorizer callback should
2799** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2800** specific action but allow the SQL statement to continue to be
2801** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2802** rejected with an error.  ^If the authorizer callback returns
2803** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2804** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2805** the authorizer will fail with an error message.
2806**
2807** When the callback returns [SQLITE_OK], that means the operation
2808** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2809** [sqlite3_prepare_v2()] or equivalent call that triggered the
2810** authorizer will fail with an error message explaining that
2811** access is denied.
2812**
2813** ^The first parameter to the authorizer callback is a copy of the third
2814** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2815** to the callback is an integer [SQLITE_COPY | action code] that specifies
2816** the particular action to be authorized. ^The third through sixth parameters
2817** to the callback are zero-terminated strings that contain additional
2818** details about the action to be authorized.
2819**
2820** ^If the action code is [SQLITE_READ]
2821** and the callback returns [SQLITE_IGNORE] then the
2822** [prepared statement] statement is constructed to substitute
2823** a NULL value in place of the table column that would have
2824** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2825** return can be used to deny an untrusted user access to individual
2826** columns of a table.
2827** ^If the action code is [SQLITE_DELETE] and the callback returns
2828** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2829** [truncate optimization] is disabled and all rows are deleted individually.
2830**
2831** An authorizer is used when [sqlite3_prepare | preparing]
2832** SQL statements from an untrusted source, to ensure that the SQL statements
2833** do not try to access data they are not allowed to see, or that they do not
2834** try to execute malicious statements that damage the database.  For
2835** example, an application may allow a user to enter arbitrary
2836** SQL queries for evaluation by a database.  But the application does
2837** not want the user to be able to make arbitrary changes to the
2838** database.  An authorizer could then be put in place while the
2839** user-entered SQL is being [sqlite3_prepare | prepared] that
2840** disallows everything except [SELECT] statements.
2841**
2842** Applications that need to process SQL from untrusted sources
2843** might also consider lowering resource limits using [sqlite3_limit()]
2844** and limiting database size using the [max_page_count] [PRAGMA]
2845** in addition to using an authorizer.
2846**
2847** ^(Only a single authorizer can be in place on a database connection
2848** at a time.  Each call to sqlite3_set_authorizer overrides the
2849** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2850** The authorizer is disabled by default.
2851**
2852** The authorizer callback must not do anything that will modify
2853** the database connection that invoked the authorizer callback.
2854** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2855** database connections for the meaning of "modify" in this paragraph.
2856**
2857** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2858** statement might be re-prepared during [sqlite3_step()] due to a
2859** schema change.  Hence, the application should ensure that the
2860** correct authorizer callback remains in place during the [sqlite3_step()].
2861**
2862** ^Note that the authorizer callback is invoked only during
2863** [sqlite3_prepare()] or its variants.  Authorization is not
2864** performed during statement evaluation in [sqlite3_step()], unless
2865** as stated in the previous paragraph, sqlite3_step() invokes
2866** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2867*/
2868SQLITE_API int sqlite3_set_authorizer(
2869  sqlite3*,
2870  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2871  void *pUserData
2872);
2873
2874/*
2875** CAPI3REF: Authorizer Return Codes
2876**
2877** The [sqlite3_set_authorizer | authorizer callback function] must
2878** return either [SQLITE_OK] or one of these two constants in order
2879** to signal SQLite whether or not the action is permitted.  See the
2880** [sqlite3_set_authorizer | authorizer documentation] for additional
2881** information.
2882**
2883** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2884** from the [sqlite3_vtab_on_conflict()] interface.
2885*/
2886#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2887#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2888
2889/*
2890** CAPI3REF: Authorizer Action Codes
2891**
2892** The [sqlite3_set_authorizer()] interface registers a callback function
2893** that is invoked to authorize certain SQL statement actions.  The
2894** second parameter to the callback is an integer code that specifies
2895** what action is being authorized.  These are the integer action codes that
2896** the authorizer callback may be passed.
2897**
2898** These action code values signify what kind of operation is to be
2899** authorized.  The 3rd and 4th parameters to the authorization
2900** callback function will be parameters or NULL depending on which of these
2901** codes is used as the second parameter.  ^(The 5th parameter to the
2902** authorizer callback is the name of the database ("main", "temp",
2903** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2904** is the name of the inner-most trigger or view that is responsible for
2905** the access attempt or NULL if this access attempt is directly from
2906** top-level SQL code.
2907*/
2908/******************************************* 3rd ************ 4th ***********/
2909#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2910#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2911#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2912#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2913#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2914#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2915#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2916#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2917#define SQLITE_DELETE                9   /* Table Name      NULL            */
2918#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2919#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2920#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2921#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2922#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2923#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2924#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2925#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2926#define SQLITE_INSERT               18   /* Table Name      NULL            */
2927#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2928#define SQLITE_READ                 20   /* Table Name      Column Name     */
2929#define SQLITE_SELECT               21   /* NULL            NULL            */
2930#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2931#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2932#define SQLITE_ATTACH               24   /* Filename        NULL            */
2933#define SQLITE_DETACH               25   /* Database Name   NULL            */
2934#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2935#define SQLITE_REINDEX              27   /* Index Name      NULL            */
2936#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2937#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2938#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2939#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2940#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2941#define SQLITE_COPY                  0   /* No longer used */
2942
2943/*
2944** CAPI3REF: Tracing And Profiling Functions
2945**
2946** These routines register callback functions that can be used for
2947** tracing and profiling the execution of SQL statements.
2948**
2949** ^The callback function registered by sqlite3_trace() is invoked at
2950** various times when an SQL statement is being run by [sqlite3_step()].
2951** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2952** SQL statement text as the statement first begins executing.
2953** ^(Additional sqlite3_trace() callbacks might occur
2954** as each triggered subprogram is entered.  The callbacks for triggers
2955** contain a UTF-8 SQL comment that identifies the trigger.)^
2956**
2957** ^The callback function registered by sqlite3_profile() is invoked
2958** as each SQL statement finishes.  ^The profile callback contains
2959** the original statement text and an estimate of wall-clock time
2960** of how long that statement took to run.  ^The profile callback
2961** time is in units of nanoseconds, however the current implementation
2962** is only capable of millisecond resolution so the six least significant
2963** digits in the time are meaningless.  Future versions of SQLite
2964** might provide greater resolution on the profiler callback.  The
2965** sqlite3_profile() function is considered experimental and is
2966** subject to change in future versions of SQLite.
2967*/
2968SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2969SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2970   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2971
2972/*
2973** CAPI3REF: Query Progress Callbacks
2974**
2975** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2976** function X to be invoked periodically during long running calls to
2977** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2978** database connection D.  An example use for this
2979** interface is to keep a GUI updated during a large query.
2980**
2981** ^The parameter P is passed through as the only parameter to the
2982** callback function X.  ^The parameter N is the number of
2983** [virtual machine instructions] that are evaluated between successive
2984** invocations of the callback X.
2985**
2986** ^Only a single progress handler may be defined at one time per
2987** [database connection]; setting a new progress handler cancels the
2988** old one.  ^Setting parameter X to NULL disables the progress handler.
2989** ^The progress handler is also disabled by setting N to a value less
2990** than 1.
2991**
2992** ^If the progress callback returns non-zero, the operation is
2993** interrupted.  This feature can be used to implement a
2994** "Cancel" button on a GUI progress dialog box.
2995**
2996** The progress handler callback must not do anything that will modify
2997** the database connection that invoked the progress handler.
2998** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2999** database connections for the meaning of "modify" in this paragraph.
3000**
3001*/
3002SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3003
3004/*
3005** CAPI3REF: Opening A New Database Connection
3006**
3007** ^These routines open an SQLite database file as specified by the
3008** filename argument. ^The filename argument is interpreted as UTF-8 for
3009** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3010** order for sqlite3_open16(). ^(A [database connection] handle is usually
3011** returned in *ppDb, even if an error occurs.  The only exception is that
3012** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3013** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3014** object.)^ ^(If the database is opened (and/or created) successfully, then
3015** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3016** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3017** an English language description of the error following a failure of any
3018** of the sqlite3_open() routines.
3019**
3020** ^The default encoding for the database will be UTF-8 if
3021** sqlite3_open() or sqlite3_open_v2() is called and
3022** UTF-16 in the native byte order if sqlite3_open16() is used.
3023**
3024** Whether or not an error occurs when it is opened, resources
3025** associated with the [database connection] handle should be released by
3026** passing it to [sqlite3_close()] when it is no longer required.
3027**
3028** The sqlite3_open_v2() interface works like sqlite3_open()
3029** except that it accepts two additional parameters for additional control
3030** over the new database connection.  ^(The flags parameter to
3031** sqlite3_open_v2() can take one of
3032** the following three values, optionally combined with the
3033** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3034** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3035**
3036** <dl>
3037** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3038** <dd>The database is opened in read-only mode.  If the database does not
3039** already exist, an error is returned.</dd>)^
3040**
3041** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3042** <dd>The database is opened for reading and writing if possible, or reading
3043** only if the file is write protected by the operating system.  In either
3044** case the database must already exist, otherwise an error is returned.</dd>)^
3045**
3046** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3047** <dd>The database is opened for reading and writing, and is created if
3048** it does not already exist. This is the behavior that is always used for
3049** sqlite3_open() and sqlite3_open16().</dd>)^
3050** </dl>
3051**
3052** If the 3rd parameter to sqlite3_open_v2() is not one of the
3053** combinations shown above optionally combined with other
3054** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3055** then the behavior is undefined.
3056**
3057** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3058** opens in the multi-thread [threading mode] as long as the single-thread
3059** mode has not been set at compile-time or start-time.  ^If the
3060** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3061** in the serialized [threading mode] unless single-thread was
3062** previously selected at compile-time or start-time.
3063** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3064** eligible to use [shared cache mode], regardless of whether or not shared
3065** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3066** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3067** participate in [shared cache mode] even if it is enabled.
3068**
3069** ^The fourth parameter to sqlite3_open_v2() is the name of the
3070** [sqlite3_vfs] object that defines the operating system interface that
3071** the new database connection should use.  ^If the fourth parameter is
3072** a NULL pointer then the default [sqlite3_vfs] object is used.
3073**
3074** ^If the filename is ":memory:", then a private, temporary in-memory database
3075** is created for the connection.  ^This in-memory database will vanish when
3076** the database connection is closed.  Future versions of SQLite might
3077** make use of additional special filenames that begin with the ":" character.
3078** It is recommended that when a database filename actually does begin with
3079** a ":" character you should prefix the filename with a pathname such as
3080** "./" to avoid ambiguity.
3081**
3082** ^If the filename is an empty string, then a private, temporary
3083** on-disk database will be created.  ^This private database will be
3084** automatically deleted as soon as the database connection is closed.
3085**
3086** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3087**
3088** ^If [URI filename] interpretation is enabled, and the filename argument
3089** begins with "file:", then the filename is interpreted as a URI. ^URI
3090** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3091** set in the fourth argument to sqlite3_open_v2(), or if it has
3092** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3093** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3094** As of SQLite version 3.7.7, URI filename interpretation is turned off
3095** by default, but future releases of SQLite might enable URI filename
3096** interpretation by default.  See "[URI filenames]" for additional
3097** information.
3098**
3099** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3100** authority, then it must be either an empty string or the string
3101** "localhost". ^If the authority is not an empty string or "localhost", an
3102** error is returned to the caller. ^The fragment component of a URI, if
3103** present, is ignored.
3104**
3105** ^SQLite uses the path component of the URI as the name of the disk file
3106** which contains the database. ^If the path begins with a '/' character,
3107** then it is interpreted as an absolute path. ^If the path does not begin
3108** with a '/' (meaning that the authority section is omitted from the URI)
3109** then the path is interpreted as a relative path.
3110** ^On windows, the first component of an absolute path
3111** is a drive specification (e.g. "C:").
3112**
3113** [[core URI query parameters]]
3114** The query component of a URI may contain parameters that are interpreted
3115** either by SQLite itself, or by a [VFS | custom VFS implementation].
3116** SQLite interprets the following three query parameters:
3117**
3118** <ul>
3119**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3120**     a VFS object that provides the operating system interface that should
3121**     be used to access the database file on disk. ^If this option is set to
3122**     an empty string the default VFS object is used. ^Specifying an unknown
3123**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3124**     present, then the VFS specified by the option takes precedence over
3125**     the value passed as the fourth parameter to sqlite3_open_v2().
3126**
3127**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw" or
3128**     "rwc". Attempting to set it to any other value is an error)^.
3129**     ^If "ro" is specified, then the database is opened for read-only
3130**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3131**     third argument to sqlite3_prepare_v2(). ^If the mode option is set to
3132**     "rw", then the database is opened for read-write (but not create)
3133**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3134**     been set. ^Value "rwc" is equivalent to setting both
3135**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If sqlite3_open_v2() is
3136**     used, it is an error to specify a value for the mode parameter that is
3137**     less restrictive than that specified by the flags passed as the third
3138**     parameter.
3139**
3140**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3141**     "private". ^Setting it to "shared" is equivalent to setting the
3142**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3143**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3144**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3145**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3146**     a URI filename, its value overrides any behaviour requested by setting
3147**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3148** </ul>
3149**
3150** ^Specifying an unknown parameter in the query component of a URI is not an
3151** error.  Future versions of SQLite might understand additional query
3152** parameters.  See "[query parameters with special meaning to SQLite]" for
3153** additional information.
3154**
3155** [[URI filename examples]] <h3>URI filename examples</h3>
3156**
3157** <table border="1" align=center cellpadding=5>
3158** <tr><th> URI filenames <th> Results
3159** <tr><td> file:data.db <td>
3160**          Open the file "data.db" in the current directory.
3161** <tr><td> file:/home/fred/data.db<br>
3162**          file:///home/fred/data.db <br>
3163**          file://localhost/home/fred/data.db <br> <td>
3164**          Open the database file "/home/fred/data.db".
3165** <tr><td> file://darkstar/home/fred/data.db <td>
3166**          An error. "darkstar" is not a recognized authority.
3167** <tr><td style="white-space:nowrap">
3168**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3169**     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3170**          C:. Note that the %20 escaping in this example is not strictly
3171**          necessary - space characters can be used literally
3172**          in URI filenames.
3173** <tr><td> file:data.db?mode=ro&cache=private <td>
3174**          Open file "data.db" in the current directory for read-only access.
3175**          Regardless of whether or not shared-cache mode is enabled by
3176**          default, use a private cache.
3177** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3178**          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3179** <tr><td> file:data.db?mode=readonly <td>
3180**          An error. "readonly" is not a valid option for the "mode" parameter.
3181** </table>
3182**
3183** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3184** query components of a URI. A hexadecimal escape sequence consists of a
3185** percent sign - "%" - followed by exactly two hexadecimal digits
3186** specifying an octet value. ^Before the path or query components of a
3187** URI filename are interpreted, they are encoded using UTF-8 and all
3188** hexadecimal escape sequences replaced by a single byte containing the
3189** corresponding octet. If this process generates an invalid UTF-8 encoding,
3190** the results are undefined.
3191**
3192** <b>Note to Windows users:</b>  The encoding used for the filename argument
3193** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3194** codepage is currently defined.  Filenames containing international
3195** characters must be converted to UTF-8 prior to passing them into
3196** sqlite3_open() or sqlite3_open_v2().
3197*/
3198SQLITE_API int sqlite3_open(
3199  const char *filename,   /* Database filename (UTF-8) */
3200  sqlite3 **ppDb          /* OUT: SQLite db handle */
3201);
3202SQLITE_API int sqlite3_open16(
3203  const void *filename,   /* Database filename (UTF-16) */
3204  sqlite3 **ppDb          /* OUT: SQLite db handle */
3205);
3206SQLITE_API int sqlite3_open_v2(
3207  const char *filename,   /* Database filename (UTF-8) */
3208  sqlite3 **ppDb,         /* OUT: SQLite db handle */
3209  int flags,              /* Flags */
3210  const char *zVfs        /* Name of VFS module to use */
3211);
3212
3213/*
3214** CAPI3REF: Obtain Values For URI Parameters
3215**
3216** These are utility routines, useful to VFS implementations, that check
3217** to see if a database file was a URI that contained a specific query
3218** parameter, and if so obtains the value of that query parameter.
3219**
3220** If F is the database filename pointer passed into the xOpen() method of
3221** a VFS implementation when the flags parameter to xOpen() has one or
3222** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3223** P is the name of the query parameter, then
3224** sqlite3_uri_parameter(F,P) returns the value of the P
3225** parameter if it exists or a NULL pointer if P does not appear as a
3226** query parameter on F.  If P is a query parameter of F
3227** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3228** a pointer to an empty string.
3229**
3230** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3231** parameter and returns true (1) or false (0) according to the value
3232** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3233** value of query parameter P is one of "yes", "true", or "on" in any
3234** case or if the value begins with a non-zero number.  The
3235** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3236** query parameter P is one of "no", "false", or "off" in any case or
3237** if the value begins with a numeric zero.  If P is not a query
3238** parameter on F or if the value of P is does not match any of the
3239** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3240**
3241** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3242** 64-bit signed integer and returns that integer, or D if P does not
3243** exist.  If the value of P is something other than an integer, then
3244** zero is returned.
3245**
3246** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3247** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3248** is not a database file pathname pointer that SQLite passed into the xOpen
3249** VFS method, then the behavior of this routine is undefined and probably
3250** undesirable.
3251*/
3252SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3253SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3254SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3255
3256
3257/*
3258** CAPI3REF: Error Codes And Messages
3259**
3260** ^The sqlite3_errcode() interface returns the numeric [result code] or
3261** [extended result code] for the most recent failed sqlite3_* API call
3262** associated with a [database connection]. If a prior API call failed
3263** but the most recent API call succeeded, the return value from
3264** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3265** interface is the same except that it always returns the
3266** [extended result code] even when extended result codes are
3267** disabled.
3268**
3269** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3270** text that describes the error, as either UTF-8 or UTF-16 respectively.
3271** ^(Memory to hold the error message string is managed internally.
3272** The application does not need to worry about freeing the result.
3273** However, the error string might be overwritten or deallocated by
3274** subsequent calls to other SQLite interface functions.)^
3275**
3276** When the serialized [threading mode] is in use, it might be the
3277** case that a second error occurs on a separate thread in between
3278** the time of the first error and the call to these interfaces.
3279** When that happens, the second error will be reported since these
3280** interfaces always report the most recent result.  To avoid
3281** this, each thread can obtain exclusive use of the [database connection] D
3282** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3283** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3284** all calls to the interfaces listed here are completed.
3285**
3286** If an interface fails with SQLITE_MISUSE, that means the interface
3287** was invoked incorrectly by the application.  In that case, the
3288** error code and message may or may not be set.
3289*/
3290SQLITE_API int sqlite3_errcode(sqlite3 *db);
3291SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3292SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3293SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3294
3295/*
3296** CAPI3REF: SQL Statement Object
3297** KEYWORDS: {prepared statement} {prepared statements}
3298**
3299** An instance of this object represents a single SQL statement.
3300** This object is variously known as a "prepared statement" or a
3301** "compiled SQL statement" or simply as a "statement".
3302**
3303** The life of a statement object goes something like this:
3304**
3305** <ol>
3306** <li> Create the object using [sqlite3_prepare_v2()] or a related
3307**      function.
3308** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3309**      interfaces.
3310** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3311** <li> Reset the statement using [sqlite3_reset()] then go back
3312**      to step 2.  Do this zero or more times.
3313** <li> Destroy the object using [sqlite3_finalize()].
3314** </ol>
3315**
3316** Refer to documentation on individual methods above for additional
3317** information.
3318*/
3319typedef struct sqlite3_stmt sqlite3_stmt;
3320
3321/*
3322** CAPI3REF: Run-time Limits
3323**
3324** ^(This interface allows the size of various constructs to be limited
3325** on a connection by connection basis.  The first parameter is the
3326** [database connection] whose limit is to be set or queried.  The
3327** second parameter is one of the [limit categories] that define a
3328** class of constructs to be size limited.  The third parameter is the
3329** new limit for that construct.)^
3330**
3331** ^If the new limit is a negative number, the limit is unchanged.
3332** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3333** [limits | hard upper bound]
3334** set at compile-time by a C preprocessor macro called
3335** [limits | SQLITE_MAX_<i>NAME</i>].
3336** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3337** ^Attempts to increase a limit above its hard upper bound are
3338** silently truncated to the hard upper bound.
3339**
3340** ^Regardless of whether or not the limit was changed, the
3341** [sqlite3_limit()] interface returns the prior value of the limit.
3342** ^Hence, to find the current value of a limit without changing it,
3343** simply invoke this interface with the third parameter set to -1.
3344**
3345** Run-time limits are intended for use in applications that manage
3346** both their own internal database and also databases that are controlled
3347** by untrusted external sources.  An example application might be a
3348** web browser that has its own databases for storing history and
3349** separate databases controlled by JavaScript applications downloaded
3350** off the Internet.  The internal databases can be given the
3351** large, default limits.  Databases managed by external sources can
3352** be given much smaller limits designed to prevent a denial of service
3353** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3354** interface to further control untrusted SQL.  The size of the database
3355** created by an untrusted script can be contained using the
3356** [max_page_count] [PRAGMA].
3357**
3358** New run-time limit categories may be added in future releases.
3359*/
3360SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3361
3362/*
3363** CAPI3REF: Run-Time Limit Categories
3364** KEYWORDS: {limit category} {*limit categories}
3365**
3366** These constants define various performance limits
3367** that can be lowered at run-time using [sqlite3_limit()].
3368** The synopsis of the meanings of the various limits is shown below.
3369** Additional information is available at [limits | Limits in SQLite].
3370**
3371** <dl>
3372** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3373** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3374**
3375** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3376** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3377**
3378** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3379** <dd>The maximum number of columns in a table definition or in the
3380** result set of a [SELECT] or the maximum number of columns in an index
3381** or in an ORDER BY or GROUP BY clause.</dd>)^
3382**
3383** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3384** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3385**
3386** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3387** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3388**
3389** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3390** <dd>The maximum number of instructions in a virtual machine program
3391** used to implement an SQL statement.  This limit is not currently
3392** enforced, though that might be added in some future release of
3393** SQLite.</dd>)^
3394**
3395** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3396** <dd>The maximum number of arguments on a function.</dd>)^
3397**
3398** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3399** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3400**
3401** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3402** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3403** <dd>The maximum length of the pattern argument to the [LIKE] or
3404** [GLOB] operators.</dd>)^
3405**
3406** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3407** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3408** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3409**
3410** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3411** <dd>The maximum depth of recursion for triggers.</dd>)^
3412** </dl>
3413*/
3414#define SQLITE_LIMIT_LENGTH                    0
3415#define SQLITE_LIMIT_SQL_LENGTH                1
3416#define SQLITE_LIMIT_COLUMN                    2
3417#define SQLITE_LIMIT_EXPR_DEPTH                3
3418#define SQLITE_LIMIT_COMPOUND_SELECT           4
3419#define SQLITE_LIMIT_VDBE_OP                   5
3420#define SQLITE_LIMIT_FUNCTION_ARG              6
3421#define SQLITE_LIMIT_ATTACHED                  7
3422#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3423#define SQLITE_LIMIT_VARIABLE_NUMBER           9
3424#define SQLITE_LIMIT_TRIGGER_DEPTH            10
3425
3426/*
3427** CAPI3REF: Compiling An SQL Statement
3428** KEYWORDS: {SQL statement compiler}
3429**
3430** To execute an SQL query, it must first be compiled into a byte-code
3431** program using one of these routines.
3432**
3433** The first argument, "db", is a [database connection] obtained from a
3434** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3435** [sqlite3_open16()].  The database connection must not have been closed.
3436**
3437** The second argument, "zSql", is the statement to be compiled, encoded
3438** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3439** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3440** use UTF-16.
3441**
3442** ^If the nByte argument is less than zero, then zSql is read up to the
3443** first zero terminator. ^If nByte is non-negative, then it is the maximum
3444** number of  bytes read from zSql.  ^When nByte is non-negative, the
3445** zSql string ends at either the first '\000' or '\u0000' character or
3446** the nByte-th byte, whichever comes first. If the caller knows
3447** that the supplied string is nul-terminated, then there is a small
3448** performance advantage to be gained by passing an nByte parameter that
3449** is equal to the number of bytes in the input string <i>including</i>
3450** the nul-terminator bytes as this saves SQLite from having to
3451** make a copy of the input string.
3452**
3453** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3454** past the end of the first SQL statement in zSql.  These routines only
3455** compile the first statement in zSql, so *pzTail is left pointing to
3456** what remains uncompiled.
3457**
3458** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3459** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3460** to NULL.  ^If the input text contains no SQL (if the input is an empty
3461** string or a comment) then *ppStmt is set to NULL.
3462** The calling procedure is responsible for deleting the compiled
3463** SQL statement using [sqlite3_finalize()] after it has finished with it.
3464** ppStmt may not be NULL.
3465**
3466** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3467** otherwise an [error code] is returned.
3468**
3469** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3470** recommended for all new programs. The two older interfaces are retained
3471** for backwards compatibility, but their use is discouraged.
3472** ^In the "v2" interfaces, the prepared statement
3473** that is returned (the [sqlite3_stmt] object) contains a copy of the
3474** original SQL text. This causes the [sqlite3_step()] interface to
3475** behave differently in three ways:
3476**
3477** <ol>
3478** <li>
3479** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3480** always used to do, [sqlite3_step()] will automatically recompile the SQL
3481** statement and try to run it again.
3482** </li>
3483**
3484** <li>
3485** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3486** [error codes] or [extended error codes].  ^The legacy behavior was that
3487** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3488** and the application would have to make a second call to [sqlite3_reset()]
3489** in order to find the underlying cause of the problem. With the "v2" prepare
3490** interfaces, the underlying reason for the error is returned immediately.
3491** </li>
3492**
3493** <li>
3494** ^If the specific value bound to [parameter | host parameter] in the
3495** WHERE clause might influence the choice of query plan for a statement,
3496** then the statement will be automatically recompiled, as if there had been
3497** a schema change, on the first  [sqlite3_step()] call following any change
3498** to the [sqlite3_bind_text | bindings] of that [parameter].
3499** ^The specific value of WHERE-clause [parameter] might influence the
3500** choice of query plan if the parameter is the left-hand side of a [LIKE]
3501** or [GLOB] operator or if the parameter is compared to an indexed column
3502** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3503** the
3504** </li>
3505** </ol>
3506*/
3507SQLITE_API int sqlite3_prepare(
3508  sqlite3 *db,            /* Database handle */
3509  const char *zSql,       /* SQL statement, UTF-8 encoded */
3510  int nByte,              /* Maximum length of zSql in bytes. */
3511  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3512  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3513);
3514SQLITE_API int sqlite3_prepare_v2(
3515  sqlite3 *db,            /* Database handle */
3516  const char *zSql,       /* SQL statement, UTF-8 encoded */
3517  int nByte,              /* Maximum length of zSql in bytes. */
3518  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3519  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3520);
3521SQLITE_API int sqlite3_prepare16(
3522  sqlite3 *db,            /* Database handle */
3523  const void *zSql,       /* SQL statement, UTF-16 encoded */
3524  int nByte,              /* Maximum length of zSql in bytes. */
3525  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3526  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3527);
3528SQLITE_API int sqlite3_prepare16_v2(
3529  sqlite3 *db,            /* Database handle */
3530  const void *zSql,       /* SQL statement, UTF-16 encoded */
3531  int nByte,              /* Maximum length of zSql in bytes. */
3532  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3533  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3534);
3535
3536/*
3537** CAPI3REF: Retrieving Statement SQL
3538**
3539** ^This interface can be used to retrieve a saved copy of the original
3540** SQL text used to create a [prepared statement] if that statement was
3541** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3542*/
3543SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3544
3545/*
3546** CAPI3REF: Determine If An SQL Statement Writes The Database
3547**
3548** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3549** and only if the [prepared statement] X makes no direct changes to
3550** the content of the database file.
3551**
3552** Note that [application-defined SQL functions] or
3553** [virtual tables] might change the database indirectly as a side effect.
3554** ^(For example, if an application defines a function "eval()" that
3555** calls [sqlite3_exec()], then the following SQL statement would
3556** change the database file through side-effects:
3557**
3558** <blockquote><pre>
3559**    SELECT eval('DELETE FROM t1') FROM t2;
3560** </pre></blockquote>
3561**
3562** But because the [SELECT] statement does not change the database file
3563** directly, sqlite3_stmt_readonly() would still return true.)^
3564**
3565** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3566** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3567** since the statements themselves do not actually modify the database but
3568** rather they control the timing of when other statements modify the
3569** database.  ^The [ATTACH] and [DETACH] statements also cause
3570** sqlite3_stmt_readonly() to return true since, while those statements
3571** change the configuration of a database connection, they do not make
3572** changes to the content of the database files on disk.
3573*/
3574SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3575
3576/*
3577** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3578**
3579** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3580** [prepared statement] S has been stepped at least once using
3581** [sqlite3_step(S)] but has not run to completion and/or has not
3582** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3583** interface returns false if S is a NULL pointer.  If S is not a
3584** NULL pointer and is not a pointer to a valid [prepared statement]
3585** object, then the behavior is undefined and probably undesirable.
3586**
3587** This interface can be used in combination [sqlite3_next_stmt()]
3588** to locate all prepared statements associated with a database
3589** connection that are in need of being reset.  This can be used,
3590** for example, in diagnostic routines to search for prepared
3591** statements that are holding a transaction open.
3592*/
3593SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3594
3595/*
3596** CAPI3REF: Dynamically Typed Value Object
3597** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3598**
3599** SQLite uses the sqlite3_value object to represent all values
3600** that can be stored in a database table. SQLite uses dynamic typing
3601** for the values it stores.  ^Values stored in sqlite3_value objects
3602** can be integers, floating point values, strings, BLOBs, or NULL.
3603**
3604** An sqlite3_value object may be either "protected" or "unprotected".
3605** Some interfaces require a protected sqlite3_value.  Other interfaces
3606** will accept either a protected or an unprotected sqlite3_value.
3607** Every interface that accepts sqlite3_value arguments specifies
3608** whether or not it requires a protected sqlite3_value.
3609**
3610** The terms "protected" and "unprotected" refer to whether or not
3611** a mutex is held.  An internal mutex is held for a protected
3612** sqlite3_value object but no mutex is held for an unprotected
3613** sqlite3_value object.  If SQLite is compiled to be single-threaded
3614** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3615** or if SQLite is run in one of reduced mutex modes
3616** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3617** then there is no distinction between protected and unprotected
3618** sqlite3_value objects and they can be used interchangeably.  However,
3619** for maximum code portability it is recommended that applications
3620** still make the distinction between protected and unprotected
3621** sqlite3_value objects even when not strictly required.
3622**
3623** ^The sqlite3_value objects that are passed as parameters into the
3624** implementation of [application-defined SQL functions] are protected.
3625** ^The sqlite3_value object returned by
3626** [sqlite3_column_value()] is unprotected.
3627** Unprotected sqlite3_value objects may only be used with
3628** [sqlite3_result_value()] and [sqlite3_bind_value()].
3629** The [sqlite3_value_blob | sqlite3_value_type()] family of
3630** interfaces require protected sqlite3_value objects.
3631*/
3632typedef struct Mem sqlite3_value;
3633
3634/*
3635** CAPI3REF: SQL Function Context Object
3636**
3637** The context in which an SQL function executes is stored in an
3638** sqlite3_context object.  ^A pointer to an sqlite3_context object
3639** is always first parameter to [application-defined SQL functions].
3640** The application-defined SQL function implementation will pass this
3641** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3642** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3643** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3644** and/or [sqlite3_set_auxdata()].
3645*/
3646typedef struct sqlite3_context sqlite3_context;
3647
3648/*
3649** CAPI3REF: Binding Values To Prepared Statements
3650** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3651** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3652**
3653** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3654** literals may be replaced by a [parameter] that matches one of following
3655** templates:
3656**
3657** <ul>
3658** <li>  ?
3659** <li>  ?NNN
3660** <li>  :VVV
3661** <li>  @VVV
3662** <li>  $VVV
3663** </ul>
3664**
3665** In the templates above, NNN represents an integer literal,
3666** and VVV represents an alphanumeric identifier.)^  ^The values of these
3667** parameters (also called "host parameter names" or "SQL parameters")
3668** can be set using the sqlite3_bind_*() routines defined here.
3669**
3670** ^The first argument to the sqlite3_bind_*() routines is always
3671** a pointer to the [sqlite3_stmt] object returned from
3672** [sqlite3_prepare_v2()] or its variants.
3673**
3674** ^The second argument is the index of the SQL parameter to be set.
3675** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3676** SQL parameter is used more than once, second and subsequent
3677** occurrences have the same index as the first occurrence.
3678** ^The index for named parameters can be looked up using the
3679** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3680** for "?NNN" parameters is the value of NNN.
3681** ^The NNN value must be between 1 and the [sqlite3_limit()]
3682** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3683**
3684** ^The third argument is the value to bind to the parameter.
3685**
3686** ^(In those routines that have a fourth argument, its value is the
3687** number of bytes in the parameter.  To be clear: the value is the
3688** number of <u>bytes</u> in the value, not the number of characters.)^
3689** ^If the fourth parameter is negative, the length of the string is
3690** the number of bytes up to the first zero terminator.
3691** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3692** or sqlite3_bind_text16() then that parameter must be the byte offset
3693** where the NUL terminator would occur assuming the string were NUL
3694** terminated.  If any NUL characters occur at byte offsets less than
3695** the value of the fourth parameter then the resulting string value will
3696** contain embedded NULs.  The result of expressions involving strings
3697** with embedded NULs is undefined.
3698**
3699** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3700** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3701** string after SQLite has finished with it.  ^The destructor is called
3702** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3703** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3704** ^If the fifth argument is
3705** the special value [SQLITE_STATIC], then SQLite assumes that the
3706** information is in static, unmanaged space and does not need to be freed.
3707** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3708** SQLite makes its own private copy of the data immediately, before
3709** the sqlite3_bind_*() routine returns.
3710**
3711** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3712** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3713** (just an integer to hold its size) while it is being processed.
3714** Zeroblobs are intended to serve as placeholders for BLOBs whose
3715** content is later written using
3716** [sqlite3_blob_open | incremental BLOB I/O] routines.
3717** ^A negative value for the zeroblob results in a zero-length BLOB.
3718**
3719** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3720** for the [prepared statement] or with a prepared statement for which
3721** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3722** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3723** routine is passed a [prepared statement] that has been finalized, the
3724** result is undefined and probably harmful.
3725**
3726** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3727** ^Unbound parameters are interpreted as NULL.
3728**
3729** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3730** [error code] if anything goes wrong.
3731** ^[SQLITE_RANGE] is returned if the parameter
3732** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3733**
3734** See also: [sqlite3_bind_parameter_count()],
3735** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3736*/
3737SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3738SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3739SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3740SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3741SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3742SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3743SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3744SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3745SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3746
3747/*
3748** CAPI3REF: Number Of SQL Parameters
3749**
3750** ^This routine can be used to find the number of [SQL parameters]
3751** in a [prepared statement].  SQL parameters are tokens of the
3752** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3753** placeholders for values that are [sqlite3_bind_blob | bound]
3754** to the parameters at a later time.
3755**
3756** ^(This routine actually returns the index of the largest (rightmost)
3757** parameter. For all forms except ?NNN, this will correspond to the
3758** number of unique parameters.  If parameters of the ?NNN form are used,
3759** there may be gaps in the list.)^
3760**
3761** See also: [sqlite3_bind_blob|sqlite3_bind()],
3762** [sqlite3_bind_parameter_name()], and
3763** [sqlite3_bind_parameter_index()].
3764*/
3765SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3766
3767/*
3768** CAPI3REF: Name Of A Host Parameter
3769**
3770** ^The sqlite3_bind_parameter_name(P,N) interface returns
3771** the name of the N-th [SQL parameter] in the [prepared statement] P.
3772** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3773** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3774** respectively.
3775** In other words, the initial ":" or "$" or "@" or "?"
3776** is included as part of the name.)^
3777** ^Parameters of the form "?" without a following integer have no name
3778** and are referred to as "nameless" or "anonymous parameters".
3779**
3780** ^The first host parameter has an index of 1, not 0.
3781**
3782** ^If the value N is out of range or if the N-th parameter is
3783** nameless, then NULL is returned.  ^The returned string is
3784** always in UTF-8 encoding even if the named parameter was
3785** originally specified as UTF-16 in [sqlite3_prepare16()] or
3786** [sqlite3_prepare16_v2()].
3787**
3788** See also: [sqlite3_bind_blob|sqlite3_bind()],
3789** [sqlite3_bind_parameter_count()], and
3790** [sqlite3_bind_parameter_index()].
3791*/
3792SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3793
3794/*
3795** CAPI3REF: Index Of A Parameter With A Given Name
3796**
3797** ^Return the index of an SQL parameter given its name.  ^The
3798** index value returned is suitable for use as the second
3799** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3800** is returned if no matching parameter is found.  ^The parameter
3801** name must be given in UTF-8 even if the original statement
3802** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3803**
3804** See also: [sqlite3_bind_blob|sqlite3_bind()],
3805** [sqlite3_bind_parameter_count()], and
3806** [sqlite3_bind_parameter_index()].
3807*/
3808SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3809
3810/*
3811** CAPI3REF: Reset All Bindings On A Prepared Statement
3812**
3813** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3814** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3815** ^Use this routine to reset all host parameters to NULL.
3816*/
3817SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3818
3819/*
3820** CAPI3REF: Number Of Columns In A Result Set
3821**
3822** ^Return the number of columns in the result set returned by the
3823** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3824** statement that does not return data (for example an [UPDATE]).
3825**
3826** See also: [sqlite3_data_count()]
3827*/
3828SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3829
3830/*
3831** CAPI3REF: Column Names In A Result Set
3832**
3833** ^These routines return the name assigned to a particular column
3834** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3835** interface returns a pointer to a zero-terminated UTF-8 string
3836** and sqlite3_column_name16() returns a pointer to a zero-terminated
3837** UTF-16 string.  ^The first parameter is the [prepared statement]
3838** that implements the [SELECT] statement. ^The second parameter is the
3839** column number.  ^The leftmost column is number 0.
3840**
3841** ^The returned string pointer is valid until either the [prepared statement]
3842** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3843** reprepared by the first call to [sqlite3_step()] for a particular run
3844** or until the next call to
3845** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3846**
3847** ^If sqlite3_malloc() fails during the processing of either routine
3848** (for example during a conversion from UTF-8 to UTF-16) then a
3849** NULL pointer is returned.
3850**
3851** ^The name of a result column is the value of the "AS" clause for
3852** that column, if there is an AS clause.  If there is no AS clause
3853** then the name of the column is unspecified and may change from
3854** one release of SQLite to the next.
3855*/
3856SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3857SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3858
3859/*
3860** CAPI3REF: Source Of Data In A Query Result
3861**
3862** ^These routines provide a means to determine the database, table, and
3863** table column that is the origin of a particular result column in
3864** [SELECT] statement.
3865** ^The name of the database or table or column can be returned as
3866** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3867** the database name, the _table_ routines return the table name, and
3868** the origin_ routines return the column name.
3869** ^The returned string is valid until the [prepared statement] is destroyed
3870** using [sqlite3_finalize()] or until the statement is automatically
3871** reprepared by the first call to [sqlite3_step()] for a particular run
3872** or until the same information is requested
3873** again in a different encoding.
3874**
3875** ^The names returned are the original un-aliased names of the
3876** database, table, and column.
3877**
3878** ^The first argument to these interfaces is a [prepared statement].
3879** ^These functions return information about the Nth result column returned by
3880** the statement, where N is the second function argument.
3881** ^The left-most column is column 0 for these routines.
3882**
3883** ^If the Nth column returned by the statement is an expression or
3884** subquery and is not a column value, then all of these functions return
3885** NULL.  ^These routine might also return NULL if a memory allocation error
3886** occurs.  ^Otherwise, they return the name of the attached database, table,
3887** or column that query result column was extracted from.
3888**
3889** ^As with all other SQLite APIs, those whose names end with "16" return
3890** UTF-16 encoded strings and the other functions return UTF-8.
3891**
3892** ^These APIs are only available if the library was compiled with the
3893** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3894**
3895** If two or more threads call one or more of these routines against the same
3896** prepared statement and column at the same time then the results are
3897** undefined.
3898**
3899** If two or more threads call one or more
3900** [sqlite3_column_database_name | column metadata interfaces]
3901** for the same [prepared statement] and result column
3902** at the same time then the results are undefined.
3903*/
3904SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3905SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3906SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3907SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3908SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3909SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3910
3911/*
3912** CAPI3REF: Declared Datatype Of A Query Result
3913**
3914** ^(The first parameter is a [prepared statement].
3915** If this statement is a [SELECT] statement and the Nth column of the
3916** returned result set of that [SELECT] is a table column (not an
3917** expression or subquery) then the declared type of the table
3918** column is returned.)^  ^If the Nth column of the result set is an
3919** expression or subquery, then a NULL pointer is returned.
3920** ^The returned string is always UTF-8 encoded.
3921**
3922** ^(For example, given the database schema:
3923**
3924** CREATE TABLE t1(c1 VARIANT);
3925**
3926** and the following statement to be compiled:
3927**
3928** SELECT c1 + 1, c1 FROM t1;
3929**
3930** this routine would return the string "VARIANT" for the second result
3931** column (i==1), and a NULL pointer for the first result column (i==0).)^
3932**
3933** ^SQLite uses dynamic run-time typing.  ^So just because a column
3934** is declared to contain a particular type does not mean that the
3935** data stored in that column is of the declared type.  SQLite is
3936** strongly typed, but the typing is dynamic not static.  ^Type
3937** is associated with individual values, not with the containers
3938** used to hold those values.
3939*/
3940SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3941SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3942
3943/*
3944** CAPI3REF: Evaluate An SQL Statement
3945**
3946** After a [prepared statement] has been prepared using either
3947** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3948** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3949** must be called one or more times to evaluate the statement.
3950**
3951** The details of the behavior of the sqlite3_step() interface depend
3952** on whether the statement was prepared using the newer "v2" interface
3953** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3954** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3955** new "v2" interface is recommended for new applications but the legacy
3956** interface will continue to be supported.
3957**
3958** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3959** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3960** ^With the "v2" interface, any of the other [result codes] or
3961** [extended result codes] might be returned as well.
3962**
3963** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3964** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3965** or occurs outside of an explicit transaction, then you can retry the
3966** statement.  If the statement is not a [COMMIT] and occurs within an
3967** explicit transaction then you should rollback the transaction before
3968** continuing.
3969**
3970** ^[SQLITE_DONE] means that the statement has finished executing
3971** successfully.  sqlite3_step() should not be called again on this virtual
3972** machine without first calling [sqlite3_reset()] to reset the virtual
3973** machine back to its initial state.
3974**
3975** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3976** is returned each time a new row of data is ready for processing by the
3977** caller. The values may be accessed using the [column access functions].
3978** sqlite3_step() is called again to retrieve the next row of data.
3979**
3980** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3981** violation) has occurred.  sqlite3_step() should not be called again on
3982** the VM. More information may be found by calling [sqlite3_errmsg()].
3983** ^With the legacy interface, a more specific error code (for example,
3984** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3985** can be obtained by calling [sqlite3_reset()] on the
3986** [prepared statement].  ^In the "v2" interface,
3987** the more specific error code is returned directly by sqlite3_step().
3988**
3989** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3990** Perhaps it was called on a [prepared statement] that has
3991** already been [sqlite3_finalize | finalized] or on one that had
3992** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3993** be the case that the same database connection is being used by two or
3994** more threads at the same moment in time.
3995**
3996** For all versions of SQLite up to and including 3.6.23.1, a call to
3997** [sqlite3_reset()] was required after sqlite3_step() returned anything
3998** other than [SQLITE_ROW] before any subsequent invocation of
3999** sqlite3_step().  Failure to reset the prepared statement using
4000** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4001** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4002** calling [sqlite3_reset()] automatically in this circumstance rather
4003** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4004** break because any application that ever receives an SQLITE_MISUSE error
4005** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4006** can be used to restore the legacy behavior.
4007**
4008** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4009** API always returns a generic error code, [SQLITE_ERROR], following any
4010** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4011** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4012** specific [error codes] that better describes the error.
4013** We admit that this is a goofy design.  The problem has been fixed
4014** with the "v2" interface.  If you prepare all of your SQL statements
4015** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4016** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4017** then the more specific [error codes] are returned directly
4018** by sqlite3_step().  The use of the "v2" interface is recommended.
4019*/
4020SQLITE_API int sqlite3_step(sqlite3_stmt*);
4021
4022/*
4023** CAPI3REF: Number of columns in a result set
4024**
4025** ^The sqlite3_data_count(P) interface returns the number of columns in the
4026** current row of the result set of [prepared statement] P.
4027** ^If prepared statement P does not have results ready to return
4028** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4029** interfaces) then sqlite3_data_count(P) returns 0.
4030** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4031** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4032** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4033** will return non-zero if previous call to [sqlite3_step](P) returned
4034** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4035** where it always returns zero since each step of that multi-step
4036** pragma returns 0 columns of data.
4037**
4038** See also: [sqlite3_column_count()]
4039*/
4040SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4041
4042/*
4043** CAPI3REF: Fundamental Datatypes
4044** KEYWORDS: SQLITE_TEXT
4045**
4046** ^(Every value in SQLite has one of five fundamental datatypes:
4047**
4048** <ul>
4049** <li> 64-bit signed integer
4050** <li> 64-bit IEEE floating point number
4051** <li> string
4052** <li> BLOB
4053** <li> NULL
4054** </ul>)^
4055**
4056** These constants are codes for each of those types.
4057**
4058** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4059** for a completely different meaning.  Software that links against both
4060** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4061** SQLITE_TEXT.
4062*/
4063#define SQLITE_INTEGER  1
4064#define SQLITE_FLOAT    2
4065#define SQLITE_BLOB     4
4066#define SQLITE_NULL     5
4067#ifdef SQLITE_TEXT
4068# undef SQLITE_TEXT
4069#else
4070# define SQLITE_TEXT     3
4071#endif
4072#define SQLITE3_TEXT     3
4073
4074/*
4075** CAPI3REF: Result Values From A Query
4076** KEYWORDS: {column access functions}
4077**
4078** These routines form the "result set" interface.
4079**
4080** ^These routines return information about a single column of the current
4081** result row of a query.  ^In every case the first argument is a pointer
4082** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4083** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4084** and the second argument is the index of the column for which information
4085** should be returned. ^The leftmost column of the result set has the index 0.
4086** ^The number of columns in the result can be determined using
4087** [sqlite3_column_count()].
4088**
4089** If the SQL statement does not currently point to a valid row, or if the
4090** column index is out of range, the result is undefined.
4091** These routines may only be called when the most recent call to
4092** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4093** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4094** If any of these routines are called after [sqlite3_reset()] or
4095** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4096** something other than [SQLITE_ROW], the results are undefined.
4097** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4098** are called from a different thread while any of these routines
4099** are pending, then the results are undefined.
4100**
4101** ^The sqlite3_column_type() routine returns the
4102** [SQLITE_INTEGER | datatype code] for the initial data type
4103** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4104** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4105** returned by sqlite3_column_type() is only meaningful if no type
4106** conversions have occurred as described below.  After a type conversion,
4107** the value returned by sqlite3_column_type() is undefined.  Future
4108** versions of SQLite may change the behavior of sqlite3_column_type()
4109** following a type conversion.
4110**
4111** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4112** routine returns the number of bytes in that BLOB or string.
4113** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4114** the string to UTF-8 and then returns the number of bytes.
4115** ^If the result is a numeric value then sqlite3_column_bytes() uses
4116** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4117** the number of bytes in that string.
4118** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4119**
4120** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4121** routine returns the number of bytes in that BLOB or string.
4122** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4123** the string to UTF-16 and then returns the number of bytes.
4124** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4125** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4126** the number of bytes in that string.
4127** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4128**
4129** ^The values returned by [sqlite3_column_bytes()] and
4130** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4131** of the string.  ^For clarity: the values returned by
4132** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4133** bytes in the string, not the number of characters.
4134**
4135** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4136** even empty strings, are always zero-terminated.  ^The return
4137** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4138**
4139** ^The object returned by [sqlite3_column_value()] is an
4140** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4141** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4142** If the [unprotected sqlite3_value] object returned by
4143** [sqlite3_column_value()] is used in any other way, including calls
4144** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4145** or [sqlite3_value_bytes()], then the behavior is undefined.
4146**
4147** These routines attempt to convert the value where appropriate.  ^For
4148** example, if the internal representation is FLOAT and a text result
4149** is requested, [sqlite3_snprintf()] is used internally to perform the
4150** conversion automatically.  ^(The following table details the conversions
4151** that are applied:
4152**
4153** <blockquote>
4154** <table border="1">
4155** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4156**
4157** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4158** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4159** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4160** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4161** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4162** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4163** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4164** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4165** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4166** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4167** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4168** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4169** <tr><td>  TEXT    <td>   BLOB    <td> No change
4170** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4171** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4172** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4173** </table>
4174** </blockquote>)^
4175**
4176** The table above makes reference to standard C library functions atoi()
4177** and atof().  SQLite does not really use these functions.  It has its
4178** own equivalent internal routines.  The atoi() and atof() names are
4179** used in the table for brevity and because they are familiar to most
4180** C programmers.
4181**
4182** Note that when type conversions occur, pointers returned by prior
4183** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4184** sqlite3_column_text16() may be invalidated.
4185** Type conversions and pointer invalidations might occur
4186** in the following cases:
4187**
4188** <ul>
4189** <li> The initial content is a BLOB and sqlite3_column_text() or
4190**      sqlite3_column_text16() is called.  A zero-terminator might
4191**      need to be added to the string.</li>
4192** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4193**      sqlite3_column_text16() is called.  The content must be converted
4194**      to UTF-16.</li>
4195** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4196**      sqlite3_column_text() is called.  The content must be converted
4197**      to UTF-8.</li>
4198** </ul>
4199**
4200** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4201** not invalidate a prior pointer, though of course the content of the buffer
4202** that the prior pointer references will have been modified.  Other kinds
4203** of conversion are done in place when it is possible, but sometimes they
4204** are not possible and in those cases prior pointers are invalidated.
4205**
4206** The safest and easiest to remember policy is to invoke these routines
4207** in one of the following ways:
4208**
4209** <ul>
4210**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4211**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4212**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4213** </ul>
4214**
4215** In other words, you should call sqlite3_column_text(),
4216** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4217** into the desired format, then invoke sqlite3_column_bytes() or
4218** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4219** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4220** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4221** with calls to sqlite3_column_bytes().
4222**
4223** ^The pointers returned are valid until a type conversion occurs as
4224** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4225** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4226** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4227** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4228** [sqlite3_free()].
4229**
4230** ^(If a memory allocation error occurs during the evaluation of any
4231** of these routines, a default value is returned.  The default value
4232** is either the integer 0, the floating point number 0.0, or a NULL
4233** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4234** [SQLITE_NOMEM].)^
4235*/
4236SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4237SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4238SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4239SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4240SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4241SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4242SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4243SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4244SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4245SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4246
4247/*
4248** CAPI3REF: Destroy A Prepared Statement Object
4249**
4250** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4251** ^If the most recent evaluation of the statement encountered no errors
4252** or if the statement is never been evaluated, then sqlite3_finalize() returns
4253** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4254** sqlite3_finalize(S) returns the appropriate [error code] or
4255** [extended error code].
4256**
4257** ^The sqlite3_finalize(S) routine can be called at any point during
4258** the life cycle of [prepared statement] S:
4259** before statement S is ever evaluated, after
4260** one or more calls to [sqlite3_reset()], or after any call
4261** to [sqlite3_step()] regardless of whether or not the statement has
4262** completed execution.
4263**
4264** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4265**
4266** The application must finalize every [prepared statement] in order to avoid
4267** resource leaks.  It is a grievous error for the application to try to use
4268** a prepared statement after it has been finalized.  Any use of a prepared
4269** statement after it has been finalized can result in undefined and
4270** undesirable behavior such as segfaults and heap corruption.
4271*/
4272SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4273
4274/*
4275** CAPI3REF: Reset A Prepared Statement Object
4276**
4277** The sqlite3_reset() function is called to reset a [prepared statement]
4278** object back to its initial state, ready to be re-executed.
4279** ^Any SQL statement variables that had values bound to them using
4280** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4281** Use [sqlite3_clear_bindings()] to reset the bindings.
4282**
4283** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4284** back to the beginning of its program.
4285**
4286** ^If the most recent call to [sqlite3_step(S)] for the
4287** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4288** or if [sqlite3_step(S)] has never before been called on S,
4289** then [sqlite3_reset(S)] returns [SQLITE_OK].
4290**
4291** ^If the most recent call to [sqlite3_step(S)] for the
4292** [prepared statement] S indicated an error, then
4293** [sqlite3_reset(S)] returns an appropriate [error code].
4294**
4295** ^The [sqlite3_reset(S)] interface does not change the values
4296** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4297*/
4298SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4299
4300/*
4301** CAPI3REF: Create Or Redefine SQL Functions
4302** KEYWORDS: {function creation routines}
4303** KEYWORDS: {application-defined SQL function}
4304** KEYWORDS: {application-defined SQL functions}
4305**
4306** ^These functions (collectively known as "function creation routines")
4307** are used to add SQL functions or aggregates or to redefine the behavior
4308** of existing SQL functions or aggregates.  The only differences between
4309** these routines are the text encoding expected for
4310** the second parameter (the name of the function being created)
4311** and the presence or absence of a destructor callback for
4312** the application data pointer.
4313**
4314** ^The first parameter is the [database connection] to which the SQL
4315** function is to be added.  ^If an application uses more than one database
4316** connection then application-defined SQL functions must be added
4317** to each database connection separately.
4318**
4319** ^The second parameter is the name of the SQL function to be created or
4320** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4321** representation, exclusive of the zero-terminator.  ^Note that the name
4322** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4323** ^Any attempt to create a function with a longer name
4324** will result in [SQLITE_MISUSE] being returned.
4325**
4326** ^The third parameter (nArg)
4327** is the number of arguments that the SQL function or
4328** aggregate takes. ^If this parameter is -1, then the SQL function or
4329** aggregate may take any number of arguments between 0 and the limit
4330** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4331** parameter is less than -1 or greater than 127 then the behavior is
4332** undefined.
4333**
4334** ^The fourth parameter, eTextRep, specifies what
4335** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4336** its parameters.  Every SQL function implementation must be able to work
4337** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4338** more efficient with one encoding than another.  ^An application may
4339** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4340** times with the same function but with different values of eTextRep.
4341** ^When multiple implementations of the same function are available, SQLite
4342** will pick the one that involves the least amount of data conversion.
4343** If there is only a single implementation which does not care what text
4344** encoding is used, then the fourth argument should be [SQLITE_ANY].
4345**
4346** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4347** function can gain access to this pointer using [sqlite3_user_data()].)^
4348**
4349** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4350** pointers to C-language functions that implement the SQL function or
4351** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4352** callback only; NULL pointers must be passed as the xStep and xFinal
4353** parameters. ^An aggregate SQL function requires an implementation of xStep
4354** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4355** SQL function or aggregate, pass NULL pointers for all three function
4356** callbacks.
4357**
4358** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4359** then it is destructor for the application data pointer.
4360** The destructor is invoked when the function is deleted, either by being
4361** overloaded or when the database connection closes.)^
4362** ^The destructor is also invoked if the call to
4363** sqlite3_create_function_v2() fails.
4364** ^When the destructor callback of the tenth parameter is invoked, it
4365** is passed a single argument which is a copy of the application data
4366** pointer which was the fifth parameter to sqlite3_create_function_v2().
4367**
4368** ^It is permitted to register multiple implementations of the same
4369** functions with the same name but with either differing numbers of
4370** arguments or differing preferred text encodings.  ^SQLite will use
4371** the implementation that most closely matches the way in which the
4372** SQL function is used.  ^A function implementation with a non-negative
4373** nArg parameter is a better match than a function implementation with
4374** a negative nArg.  ^A function where the preferred text encoding
4375** matches the database encoding is a better
4376** match than a function where the encoding is different.
4377** ^A function where the encoding difference is between UTF16le and UTF16be
4378** is a closer match than a function where the encoding difference is
4379** between UTF8 and UTF16.
4380**
4381** ^Built-in functions may be overloaded by new application-defined functions.
4382**
4383** ^An application-defined function is permitted to call other
4384** SQLite interfaces.  However, such calls must not
4385** close the database connection nor finalize or reset the prepared
4386** statement in which the function is running.
4387*/
4388SQLITE_API int sqlite3_create_function(
4389  sqlite3 *db,
4390  const char *zFunctionName,
4391  int nArg,
4392  int eTextRep,
4393  void *pApp,
4394  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4395  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4396  void (*xFinal)(sqlite3_context*)
4397);
4398SQLITE_API int sqlite3_create_function16(
4399  sqlite3 *db,
4400  const void *zFunctionName,
4401  int nArg,
4402  int eTextRep,
4403  void *pApp,
4404  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4405  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4406  void (*xFinal)(sqlite3_context*)
4407);
4408SQLITE_API int sqlite3_create_function_v2(
4409  sqlite3 *db,
4410  const char *zFunctionName,
4411  int nArg,
4412  int eTextRep,
4413  void *pApp,
4414  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4415  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4416  void (*xFinal)(sqlite3_context*),
4417  void(*xDestroy)(void*)
4418);
4419
4420/*
4421** CAPI3REF: Text Encodings
4422**
4423** These constant define integer codes that represent the various
4424** text encodings supported by SQLite.
4425*/
4426#define SQLITE_UTF8           1
4427#define SQLITE_UTF16LE        2
4428#define SQLITE_UTF16BE        3
4429#define SQLITE_UTF16          4    /* Use native byte order */
4430#define SQLITE_ANY            5    /* sqlite3_create_function only */
4431#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4432
4433/*
4434** CAPI3REF: Deprecated Functions
4435** DEPRECATED
4436**
4437** These functions are [deprecated].  In order to maintain
4438** backwards compatibility with older code, these functions continue
4439** to be supported.  However, new applications should avoid
4440** the use of these functions.  To help encourage people to avoid
4441** using these functions, we are not going to tell you what they do.
4442*/
4443#ifndef SQLITE_OMIT_DEPRECATED
4444SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4445SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4446SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4447SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4448SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4449SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4450#endif
4451
4452/*
4453** CAPI3REF: Obtaining SQL Function Parameter Values
4454**
4455** The C-language implementation of SQL functions and aggregates uses
4456** this set of interface routines to access the parameter values on
4457** the function or aggregate.
4458**
4459** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4460** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4461** define callbacks that implement the SQL functions and aggregates.
4462** The 3rd parameter to these callbacks is an array of pointers to
4463** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4464** each parameter to the SQL function.  These routines are used to
4465** extract values from the [sqlite3_value] objects.
4466**
4467** These routines work only with [protected sqlite3_value] objects.
4468** Any attempt to use these routines on an [unprotected sqlite3_value]
4469** object results in undefined behavior.
4470**
4471** ^These routines work just like the corresponding [column access functions]
4472** except that  these routines take a single [protected sqlite3_value] object
4473** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4474**
4475** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4476** in the native byte-order of the host machine.  ^The
4477** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4478** extract UTF-16 strings as big-endian and little-endian respectively.
4479**
4480** ^(The sqlite3_value_numeric_type() interface attempts to apply
4481** numeric affinity to the value.  This means that an attempt is
4482** made to convert the value to an integer or floating point.  If
4483** such a conversion is possible without loss of information (in other
4484** words, if the value is a string that looks like a number)
4485** then the conversion is performed.  Otherwise no conversion occurs.
4486** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4487**
4488** Please pay particular attention to the fact that the pointer returned
4489** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4490** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4491** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4492** or [sqlite3_value_text16()].
4493**
4494** These routines must be called from the same thread as
4495** the SQL function that supplied the [sqlite3_value*] parameters.
4496*/
4497SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4498SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4499SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4500SQLITE_API double sqlite3_value_double(sqlite3_value*);
4501SQLITE_API int sqlite3_value_int(sqlite3_value*);
4502SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4503SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4504SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4505SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4506SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4507SQLITE_API int sqlite3_value_type(sqlite3_value*);
4508SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4509
4510/*
4511** CAPI3REF: Obtain Aggregate Function Context
4512**
4513** Implementations of aggregate SQL functions use this
4514** routine to allocate memory for storing their state.
4515**
4516** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4517** for a particular aggregate function, SQLite
4518** allocates N of memory, zeroes out that memory, and returns a pointer
4519** to the new memory. ^On second and subsequent calls to
4520** sqlite3_aggregate_context() for the same aggregate function instance,
4521** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4522** called once for each invocation of the xStep callback and then one
4523** last time when the xFinal callback is invoked.  ^(When no rows match
4524** an aggregate query, the xStep() callback of the aggregate function
4525** implementation is never called and xFinal() is called exactly once.
4526** In those cases, sqlite3_aggregate_context() might be called for the
4527** first time from within xFinal().)^
4528**
4529** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4530** less than or equal to zero or if a memory allocate error occurs.
4531**
4532** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4533** determined by the N parameter on first successful call.  Changing the
4534** value of N in subsequent call to sqlite3_aggregate_context() within
4535** the same aggregate function instance will not resize the memory
4536** allocation.)^
4537**
4538** ^SQLite automatically frees the memory allocated by
4539** sqlite3_aggregate_context() when the aggregate query concludes.
4540**
4541** The first parameter must be a copy of the
4542** [sqlite3_context | SQL function context] that is the first parameter
4543** to the xStep or xFinal callback routine that implements the aggregate
4544** function.
4545**
4546** This routine must be called from the same thread in which
4547** the aggregate SQL function is running.
4548*/
4549SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4550
4551/*
4552** CAPI3REF: User Data For Functions
4553**
4554** ^The sqlite3_user_data() interface returns a copy of
4555** the pointer that was the pUserData parameter (the 5th parameter)
4556** of the [sqlite3_create_function()]
4557** and [sqlite3_create_function16()] routines that originally
4558** registered the application defined function.
4559**
4560** This routine must be called from the same thread in which
4561** the application-defined function is running.
4562*/
4563SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4564
4565/*
4566** CAPI3REF: Database Connection For Functions
4567**
4568** ^The sqlite3_context_db_handle() interface returns a copy of
4569** the pointer to the [database connection] (the 1st parameter)
4570** of the [sqlite3_create_function()]
4571** and [sqlite3_create_function16()] routines that originally
4572** registered the application defined function.
4573*/
4574SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4575
4576/*
4577** CAPI3REF: Function Auxiliary Data
4578**
4579** The following two functions may be used by scalar SQL functions to
4580** associate metadata with argument values. If the same value is passed to
4581** multiple invocations of the same SQL function during query execution, under
4582** some circumstances the associated metadata may be preserved. This may
4583** be used, for example, to add a regular-expression matching scalar
4584** function. The compiled version of the regular expression is stored as
4585** metadata associated with the SQL value passed as the regular expression
4586** pattern.  The compiled regular expression can be reused on multiple
4587** invocations of the same function so that the original pattern string
4588** does not need to be recompiled on each invocation.
4589**
4590** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4591** associated by the sqlite3_set_auxdata() function with the Nth argument
4592** value to the application-defined function. ^If no metadata has been ever
4593** been set for the Nth argument of the function, or if the corresponding
4594** function parameter has changed since the meta-data was set,
4595** then sqlite3_get_auxdata() returns a NULL pointer.
4596**
4597** ^The sqlite3_set_auxdata() interface saves the metadata
4598** pointed to by its 3rd parameter as the metadata for the N-th
4599** argument of the application-defined function.  Subsequent
4600** calls to sqlite3_get_auxdata() might return this data, if it has
4601** not been destroyed.
4602** ^If it is not NULL, SQLite will invoke the destructor
4603** function given by the 4th parameter to sqlite3_set_auxdata() on
4604** the metadata when the corresponding function parameter changes
4605** or when the SQL statement completes, whichever comes first.
4606**
4607** SQLite is free to call the destructor and drop metadata on any
4608** parameter of any function at any time.  ^The only guarantee is that
4609** the destructor will be called before the metadata is dropped.
4610**
4611** ^(In practice, metadata is preserved between function calls for
4612** expressions that are constant at compile time. This includes literal
4613** values and [parameters].)^
4614**
4615** These routines must be called from the same thread in which
4616** the SQL function is running.
4617*/
4618SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4619SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4620
4621
4622/*
4623** CAPI3REF: Constants Defining Special Destructor Behavior
4624**
4625** These are special values for the destructor that is passed in as the
4626** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4627** argument is SQLITE_STATIC, it means that the content pointer is constant
4628** and will never change.  It does not need to be destroyed.  ^The
4629** SQLITE_TRANSIENT value means that the content will likely change in
4630** the near future and that SQLite should make its own private copy of
4631** the content before returning.
4632**
4633** The typedef is necessary to work around problems in certain
4634** C++ compilers.  See ticket #2191.
4635*/
4636typedef void (*sqlite3_destructor_type)(void*);
4637#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4638#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4639
4640/*
4641** CAPI3REF: Setting The Result Of An SQL Function
4642**
4643** These routines are used by the xFunc or xFinal callbacks that
4644** implement SQL functions and aggregates.  See
4645** [sqlite3_create_function()] and [sqlite3_create_function16()]
4646** for additional information.
4647**
4648** These functions work very much like the [parameter binding] family of
4649** functions used to bind values to host parameters in prepared statements.
4650** Refer to the [SQL parameter] documentation for additional information.
4651**
4652** ^The sqlite3_result_blob() interface sets the result from
4653** an application-defined function to be the BLOB whose content is pointed
4654** to by the second parameter and which is N bytes long where N is the
4655** third parameter.
4656**
4657** ^The sqlite3_result_zeroblob() interfaces set the result of
4658** the application-defined function to be a BLOB containing all zero
4659** bytes and N bytes in size, where N is the value of the 2nd parameter.
4660**
4661** ^The sqlite3_result_double() interface sets the result from
4662** an application-defined function to be a floating point value specified
4663** by its 2nd argument.
4664**
4665** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4666** cause the implemented SQL function to throw an exception.
4667** ^SQLite uses the string pointed to by the
4668** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4669** as the text of an error message.  ^SQLite interprets the error
4670** message string from sqlite3_result_error() as UTF-8. ^SQLite
4671** interprets the string from sqlite3_result_error16() as UTF-16 in native
4672** byte order.  ^If the third parameter to sqlite3_result_error()
4673** or sqlite3_result_error16() is negative then SQLite takes as the error
4674** message all text up through the first zero character.
4675** ^If the third parameter to sqlite3_result_error() or
4676** sqlite3_result_error16() is non-negative then SQLite takes that many
4677** bytes (not characters) from the 2nd parameter as the error message.
4678** ^The sqlite3_result_error() and sqlite3_result_error16()
4679** routines make a private copy of the error message text before
4680** they return.  Hence, the calling function can deallocate or
4681** modify the text after they return without harm.
4682** ^The sqlite3_result_error_code() function changes the error code
4683** returned by SQLite as a result of an error in a function.  ^By default,
4684** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4685** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4686**
4687** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4688** indicating that a string or BLOB is too long to represent.
4689**
4690** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4691** indicating that a memory allocation failed.
4692**
4693** ^The sqlite3_result_int() interface sets the return value
4694** of the application-defined function to be the 32-bit signed integer
4695** value given in the 2nd argument.
4696** ^The sqlite3_result_int64() interface sets the return value
4697** of the application-defined function to be the 64-bit signed integer
4698** value given in the 2nd argument.
4699**
4700** ^The sqlite3_result_null() interface sets the return value
4701** of the application-defined function to be NULL.
4702**
4703** ^The sqlite3_result_text(), sqlite3_result_text16(),
4704** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4705** set the return value of the application-defined function to be
4706** a text string which is represented as UTF-8, UTF-16 native byte order,
4707** UTF-16 little endian, or UTF-16 big endian, respectively.
4708** ^SQLite takes the text result from the application from
4709** the 2nd parameter of the sqlite3_result_text* interfaces.
4710** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4711** is negative, then SQLite takes result text from the 2nd parameter
4712** through the first zero character.
4713** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4714** is non-negative, then as many bytes (not characters) of the text
4715** pointed to by the 2nd parameter are taken as the application-defined
4716** function result.  If the 3rd parameter is non-negative, then it
4717** must be the byte offset into the string where the NUL terminator would
4718** appear if the string where NUL terminated.  If any NUL characters occur
4719** in the string at a byte offset that is less than the value of the 3rd
4720** parameter, then the resulting string will contain embedded NULs and the
4721** result of expressions operating on strings with embedded NULs is undefined.
4722** ^If the 4th parameter to the sqlite3_result_text* interfaces
4723** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4724** function as the destructor on the text or BLOB result when it has
4725** finished using that result.
4726** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4727** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4728** assumes that the text or BLOB result is in constant space and does not
4729** copy the content of the parameter nor call a destructor on the content
4730** when it has finished using that result.
4731** ^If the 4th parameter to the sqlite3_result_text* interfaces
4732** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4733** then SQLite makes a copy of the result into space obtained from
4734** from [sqlite3_malloc()] before it returns.
4735**
4736** ^The sqlite3_result_value() interface sets the result of
4737** the application-defined function to be a copy the
4738** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4739** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4740** so that the [sqlite3_value] specified in the parameter may change or
4741** be deallocated after sqlite3_result_value() returns without harm.
4742** ^A [protected sqlite3_value] object may always be used where an
4743** [unprotected sqlite3_value] object is required, so either
4744** kind of [sqlite3_value] object can be used with this interface.
4745**
4746** If these routines are called from within the different thread
4747** than the one containing the application-defined function that received
4748** the [sqlite3_context] pointer, the results are undefined.
4749*/
4750SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4751SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4752SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4753SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4754SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4755SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4756SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4757SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4758SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4759SQLITE_API void sqlite3_result_null(sqlite3_context*);
4760SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4761SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4762SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4763SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4764SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4765SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4766
4767/*
4768** CAPI3REF: Define New Collating Sequences
4769**
4770** ^These functions add, remove, or modify a [collation] associated
4771** with the [database connection] specified as the first argument.
4772**
4773** ^The name of the collation is a UTF-8 string
4774** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4775** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4776** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4777** considered to be the same name.
4778**
4779** ^(The third argument (eTextRep) must be one of the constants:
4780** <ul>
4781** <li> [SQLITE_UTF8],
4782** <li> [SQLITE_UTF16LE],
4783** <li> [SQLITE_UTF16BE],
4784** <li> [SQLITE_UTF16], or
4785** <li> [SQLITE_UTF16_ALIGNED].
4786** </ul>)^
4787** ^The eTextRep argument determines the encoding of strings passed
4788** to the collating function callback, xCallback.
4789** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4790** force strings to be UTF16 with native byte order.
4791** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4792** on an even byte address.
4793**
4794** ^The fourth argument, pArg, is an application data pointer that is passed
4795** through as the first argument to the collating function callback.
4796**
4797** ^The fifth argument, xCallback, is a pointer to the collating function.
4798** ^Multiple collating functions can be registered using the same name but
4799** with different eTextRep parameters and SQLite will use whichever
4800** function requires the least amount of data transformation.
4801** ^If the xCallback argument is NULL then the collating function is
4802** deleted.  ^When all collating functions having the same name are deleted,
4803** that collation is no longer usable.
4804**
4805** ^The collating function callback is invoked with a copy of the pArg
4806** application data pointer and with two strings in the encoding specified
4807** by the eTextRep argument.  The collating function must return an
4808** integer that is negative, zero, or positive
4809** if the first string is less than, equal to, or greater than the second,
4810** respectively.  A collating function must always return the same answer
4811** given the same inputs.  If two or more collating functions are registered
4812** to the same collation name (using different eTextRep values) then all
4813** must give an equivalent answer when invoked with equivalent strings.
4814** The collating function must obey the following properties for all
4815** strings A, B, and C:
4816**
4817** <ol>
4818** <li> If A==B then B==A.
4819** <li> If A==B and B==C then A==C.
4820** <li> If A&lt;B THEN B&gt;A.
4821** <li> If A&lt;B and B&lt;C then A&lt;C.
4822** </ol>
4823**
4824** If a collating function fails any of the above constraints and that
4825** collating function is  registered and used, then the behavior of SQLite
4826** is undefined.
4827**
4828** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4829** with the addition that the xDestroy callback is invoked on pArg when
4830** the collating function is deleted.
4831** ^Collating functions are deleted when they are overridden by later
4832** calls to the collation creation functions or when the
4833** [database connection] is closed using [sqlite3_close()].
4834**
4835** ^The xDestroy callback is <u>not</u> called if the
4836** sqlite3_create_collation_v2() function fails.  Applications that invoke
4837** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4838** check the return code and dispose of the application data pointer
4839** themselves rather than expecting SQLite to deal with it for them.
4840** This is different from every other SQLite interface.  The inconsistency
4841** is unfortunate but cannot be changed without breaking backwards
4842** compatibility.
4843**
4844** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4845*/
4846SQLITE_API int sqlite3_create_collation(
4847  sqlite3*,
4848  const char *zName,
4849  int eTextRep,
4850  void *pArg,
4851  int(*xCompare)(void*,int,const void*,int,const void*)
4852);
4853SQLITE_API int sqlite3_create_collation_v2(
4854  sqlite3*,
4855  const char *zName,
4856  int eTextRep,
4857  void *pArg,
4858  int(*xCompare)(void*,int,const void*,int,const void*),
4859  void(*xDestroy)(void*)
4860);
4861SQLITE_API int sqlite3_create_collation16(
4862  sqlite3*,
4863  const void *zName,
4864  int eTextRep,
4865  void *pArg,
4866  int(*xCompare)(void*,int,const void*,int,const void*)
4867);
4868
4869/*
4870** CAPI3REF: Collation Needed Callbacks
4871**
4872** ^To avoid having to register all collation sequences before a database
4873** can be used, a single callback function may be registered with the
4874** [database connection] to be invoked whenever an undefined collation
4875** sequence is required.
4876**
4877** ^If the function is registered using the sqlite3_collation_needed() API,
4878** then it is passed the names of undefined collation sequences as strings
4879** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4880** the names are passed as UTF-16 in machine native byte order.
4881** ^A call to either function replaces the existing collation-needed callback.
4882**
4883** ^(When the callback is invoked, the first argument passed is a copy
4884** of the second argument to sqlite3_collation_needed() or
4885** sqlite3_collation_needed16().  The second argument is the database
4886** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4887** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4888** sequence function required.  The fourth parameter is the name of the
4889** required collation sequence.)^
4890**
4891** The callback function should register the desired collation using
4892** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4893** [sqlite3_create_collation_v2()].
4894*/
4895SQLITE_API int sqlite3_collation_needed(
4896  sqlite3*,
4897  void*,
4898  void(*)(void*,sqlite3*,int eTextRep,const char*)
4899);
4900SQLITE_API int sqlite3_collation_needed16(
4901  sqlite3*,
4902  void*,
4903  void(*)(void*,sqlite3*,int eTextRep,const void*)
4904);
4905
4906#ifdef SQLITE_HAS_CODEC
4907/*
4908** Specify the key for an encrypted database.  This routine should be
4909** called right after sqlite3_open().
4910**
4911** The code to implement this API is not available in the public release
4912** of SQLite.
4913*/
4914SQLITE_API int sqlite3_key(
4915  sqlite3 *db,                   /* Database to be rekeyed */
4916  const void *pKey, int nKey     /* The key */
4917);
4918
4919/*
4920** Change the key on an open database.  If the current database is not
4921** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4922** database is decrypted.
4923**
4924** The code to implement this API is not available in the public release
4925** of SQLite.
4926*/
4927SQLITE_API int sqlite3_rekey(
4928  sqlite3 *db,                   /* Database to be rekeyed */
4929  const void *pKey, int nKey     /* The new key */
4930);
4931
4932/*
4933** Specify the activation key for a SEE database.  Unless
4934** activated, none of the SEE routines will work.
4935*/
4936SQLITE_API void sqlite3_activate_see(
4937  const char *zPassPhrase        /* Activation phrase */
4938);
4939#endif
4940
4941#ifdef SQLITE_ENABLE_CEROD
4942/*
4943** Specify the activation key for a CEROD database.  Unless
4944** activated, none of the CEROD routines will work.
4945*/
4946SQLITE_API void sqlite3_activate_cerod(
4947  const char *zPassPhrase        /* Activation phrase */
4948);
4949#endif
4950
4951/*
4952** CAPI3REF: Suspend Execution For A Short Time
4953**
4954** The sqlite3_sleep() function causes the current thread to suspend execution
4955** for at least a number of milliseconds specified in its parameter.
4956**
4957** If the operating system does not support sleep requests with
4958** millisecond time resolution, then the time will be rounded up to
4959** the nearest second. The number of milliseconds of sleep actually
4960** requested from the operating system is returned.
4961**
4962** ^SQLite implements this interface by calling the xSleep()
4963** method of the default [sqlite3_vfs] object.  If the xSleep() method
4964** of the default VFS is not implemented correctly, or not implemented at
4965** all, then the behavior of sqlite3_sleep() may deviate from the description
4966** in the previous paragraphs.
4967*/
4968SQLITE_API int sqlite3_sleep(int);
4969
4970/*
4971** CAPI3REF: Name Of The Folder Holding Temporary Files
4972**
4973** ^(If this global variable is made to point to a string which is
4974** the name of a folder (a.k.a. directory), then all temporary files
4975** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4976** will be placed in that directory.)^  ^If this variable
4977** is a NULL pointer, then SQLite performs a search for an appropriate
4978** temporary file directory.
4979**
4980** It is not safe to read or modify this variable in more than one
4981** thread at a time.  It is not safe to read or modify this variable
4982** if a [database connection] is being used at the same time in a separate
4983** thread.
4984** It is intended that this variable be set once
4985** as part of process initialization and before any SQLite interface
4986** routines have been called and that this variable remain unchanged
4987** thereafter.
4988**
4989** ^The [temp_store_directory pragma] may modify this variable and cause
4990** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4991** the [temp_store_directory pragma] always assumes that any string
4992** that this variable points to is held in memory obtained from
4993** [sqlite3_malloc] and the pragma may attempt to free that memory
4994** using [sqlite3_free].
4995** Hence, if this variable is modified directly, either it should be
4996** made NULL or made to point to memory obtained from [sqlite3_malloc]
4997** or else the use of the [temp_store_directory pragma] should be avoided.
4998*/
4999SQLITE_API char *sqlite3_temp_directory;
5000
5001/*
5002** CAPI3REF: Test For Auto-Commit Mode
5003** KEYWORDS: {autocommit mode}
5004**
5005** ^The sqlite3_get_autocommit() interface returns non-zero or
5006** zero if the given database connection is or is not in autocommit mode,
5007** respectively.  ^Autocommit mode is on by default.
5008** ^Autocommit mode is disabled by a [BEGIN] statement.
5009** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5010**
5011** If certain kinds of errors occur on a statement within a multi-statement
5012** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5013** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5014** transaction might be rolled back automatically.  The only way to
5015** find out whether SQLite automatically rolled back the transaction after
5016** an error is to use this function.
5017**
5018** If another thread changes the autocommit status of the database
5019** connection while this routine is running, then the return value
5020** is undefined.
5021*/
5022SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5023
5024/*
5025** CAPI3REF: Find The Database Handle Of A Prepared Statement
5026**
5027** ^The sqlite3_db_handle interface returns the [database connection] handle
5028** to which a [prepared statement] belongs.  ^The [database connection]
5029** returned by sqlite3_db_handle is the same [database connection]
5030** that was the first argument
5031** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5032** create the statement in the first place.
5033*/
5034SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5035
5036/*
5037** CAPI3REF: Return The Filename For A Database Connection
5038**
5039** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5040** associated with database N of connection D.  ^The main database file
5041** has the name "main".  If there is no attached database N on the database
5042** connection D, or if database N is a temporary or in-memory database, then
5043** a NULL pointer is returned.
5044**
5045** ^The filename returned by this function is the output of the
5046** xFullPathname method of the [VFS].  ^In other words, the filename
5047** will be an absolute pathname, even if the filename used
5048** to open the database originally was a URI or relative pathname.
5049*/
5050SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5051
5052/*
5053** CAPI3REF: Determine if a database is read-only
5054**
5055** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5056** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5057** the name of a database on connection D.
5058*/
5059SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5060
5061/*
5062** CAPI3REF: Find the next prepared statement
5063**
5064** ^This interface returns a pointer to the next [prepared statement] after
5065** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5066** then this interface returns a pointer to the first prepared statement
5067** associated with the database connection pDb.  ^If no prepared statement
5068** satisfies the conditions of this routine, it returns NULL.
5069**
5070** The [database connection] pointer D in a call to
5071** [sqlite3_next_stmt(D,S)] must refer to an open database
5072** connection and in particular must not be a NULL pointer.
5073*/
5074SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5075
5076/*
5077** CAPI3REF: Commit And Rollback Notification Callbacks
5078**
5079** ^The sqlite3_commit_hook() interface registers a callback
5080** function to be invoked whenever a transaction is [COMMIT | committed].
5081** ^Any callback set by a previous call to sqlite3_commit_hook()
5082** for the same database connection is overridden.
5083** ^The sqlite3_rollback_hook() interface registers a callback
5084** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5085** ^Any callback set by a previous call to sqlite3_rollback_hook()
5086** for the same database connection is overridden.
5087** ^The pArg argument is passed through to the callback.
5088** ^If the callback on a commit hook function returns non-zero,
5089** then the commit is converted into a rollback.
5090**
5091** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5092** return the P argument from the previous call of the same function
5093** on the same [database connection] D, or NULL for
5094** the first call for each function on D.
5095**
5096** The commit and rollback hook callbacks are not reentrant.
5097** The callback implementation must not do anything that will modify
5098** the database connection that invoked the callback.  Any actions
5099** to modify the database connection must be deferred until after the
5100** completion of the [sqlite3_step()] call that triggered the commit
5101** or rollback hook in the first place.
5102** Note that running any other SQL statements, including SELECT statements,
5103** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5104** the database connections for the meaning of "modify" in this paragraph.
5105**
5106** ^Registering a NULL function disables the callback.
5107**
5108** ^When the commit hook callback routine returns zero, the [COMMIT]
5109** operation is allowed to continue normally.  ^If the commit hook
5110** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5111** ^The rollback hook is invoked on a rollback that results from a commit
5112** hook returning non-zero, just as it would be with any other rollback.
5113**
5114** ^For the purposes of this API, a transaction is said to have been
5115** rolled back if an explicit "ROLLBACK" statement is executed, or
5116** an error or constraint causes an implicit rollback to occur.
5117** ^The rollback callback is not invoked if a transaction is
5118** automatically rolled back because the database connection is closed.
5119**
5120** See also the [sqlite3_update_hook()] interface.
5121*/
5122SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5123SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5124
5125/*
5126** CAPI3REF: Data Change Notification Callbacks
5127**
5128** ^The sqlite3_update_hook() interface registers a callback function
5129** with the [database connection] identified by the first argument
5130** to be invoked whenever a row is updated, inserted or deleted.
5131** ^Any callback set by a previous call to this function
5132** for the same database connection is overridden.
5133**
5134** ^The second argument is a pointer to the function to invoke when a
5135** row is updated, inserted or deleted.
5136** ^The first argument to the callback is a copy of the third argument
5137** to sqlite3_update_hook().
5138** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5139** or [SQLITE_UPDATE], depending on the operation that caused the callback
5140** to be invoked.
5141** ^The third and fourth arguments to the callback contain pointers to the
5142** database and table name containing the affected row.
5143** ^The final callback parameter is the [rowid] of the row.
5144** ^In the case of an update, this is the [rowid] after the update takes place.
5145**
5146** ^(The update hook is not invoked when internal system tables are
5147** modified (i.e. sqlite_master and sqlite_sequence).)^
5148**
5149** ^In the current implementation, the update hook
5150** is not invoked when duplication rows are deleted because of an
5151** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5152** invoked when rows are deleted using the [truncate optimization].
5153** The exceptions defined in this paragraph might change in a future
5154** release of SQLite.
5155**
5156** The update hook implementation must not do anything that will modify
5157** the database connection that invoked the update hook.  Any actions
5158** to modify the database connection must be deferred until after the
5159** completion of the [sqlite3_step()] call that triggered the update hook.
5160** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5161** database connections for the meaning of "modify" in this paragraph.
5162**
5163** ^The sqlite3_update_hook(D,C,P) function
5164** returns the P argument from the previous call
5165** on the same [database connection] D, or NULL for
5166** the first call on D.
5167**
5168** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5169** interfaces.
5170*/
5171SQLITE_API void *sqlite3_update_hook(
5172  sqlite3*,
5173  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5174  void*
5175);
5176
5177/*
5178** CAPI3REF: Enable Or Disable Shared Pager Cache
5179** KEYWORDS: {shared cache}
5180**
5181** ^(This routine enables or disables the sharing of the database cache
5182** and schema data structures between [database connection | connections]
5183** to the same database. Sharing is enabled if the argument is true
5184** and disabled if the argument is false.)^
5185**
5186** ^Cache sharing is enabled and disabled for an entire process.
5187** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5188** sharing was enabled or disabled for each thread separately.
5189**
5190** ^(The cache sharing mode set by this interface effects all subsequent
5191** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5192** Existing database connections continue use the sharing mode
5193** that was in effect at the time they were opened.)^
5194**
5195** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5196** successfully.  An [error code] is returned otherwise.)^
5197**
5198** ^Shared cache is disabled by default. But this might change in
5199** future releases of SQLite.  Applications that care about shared
5200** cache setting should set it explicitly.
5201**
5202** See Also:  [SQLite Shared-Cache Mode]
5203*/
5204SQLITE_API int sqlite3_enable_shared_cache(int);
5205
5206/*
5207** CAPI3REF: Attempt To Free Heap Memory
5208**
5209** ^The sqlite3_release_memory() interface attempts to free N bytes
5210** of heap memory by deallocating non-essential memory allocations
5211** held by the database library.   Memory used to cache database
5212** pages to improve performance is an example of non-essential memory.
5213** ^sqlite3_release_memory() returns the number of bytes actually freed,
5214** which might be more or less than the amount requested.
5215** ^The sqlite3_release_memory() routine is a no-op returning zero
5216** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5217**
5218** See also: [sqlite3_db_release_memory()]
5219*/
5220SQLITE_API int sqlite3_release_memory(int);
5221
5222/*
5223** CAPI3REF: Free Memory Used By A Database Connection
5224**
5225** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5226** memory as possible from database connection D. Unlike the
5227** [sqlite3_release_memory()] interface, this interface is effect even
5228** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5229** omitted.
5230**
5231** See also: [sqlite3_release_memory()]
5232*/
5233SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5234
5235/*
5236** CAPI3REF: Impose A Limit On Heap Size
5237**
5238** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5239** soft limit on the amount of heap memory that may be allocated by SQLite.
5240** ^SQLite strives to keep heap memory utilization below the soft heap
5241** limit by reducing the number of pages held in the page cache
5242** as heap memory usages approaches the limit.
5243** ^The soft heap limit is "soft" because even though SQLite strives to stay
5244** below the limit, it will exceed the limit rather than generate
5245** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5246** is advisory only.
5247**
5248** ^The return value from sqlite3_soft_heap_limit64() is the size of
5249** the soft heap limit prior to the call, or negative in the case of an
5250** error.  ^If the argument N is negative
5251** then no change is made to the soft heap limit.  Hence, the current
5252** size of the soft heap limit can be determined by invoking
5253** sqlite3_soft_heap_limit64() with a negative argument.
5254**
5255** ^If the argument N is zero then the soft heap limit is disabled.
5256**
5257** ^(The soft heap limit is not enforced in the current implementation
5258** if one or more of following conditions are true:
5259**
5260** <ul>
5261** <li> The soft heap limit is set to zero.
5262** <li> Memory accounting is disabled using a combination of the
5263**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5264**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5265** <li> An alternative page cache implementation is specified using
5266**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5267** <li> The page cache allocates from its own memory pool supplied
5268**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5269**      from the heap.
5270** </ul>)^
5271**
5272** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5273** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5274** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5275** the soft heap limit is enforced on every memory allocation.  Without
5276** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5277** when memory is allocated by the page cache.  Testing suggests that because
5278** the page cache is the predominate memory user in SQLite, most
5279** applications will achieve adequate soft heap limit enforcement without
5280** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5281**
5282** The circumstances under which SQLite will enforce the soft heap limit may
5283** changes in future releases of SQLite.
5284*/
5285SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5286
5287/*
5288** CAPI3REF: Deprecated Soft Heap Limit Interface
5289** DEPRECATED
5290**
5291** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5292** interface.  This routine is provided for historical compatibility
5293** only.  All new applications should use the
5294** [sqlite3_soft_heap_limit64()] interface rather than this one.
5295*/
5296SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5297
5298
5299/*
5300** CAPI3REF: Extract Metadata About A Column Of A Table
5301**
5302** ^This routine returns metadata about a specific column of a specific
5303** database table accessible using the [database connection] handle
5304** passed as the first function argument.
5305**
5306** ^The column is identified by the second, third and fourth parameters to
5307** this function. ^The second parameter is either the name of the database
5308** (i.e. "main", "temp", or an attached database) containing the specified
5309** table or NULL. ^If it is NULL, then all attached databases are searched
5310** for the table using the same algorithm used by the database engine to
5311** resolve unqualified table references.
5312**
5313** ^The third and fourth parameters to this function are the table and column
5314** name of the desired column, respectively. Neither of these parameters
5315** may be NULL.
5316**
5317** ^Metadata is returned by writing to the memory locations passed as the 5th
5318** and subsequent parameters to this function. ^Any of these arguments may be
5319** NULL, in which case the corresponding element of metadata is omitted.
5320**
5321** ^(<blockquote>
5322** <table border="1">
5323** <tr><th> Parameter <th> Output<br>Type <th>  Description
5324**
5325** <tr><td> 5th <td> const char* <td> Data type
5326** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5327** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5328** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5329** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5330** </table>
5331** </blockquote>)^
5332**
5333** ^The memory pointed to by the character pointers returned for the
5334** declaration type and collation sequence is valid only until the next
5335** call to any SQLite API function.
5336**
5337** ^If the specified table is actually a view, an [error code] is returned.
5338**
5339** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5340** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5341** parameters are set for the explicitly declared column. ^(If there is no
5342** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5343** parameters are set as follows:
5344**
5345** <pre>
5346**     data type: "INTEGER"
5347**     collation sequence: "BINARY"
5348**     not null: 0
5349**     primary key: 1
5350**     auto increment: 0
5351** </pre>)^
5352**
5353** ^(This function may load one or more schemas from database files. If an
5354** error occurs during this process, or if the requested table or column
5355** cannot be found, an [error code] is returned and an error message left
5356** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5357**
5358** ^This API is only available if the library was compiled with the
5359** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5360*/
5361SQLITE_API int sqlite3_table_column_metadata(
5362  sqlite3 *db,                /* Connection handle */
5363  const char *zDbName,        /* Database name or NULL */
5364  const char *zTableName,     /* Table name */
5365  const char *zColumnName,    /* Column name */
5366  char const **pzDataType,    /* OUTPUT: Declared data type */
5367  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5368  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5369  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5370  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5371);
5372
5373/*
5374** CAPI3REF: Load An Extension
5375**
5376** ^This interface loads an SQLite extension library from the named file.
5377**
5378** ^The sqlite3_load_extension() interface attempts to load an
5379** SQLite extension library contained in the file zFile.
5380**
5381** ^The entry point is zProc.
5382** ^zProc may be 0, in which case the name of the entry point
5383** defaults to "sqlite3_extension_init".
5384** ^The sqlite3_load_extension() interface returns
5385** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5386** ^If an error occurs and pzErrMsg is not 0, then the
5387** [sqlite3_load_extension()] interface shall attempt to
5388** fill *pzErrMsg with error message text stored in memory
5389** obtained from [sqlite3_malloc()]. The calling function
5390** should free this memory by calling [sqlite3_free()].
5391**
5392** ^Extension loading must be enabled using
5393** [sqlite3_enable_load_extension()] prior to calling this API,
5394** otherwise an error will be returned.
5395**
5396** See also the [load_extension() SQL function].
5397*/
5398SQLITE_API int sqlite3_load_extension(
5399  sqlite3 *db,          /* Load the extension into this database connection */
5400  const char *zFile,    /* Name of the shared library containing extension */
5401  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5402  char **pzErrMsg       /* Put error message here if not 0 */
5403);
5404
5405/*
5406** CAPI3REF: Enable Or Disable Extension Loading
5407**
5408** ^So as not to open security holes in older applications that are
5409** unprepared to deal with extension loading, and as a means of disabling
5410** extension loading while evaluating user-entered SQL, the following API
5411** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5412**
5413** ^Extension loading is off by default. See ticket #1863.
5414** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5415** to turn extension loading on and call it with onoff==0 to turn
5416** it back off again.
5417*/
5418SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5419
5420/*
5421** CAPI3REF: Automatically Load Statically Linked Extensions
5422**
5423** ^This interface causes the xEntryPoint() function to be invoked for
5424** each new [database connection] that is created.  The idea here is that
5425** xEntryPoint() is the entry point for a statically linked SQLite extension
5426** that is to be automatically loaded into all new database connections.
5427**
5428** ^(Even though the function prototype shows that xEntryPoint() takes
5429** no arguments and returns void, SQLite invokes xEntryPoint() with three
5430** arguments and expects and integer result as if the signature of the
5431** entry point where as follows:
5432**
5433** <blockquote><pre>
5434** &nbsp;  int xEntryPoint(
5435** &nbsp;    sqlite3 *db,
5436** &nbsp;    const char **pzErrMsg,
5437** &nbsp;    const struct sqlite3_api_routines *pThunk
5438** &nbsp;  );
5439** </pre></blockquote>)^
5440**
5441** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5442** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5443** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5444** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5445** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5446** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5447** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5448**
5449** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5450** on the list of automatic extensions is a harmless no-op. ^No entry point
5451** will be called more than once for each database connection that is opened.
5452**
5453** See also: [sqlite3_reset_auto_extension()].
5454*/
5455SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5456
5457/*
5458** CAPI3REF: Reset Automatic Extension Loading
5459**
5460** ^This interface disables all automatic extensions previously
5461** registered using [sqlite3_auto_extension()].
5462*/
5463SQLITE_API void sqlite3_reset_auto_extension(void);
5464
5465/*
5466** The interface to the virtual-table mechanism is currently considered
5467** to be experimental.  The interface might change in incompatible ways.
5468** If this is a problem for you, do not use the interface at this time.
5469**
5470** When the virtual-table mechanism stabilizes, we will declare the
5471** interface fixed, support it indefinitely, and remove this comment.
5472*/
5473
5474/*
5475** Structures used by the virtual table interface
5476*/
5477typedef struct sqlite3_vtab sqlite3_vtab;
5478typedef struct sqlite3_index_info sqlite3_index_info;
5479typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5480typedef struct sqlite3_module sqlite3_module;
5481
5482/*
5483** CAPI3REF: Virtual Table Object
5484** KEYWORDS: sqlite3_module {virtual table module}
5485**
5486** This structure, sometimes called a "virtual table module",
5487** defines the implementation of a [virtual tables].
5488** This structure consists mostly of methods for the module.
5489**
5490** ^A virtual table module is created by filling in a persistent
5491** instance of this structure and passing a pointer to that instance
5492** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5493** ^The registration remains valid until it is replaced by a different
5494** module or until the [database connection] closes.  The content
5495** of this structure must not change while it is registered with
5496** any database connection.
5497*/
5498struct sqlite3_module {
5499  int iVersion;
5500  int (*xCreate)(sqlite3*, void *pAux,
5501               int argc, const char *const*argv,
5502               sqlite3_vtab **ppVTab, char**);
5503  int (*xConnect)(sqlite3*, void *pAux,
5504               int argc, const char *const*argv,
5505               sqlite3_vtab **ppVTab, char**);
5506  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5507  int (*xDisconnect)(sqlite3_vtab *pVTab);
5508  int (*xDestroy)(sqlite3_vtab *pVTab);
5509  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5510  int (*xClose)(sqlite3_vtab_cursor*);
5511  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5512                int argc, sqlite3_value **argv);
5513  int (*xNext)(sqlite3_vtab_cursor*);
5514  int (*xEof)(sqlite3_vtab_cursor*);
5515  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5516  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5517  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5518  int (*xBegin)(sqlite3_vtab *pVTab);
5519  int (*xSync)(sqlite3_vtab *pVTab);
5520  int (*xCommit)(sqlite3_vtab *pVTab);
5521  int (*xRollback)(sqlite3_vtab *pVTab);
5522  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5523                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5524                       void **ppArg);
5525  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5526  /* The methods above are in version 1 of the sqlite_module object. Those
5527  ** below are for version 2 and greater. */
5528  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5529  int (*xRelease)(sqlite3_vtab *pVTab, int);
5530  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5531};
5532
5533/*
5534** CAPI3REF: Virtual Table Indexing Information
5535** KEYWORDS: sqlite3_index_info
5536**
5537** The sqlite3_index_info structure and its substructures is used as part
5538** of the [virtual table] interface to
5539** pass information into and receive the reply from the [xBestIndex]
5540** method of a [virtual table module].  The fields under **Inputs** are the
5541** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5542** results into the **Outputs** fields.
5543**
5544** ^(The aConstraint[] array records WHERE clause constraints of the form:
5545**
5546** <blockquote>column OP expr</blockquote>
5547**
5548** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5549** stored in aConstraint[].op using one of the
5550** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5551** ^(The index of the column is stored in
5552** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5553** expr on the right-hand side can be evaluated (and thus the constraint
5554** is usable) and false if it cannot.)^
5555**
5556** ^The optimizer automatically inverts terms of the form "expr OP column"
5557** and makes other simplifications to the WHERE clause in an attempt to
5558** get as many WHERE clause terms into the form shown above as possible.
5559** ^The aConstraint[] array only reports WHERE clause terms that are
5560** relevant to the particular virtual table being queried.
5561**
5562** ^Information about the ORDER BY clause is stored in aOrderBy[].
5563** ^Each term of aOrderBy records a column of the ORDER BY clause.
5564**
5565** The [xBestIndex] method must fill aConstraintUsage[] with information
5566** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5567** the right-hand side of the corresponding aConstraint[] is evaluated
5568** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5569** is true, then the constraint is assumed to be fully handled by the
5570** virtual table and is not checked again by SQLite.)^
5571**
5572** ^The idxNum and idxPtr values are recorded and passed into the
5573** [xFilter] method.
5574** ^[sqlite3_free()] is used to free idxPtr if and only if
5575** needToFreeIdxPtr is true.
5576**
5577** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5578** the correct order to satisfy the ORDER BY clause so that no separate
5579** sorting step is required.
5580**
5581** ^The estimatedCost value is an estimate of the cost of doing the
5582** particular lookup.  A full scan of a table with N entries should have
5583** a cost of N.  A binary search of a table of N entries should have a
5584** cost of approximately log(N).
5585*/
5586struct sqlite3_index_info {
5587  /* Inputs */
5588  int nConstraint;           /* Number of entries in aConstraint */
5589  struct sqlite3_index_constraint {
5590     int iColumn;              /* Column on left-hand side of constraint */
5591     unsigned char op;         /* Constraint operator */
5592     unsigned char usable;     /* True if this constraint is usable */
5593     int iTermOffset;          /* Used internally - xBestIndex should ignore */
5594  } *aConstraint;            /* Table of WHERE clause constraints */
5595  int nOrderBy;              /* Number of terms in the ORDER BY clause */
5596  struct sqlite3_index_orderby {
5597     int iColumn;              /* Column number */
5598     unsigned char desc;       /* True for DESC.  False for ASC. */
5599  } *aOrderBy;               /* The ORDER BY clause */
5600  /* Outputs */
5601  struct sqlite3_index_constraint_usage {
5602    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5603    unsigned char omit;      /* Do not code a test for this constraint */
5604  } *aConstraintUsage;
5605  int idxNum;                /* Number used to identify the index */
5606  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5607  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5608  int orderByConsumed;       /* True if output is already ordered */
5609  double estimatedCost;      /* Estimated cost of using this index */
5610};
5611
5612/*
5613** CAPI3REF: Virtual Table Constraint Operator Codes
5614**
5615** These macros defined the allowed values for the
5616** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5617** an operator that is part of a constraint term in the wHERE clause of
5618** a query that uses a [virtual table].
5619*/
5620#define SQLITE_INDEX_CONSTRAINT_EQ    2
5621#define SQLITE_INDEX_CONSTRAINT_GT    4
5622#define SQLITE_INDEX_CONSTRAINT_LE    8
5623#define SQLITE_INDEX_CONSTRAINT_LT    16
5624#define SQLITE_INDEX_CONSTRAINT_GE    32
5625#define SQLITE_INDEX_CONSTRAINT_MATCH 64
5626
5627/*
5628** CAPI3REF: Register A Virtual Table Implementation
5629**
5630** ^These routines are used to register a new [virtual table module] name.
5631** ^Module names must be registered before
5632** creating a new [virtual table] using the module and before using a
5633** preexisting [virtual table] for the module.
5634**
5635** ^The module name is registered on the [database connection] specified
5636** by the first parameter.  ^The name of the module is given by the
5637** second parameter.  ^The third parameter is a pointer to
5638** the implementation of the [virtual table module].   ^The fourth
5639** parameter is an arbitrary client data pointer that is passed through
5640** into the [xCreate] and [xConnect] methods of the virtual table module
5641** when a new virtual table is be being created or reinitialized.
5642**
5643** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5644** is a pointer to a destructor for the pClientData.  ^SQLite will
5645** invoke the destructor function (if it is not NULL) when SQLite
5646** no longer needs the pClientData pointer.  ^The destructor will also
5647** be invoked if the call to sqlite3_create_module_v2() fails.
5648** ^The sqlite3_create_module()
5649** interface is equivalent to sqlite3_create_module_v2() with a NULL
5650** destructor.
5651*/
5652SQLITE_API int sqlite3_create_module(
5653  sqlite3 *db,               /* SQLite connection to register module with */
5654  const char *zName,         /* Name of the module */
5655  const sqlite3_module *p,   /* Methods for the module */
5656  void *pClientData          /* Client data for xCreate/xConnect */
5657);
5658SQLITE_API int sqlite3_create_module_v2(
5659  sqlite3 *db,               /* SQLite connection to register module with */
5660  const char *zName,         /* Name of the module */
5661  const sqlite3_module *p,   /* Methods for the module */
5662  void *pClientData,         /* Client data for xCreate/xConnect */
5663  void(*xDestroy)(void*)     /* Module destructor function */
5664);
5665
5666/*
5667** CAPI3REF: Virtual Table Instance Object
5668** KEYWORDS: sqlite3_vtab
5669**
5670** Every [virtual table module] implementation uses a subclass
5671** of this object to describe a particular instance
5672** of the [virtual table].  Each subclass will
5673** be tailored to the specific needs of the module implementation.
5674** The purpose of this superclass is to define certain fields that are
5675** common to all module implementations.
5676**
5677** ^Virtual tables methods can set an error message by assigning a
5678** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5679** take care that any prior string is freed by a call to [sqlite3_free()]
5680** prior to assigning a new string to zErrMsg.  ^After the error message
5681** is delivered up to the client application, the string will be automatically
5682** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5683*/
5684struct sqlite3_vtab {
5685  const sqlite3_module *pModule;  /* The module for this virtual table */
5686  int nRef;                       /* NO LONGER USED */
5687  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5688  /* Virtual table implementations will typically add additional fields */
5689};
5690
5691/*
5692** CAPI3REF: Virtual Table Cursor Object
5693** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5694**
5695** Every [virtual table module] implementation uses a subclass of the
5696** following structure to describe cursors that point into the
5697** [virtual table] and are used
5698** to loop through the virtual table.  Cursors are created using the
5699** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5700** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5701** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5702** of the module.  Each module implementation will define
5703** the content of a cursor structure to suit its own needs.
5704**
5705** This superclass exists in order to define fields of the cursor that
5706** are common to all implementations.
5707*/
5708struct sqlite3_vtab_cursor {
5709  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5710  /* Virtual table implementations will typically add additional fields */
5711};
5712
5713/*
5714** CAPI3REF: Declare The Schema Of A Virtual Table
5715**
5716** ^The [xCreate] and [xConnect] methods of a
5717** [virtual table module] call this interface
5718** to declare the format (the names and datatypes of the columns) of
5719** the virtual tables they implement.
5720*/
5721SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5722
5723/*
5724** CAPI3REF: Overload A Function For A Virtual Table
5725**
5726** ^(Virtual tables can provide alternative implementations of functions
5727** using the [xFindFunction] method of the [virtual table module].
5728** But global versions of those functions
5729** must exist in order to be overloaded.)^
5730**
5731** ^(This API makes sure a global version of a function with a particular
5732** name and number of parameters exists.  If no such function exists
5733** before this API is called, a new function is created.)^  ^The implementation
5734** of the new function always causes an exception to be thrown.  So
5735** the new function is not good for anything by itself.  Its only
5736** purpose is to be a placeholder function that can be overloaded
5737** by a [virtual table].
5738*/
5739SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5740
5741/*
5742** The interface to the virtual-table mechanism defined above (back up
5743** to a comment remarkably similar to this one) is currently considered
5744** to be experimental.  The interface might change in incompatible ways.
5745** If this is a problem for you, do not use the interface at this time.
5746**
5747** When the virtual-table mechanism stabilizes, we will declare the
5748** interface fixed, support it indefinitely, and remove this comment.
5749*/
5750
5751/*
5752** CAPI3REF: A Handle To An Open BLOB
5753** KEYWORDS: {BLOB handle} {BLOB handles}
5754**
5755** An instance of this object represents an open BLOB on which
5756** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5757** ^Objects of this type are created by [sqlite3_blob_open()]
5758** and destroyed by [sqlite3_blob_close()].
5759** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5760** can be used to read or write small subsections of the BLOB.
5761** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5762*/
5763typedef struct sqlite3_blob sqlite3_blob;
5764
5765/*
5766** CAPI3REF: Open A BLOB For Incremental I/O
5767**
5768** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5769** in row iRow, column zColumn, table zTable in database zDb;
5770** in other words, the same BLOB that would be selected by:
5771**
5772** <pre>
5773**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5774** </pre>)^
5775**
5776** ^If the flags parameter is non-zero, then the BLOB is opened for read
5777** and write access. ^If it is zero, the BLOB is opened for read access.
5778** ^It is not possible to open a column that is part of an index or primary
5779** key for writing. ^If [foreign key constraints] are enabled, it is
5780** not possible to open a column that is part of a [child key] for writing.
5781**
5782** ^Note that the database name is not the filename that contains
5783** the database but rather the symbolic name of the database that
5784** appears after the AS keyword when the database is connected using [ATTACH].
5785** ^For the main database file, the database name is "main".
5786** ^For TEMP tables, the database name is "temp".
5787**
5788** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5789** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5790** to be a null pointer.)^
5791** ^This function sets the [database connection] error code and message
5792** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5793** functions. ^Note that the *ppBlob variable is always initialized in a
5794** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5795** regardless of the success or failure of this routine.
5796**
5797** ^(If the row that a BLOB handle points to is modified by an
5798** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5799** then the BLOB handle is marked as "expired".
5800** This is true if any column of the row is changed, even a column
5801** other than the one the BLOB handle is open on.)^
5802** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5803** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5804** ^(Changes written into a BLOB prior to the BLOB expiring are not
5805** rolled back by the expiration of the BLOB.  Such changes will eventually
5806** commit if the transaction continues to completion.)^
5807**
5808** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5809** the opened blob.  ^The size of a blob may not be changed by this
5810** interface.  Use the [UPDATE] SQL command to change the size of a
5811** blob.
5812**
5813** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5814** and the built-in [zeroblob] SQL function can be used, if desired,
5815** to create an empty, zero-filled blob in which to read or write using
5816** this interface.
5817**
5818** To avoid a resource leak, every open [BLOB handle] should eventually
5819** be released by a call to [sqlite3_blob_close()].
5820*/
5821SQLITE_API int sqlite3_blob_open(
5822  sqlite3*,
5823  const char *zDb,
5824  const char *zTable,
5825  const char *zColumn,
5826  sqlite3_int64 iRow,
5827  int flags,
5828  sqlite3_blob **ppBlob
5829);
5830
5831/*
5832** CAPI3REF: Move a BLOB Handle to a New Row
5833**
5834** ^This function is used to move an existing blob handle so that it points
5835** to a different row of the same database table. ^The new row is identified
5836** by the rowid value passed as the second argument. Only the row can be
5837** changed. ^The database, table and column on which the blob handle is open
5838** remain the same. Moving an existing blob handle to a new row can be
5839** faster than closing the existing handle and opening a new one.
5840**
5841** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5842** it must exist and there must be either a blob or text value stored in
5843** the nominated column.)^ ^If the new row is not present in the table, or if
5844** it does not contain a blob or text value, or if another error occurs, an
5845** SQLite error code is returned and the blob handle is considered aborted.
5846** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5847** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5848** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5849** always returns zero.
5850**
5851** ^This function sets the database handle error code and message.
5852*/
5853SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5854
5855/*
5856** CAPI3REF: Close A BLOB Handle
5857**
5858** ^Closes an open [BLOB handle].
5859**
5860** ^Closing a BLOB shall cause the current transaction to commit
5861** if there are no other BLOBs, no pending prepared statements, and the
5862** database connection is in [autocommit mode].
5863** ^If any writes were made to the BLOB, they might be held in cache
5864** until the close operation if they will fit.
5865**
5866** ^(Closing the BLOB often forces the changes
5867** out to disk and so if any I/O errors occur, they will likely occur
5868** at the time when the BLOB is closed.  Any errors that occur during
5869** closing are reported as a non-zero return value.)^
5870**
5871** ^(The BLOB is closed unconditionally.  Even if this routine returns
5872** an error code, the BLOB is still closed.)^
5873**
5874** ^Calling this routine with a null pointer (such as would be returned
5875** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5876*/
5877SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5878
5879/*
5880** CAPI3REF: Return The Size Of An Open BLOB
5881**
5882** ^Returns the size in bytes of the BLOB accessible via the
5883** successfully opened [BLOB handle] in its only argument.  ^The
5884** incremental blob I/O routines can only read or overwriting existing
5885** blob content; they cannot change the size of a blob.
5886**
5887** This routine only works on a [BLOB handle] which has been created
5888** by a prior successful call to [sqlite3_blob_open()] and which has not
5889** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5890** to this routine results in undefined and probably undesirable behavior.
5891*/
5892SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5893
5894/*
5895** CAPI3REF: Read Data From A BLOB Incrementally
5896**
5897** ^(This function is used to read data from an open [BLOB handle] into a
5898** caller-supplied buffer. N bytes of data are copied into buffer Z
5899** from the open BLOB, starting at offset iOffset.)^
5900**
5901** ^If offset iOffset is less than N bytes from the end of the BLOB,
5902** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5903** less than zero, [SQLITE_ERROR] is returned and no data is read.
5904** ^The size of the blob (and hence the maximum value of N+iOffset)
5905** can be determined using the [sqlite3_blob_bytes()] interface.
5906**
5907** ^An attempt to read from an expired [BLOB handle] fails with an
5908** error code of [SQLITE_ABORT].
5909**
5910** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5911** Otherwise, an [error code] or an [extended error code] is returned.)^
5912**
5913** This routine only works on a [BLOB handle] which has been created
5914** by a prior successful call to [sqlite3_blob_open()] and which has not
5915** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5916** to this routine results in undefined and probably undesirable behavior.
5917**
5918** See also: [sqlite3_blob_write()].
5919*/
5920SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5921
5922/*
5923** CAPI3REF: Write Data Into A BLOB Incrementally
5924**
5925** ^This function is used to write data into an open [BLOB handle] from a
5926** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5927** into the open BLOB, starting at offset iOffset.
5928**
5929** ^If the [BLOB handle] passed as the first argument was not opened for
5930** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5931** this function returns [SQLITE_READONLY].
5932**
5933** ^This function may only modify the contents of the BLOB; it is
5934** not possible to increase the size of a BLOB using this API.
5935** ^If offset iOffset is less than N bytes from the end of the BLOB,
5936** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5937** less than zero [SQLITE_ERROR] is returned and no data is written.
5938** The size of the BLOB (and hence the maximum value of N+iOffset)
5939** can be determined using the [sqlite3_blob_bytes()] interface.
5940**
5941** ^An attempt to write to an expired [BLOB handle] fails with an
5942** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5943** before the [BLOB handle] expired are not rolled back by the
5944** expiration of the handle, though of course those changes might
5945** have been overwritten by the statement that expired the BLOB handle
5946** or by other independent statements.
5947**
5948** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5949** Otherwise, an  [error code] or an [extended error code] is returned.)^
5950**
5951** This routine only works on a [BLOB handle] which has been created
5952** by a prior successful call to [sqlite3_blob_open()] and which has not
5953** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5954** to this routine results in undefined and probably undesirable behavior.
5955**
5956** See also: [sqlite3_blob_read()].
5957*/
5958SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5959
5960/*
5961** CAPI3REF: Virtual File System Objects
5962**
5963** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5964** that SQLite uses to interact
5965** with the underlying operating system.  Most SQLite builds come with a
5966** single default VFS that is appropriate for the host computer.
5967** New VFSes can be registered and existing VFSes can be unregistered.
5968** The following interfaces are provided.
5969**
5970** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5971** ^Names are case sensitive.
5972** ^Names are zero-terminated UTF-8 strings.
5973** ^If there is no match, a NULL pointer is returned.
5974** ^If zVfsName is NULL then the default VFS is returned.
5975**
5976** ^New VFSes are registered with sqlite3_vfs_register().
5977** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5978** ^The same VFS can be registered multiple times without injury.
5979** ^To make an existing VFS into the default VFS, register it again
5980** with the makeDflt flag set.  If two different VFSes with the
5981** same name are registered, the behavior is undefined.  If a
5982** VFS is registered with a name that is NULL or an empty string,
5983** then the behavior is undefined.
5984**
5985** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5986** ^(If the default VFS is unregistered, another VFS is chosen as
5987** the default.  The choice for the new VFS is arbitrary.)^
5988*/
5989SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5990SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5991SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5992
5993/*
5994** CAPI3REF: Mutexes
5995**
5996** The SQLite core uses these routines for thread
5997** synchronization. Though they are intended for internal
5998** use by SQLite, code that links against SQLite is
5999** permitted to use any of these routines.
6000**
6001** The SQLite source code contains multiple implementations
6002** of these mutex routines.  An appropriate implementation
6003** is selected automatically at compile-time.  ^(The following
6004** implementations are available in the SQLite core:
6005**
6006** <ul>
6007** <li>   SQLITE_MUTEX_OS2
6008** <li>   SQLITE_MUTEX_PTHREADS
6009** <li>   SQLITE_MUTEX_W32
6010** <li>   SQLITE_MUTEX_NOOP
6011** </ul>)^
6012**
6013** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6014** that does no real locking and is appropriate for use in
6015** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
6016** SQLITE_MUTEX_PTHREADS, and SQLITE_MUTEX_W32 implementations
6017** are appropriate for use on OS/2, Unix, and Windows.
6018**
6019** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6020** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6021** implementation is included with the library. In this case the
6022** application must supply a custom mutex implementation using the
6023** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6024** before calling sqlite3_initialize() or any other public sqlite3_
6025** function that calls sqlite3_initialize().)^
6026**
6027** ^The sqlite3_mutex_alloc() routine allocates a new
6028** mutex and returns a pointer to it. ^If it returns NULL
6029** that means that a mutex could not be allocated.  ^SQLite
6030** will unwind its stack and return an error.  ^(The argument
6031** to sqlite3_mutex_alloc() is one of these integer constants:
6032**
6033** <ul>
6034** <li>  SQLITE_MUTEX_FAST
6035** <li>  SQLITE_MUTEX_RECURSIVE
6036** <li>  SQLITE_MUTEX_STATIC_MASTER
6037** <li>  SQLITE_MUTEX_STATIC_MEM
6038** <li>  SQLITE_MUTEX_STATIC_MEM2
6039** <li>  SQLITE_MUTEX_STATIC_PRNG
6040** <li>  SQLITE_MUTEX_STATIC_LRU
6041** <li>  SQLITE_MUTEX_STATIC_LRU2
6042** </ul>)^
6043**
6044** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6045** cause sqlite3_mutex_alloc() to create
6046** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6047** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6048** The mutex implementation does not need to make a distinction
6049** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6050** not want to.  ^SQLite will only request a recursive mutex in
6051** cases where it really needs one.  ^If a faster non-recursive mutex
6052** implementation is available on the host platform, the mutex subsystem
6053** might return such a mutex in response to SQLITE_MUTEX_FAST.
6054**
6055** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6056** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6057** a pointer to a static preexisting mutex.  ^Six static mutexes are
6058** used by the current version of SQLite.  Future versions of SQLite
6059** may add additional static mutexes.  Static mutexes are for internal
6060** use by SQLite only.  Applications that use SQLite mutexes should
6061** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6062** SQLITE_MUTEX_RECURSIVE.
6063**
6064** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6065** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6066** returns a different mutex on every call.  ^But for the static
6067** mutex types, the same mutex is returned on every call that has
6068** the same type number.
6069**
6070** ^The sqlite3_mutex_free() routine deallocates a previously
6071** allocated dynamic mutex.  ^SQLite is careful to deallocate every
6072** dynamic mutex that it allocates.  The dynamic mutexes must not be in
6073** use when they are deallocated.  Attempting to deallocate a static
6074** mutex results in undefined behavior.  ^SQLite never deallocates
6075** a static mutex.
6076**
6077** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6078** to enter a mutex.  ^If another thread is already within the mutex,
6079** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6080** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6081** upon successful entry.  ^(Mutexes created using
6082** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6083** In such cases the,
6084** mutex must be exited an equal number of times before another thread
6085** can enter.)^  ^(If the same thread tries to enter any other
6086** kind of mutex more than once, the behavior is undefined.
6087** SQLite will never exhibit
6088** such behavior in its own use of mutexes.)^
6089**
6090** ^(Some systems (for example, Windows 95) do not support the operation
6091** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6092** will always return SQLITE_BUSY.  The SQLite core only ever uses
6093** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6094**
6095** ^The sqlite3_mutex_leave() routine exits a mutex that was
6096** previously entered by the same thread.   ^(The behavior
6097** is undefined if the mutex is not currently entered by the
6098** calling thread or is not currently allocated.  SQLite will
6099** never do either.)^
6100**
6101** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6102** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6103** behave as no-ops.
6104**
6105** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6106*/
6107SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6108SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6109SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6110SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6111SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6112
6113/*
6114** CAPI3REF: Mutex Methods Object
6115**
6116** An instance of this structure defines the low-level routines
6117** used to allocate and use mutexes.
6118**
6119** Usually, the default mutex implementations provided by SQLite are
6120** sufficient, however the user has the option of substituting a custom
6121** implementation for specialized deployments or systems for which SQLite
6122** does not provide a suitable implementation. In this case, the user
6123** creates and populates an instance of this structure to pass
6124** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6125** Additionally, an instance of this structure can be used as an
6126** output variable when querying the system for the current mutex
6127** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6128**
6129** ^The xMutexInit method defined by this structure is invoked as
6130** part of system initialization by the sqlite3_initialize() function.
6131** ^The xMutexInit routine is called by SQLite exactly once for each
6132** effective call to [sqlite3_initialize()].
6133**
6134** ^The xMutexEnd method defined by this structure is invoked as
6135** part of system shutdown by the sqlite3_shutdown() function. The
6136** implementation of this method is expected to release all outstanding
6137** resources obtained by the mutex methods implementation, especially
6138** those obtained by the xMutexInit method.  ^The xMutexEnd()
6139** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6140**
6141** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6142** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6143** xMutexNotheld) implement the following interfaces (respectively):
6144**
6145** <ul>
6146**   <li>  [sqlite3_mutex_alloc()] </li>
6147**   <li>  [sqlite3_mutex_free()] </li>
6148**   <li>  [sqlite3_mutex_enter()] </li>
6149**   <li>  [sqlite3_mutex_try()] </li>
6150**   <li>  [sqlite3_mutex_leave()] </li>
6151**   <li>  [sqlite3_mutex_held()] </li>
6152**   <li>  [sqlite3_mutex_notheld()] </li>
6153** </ul>)^
6154**
6155** The only difference is that the public sqlite3_XXX functions enumerated
6156** above silently ignore any invocations that pass a NULL pointer instead
6157** of a valid mutex handle. The implementations of the methods defined
6158** by this structure are not required to handle this case, the results
6159** of passing a NULL pointer instead of a valid mutex handle are undefined
6160** (i.e. it is acceptable to provide an implementation that segfaults if
6161** it is passed a NULL pointer).
6162**
6163** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6164** invoke xMutexInit() multiple times within the same process and without
6165** intervening calls to xMutexEnd().  Second and subsequent calls to
6166** xMutexInit() must be no-ops.
6167**
6168** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6169** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6170** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6171** memory allocation for a fast or recursive mutex.
6172**
6173** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6174** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6175** If xMutexInit fails in any way, it is expected to clean up after itself
6176** prior to returning.
6177*/
6178typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6179struct sqlite3_mutex_methods {
6180  int (*xMutexInit)(void);
6181  int (*xMutexEnd)(void);
6182  sqlite3_mutex *(*xMutexAlloc)(int);
6183  void (*xMutexFree)(sqlite3_mutex *);
6184  void (*xMutexEnter)(sqlite3_mutex *);
6185  int (*xMutexTry)(sqlite3_mutex *);
6186  void (*xMutexLeave)(sqlite3_mutex *);
6187  int (*xMutexHeld)(sqlite3_mutex *);
6188  int (*xMutexNotheld)(sqlite3_mutex *);
6189};
6190
6191/*
6192** CAPI3REF: Mutex Verification Routines
6193**
6194** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6195** are intended for use inside assert() statements.  ^The SQLite core
6196** never uses these routines except inside an assert() and applications
6197** are advised to follow the lead of the core.  ^The SQLite core only
6198** provides implementations for these routines when it is compiled
6199** with the SQLITE_DEBUG flag.  ^External mutex implementations
6200** are only required to provide these routines if SQLITE_DEBUG is
6201** defined and if NDEBUG is not defined.
6202**
6203** ^These routines should return true if the mutex in their argument
6204** is held or not held, respectively, by the calling thread.
6205**
6206** ^The implementation is not required to provide versions of these
6207** routines that actually work. If the implementation does not provide working
6208** versions of these routines, it should at least provide stubs that always
6209** return true so that one does not get spurious assertion failures.
6210**
6211** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6212** the routine should return 1.   This seems counter-intuitive since
6213** clearly the mutex cannot be held if it does not exist.  But
6214** the reason the mutex does not exist is because the build is not
6215** using mutexes.  And we do not want the assert() containing the
6216** call to sqlite3_mutex_held() to fail, so a non-zero return is
6217** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6218** interface should also return 1 when given a NULL pointer.
6219*/
6220#ifndef NDEBUG
6221SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6222SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6223#endif
6224
6225/*
6226** CAPI3REF: Mutex Types
6227**
6228** The [sqlite3_mutex_alloc()] interface takes a single argument
6229** which is one of these integer constants.
6230**
6231** The set of static mutexes may change from one SQLite release to the
6232** next.  Applications that override the built-in mutex logic must be
6233** prepared to accommodate additional static mutexes.
6234*/
6235#define SQLITE_MUTEX_FAST             0
6236#define SQLITE_MUTEX_RECURSIVE        1
6237#define SQLITE_MUTEX_STATIC_MASTER    2
6238#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6239#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6240#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6241#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6242#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6243#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6244#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6245
6246/*
6247** CAPI3REF: Retrieve the mutex for a database connection
6248**
6249** ^This interface returns a pointer the [sqlite3_mutex] object that
6250** serializes access to the [database connection] given in the argument
6251** when the [threading mode] is Serialized.
6252** ^If the [threading mode] is Single-thread or Multi-thread then this
6253** routine returns a NULL pointer.
6254*/
6255SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6256
6257/*
6258** CAPI3REF: Low-Level Control Of Database Files
6259**
6260** ^The [sqlite3_file_control()] interface makes a direct call to the
6261** xFileControl method for the [sqlite3_io_methods] object associated
6262** with a particular database identified by the second argument. ^The
6263** name of the database is "main" for the main database or "temp" for the
6264** TEMP database, or the name that appears after the AS keyword for
6265** databases that are added using the [ATTACH] SQL command.
6266** ^A NULL pointer can be used in place of "main" to refer to the
6267** main database file.
6268** ^The third and fourth parameters to this routine
6269** are passed directly through to the second and third parameters of
6270** the xFileControl method.  ^The return value of the xFileControl
6271** method becomes the return value of this routine.
6272**
6273** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6274** a pointer to the underlying [sqlite3_file] object to be written into
6275** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6276** case is a short-circuit path which does not actually invoke the
6277** underlying sqlite3_io_methods.xFileControl method.
6278**
6279** ^If the second parameter (zDbName) does not match the name of any
6280** open database file, then SQLITE_ERROR is returned.  ^This error
6281** code is not remembered and will not be recalled by [sqlite3_errcode()]
6282** or [sqlite3_errmsg()].  The underlying xFileControl method might
6283** also return SQLITE_ERROR.  There is no way to distinguish between
6284** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6285** xFileControl method.
6286**
6287** See also: [SQLITE_FCNTL_LOCKSTATE]
6288*/
6289SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6290
6291/*
6292** CAPI3REF: Testing Interface
6293**
6294** ^The sqlite3_test_control() interface is used to read out internal
6295** state of SQLite and to inject faults into SQLite for testing
6296** purposes.  ^The first parameter is an operation code that determines
6297** the number, meaning, and operation of all subsequent parameters.
6298**
6299** This interface is not for use by applications.  It exists solely
6300** for verifying the correct operation of the SQLite library.  Depending
6301** on how the SQLite library is compiled, this interface might not exist.
6302**
6303** The details of the operation codes, their meanings, the parameters
6304** they take, and what they do are all subject to change without notice.
6305** Unlike most of the SQLite API, this function is not guaranteed to
6306** operate consistently from one release to the next.
6307*/
6308SQLITE_API int sqlite3_test_control(int op, ...);
6309
6310/*
6311** CAPI3REF: Testing Interface Operation Codes
6312**
6313** These constants are the valid operation code parameters used
6314** as the first argument to [sqlite3_test_control()].
6315**
6316** These parameters and their meanings are subject to change
6317** without notice.  These values are for testing purposes only.
6318** Applications should not use any of these parameters or the
6319** [sqlite3_test_control()] interface.
6320*/
6321#define SQLITE_TESTCTRL_FIRST                    5
6322#define SQLITE_TESTCTRL_PRNG_SAVE                5
6323#define SQLITE_TESTCTRL_PRNG_RESTORE             6
6324#define SQLITE_TESTCTRL_PRNG_RESET               7
6325#define SQLITE_TESTCTRL_BITVEC_TEST              8
6326#define SQLITE_TESTCTRL_FAULT_INSTALL            9
6327#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6328#define SQLITE_TESTCTRL_PENDING_BYTE            11
6329#define SQLITE_TESTCTRL_ASSERT                  12
6330#define SQLITE_TESTCTRL_ALWAYS                  13
6331#define SQLITE_TESTCTRL_RESERVE                 14
6332#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6333#define SQLITE_TESTCTRL_ISKEYWORD               16
6334#define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6335#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6336#define SQLITE_TESTCTRL_EXPLAIN_STMT            19
6337#define SQLITE_TESTCTRL_LAST                    19
6338
6339/*
6340** CAPI3REF: SQLite Runtime Status
6341**
6342** ^This interface is used to retrieve runtime status information
6343** about the performance of SQLite, and optionally to reset various
6344** highwater marks.  ^The first argument is an integer code for
6345** the specific parameter to measure.  ^(Recognized integer codes
6346** are of the form [status parameters | SQLITE_STATUS_...].)^
6347** ^The current value of the parameter is returned into *pCurrent.
6348** ^The highest recorded value is returned in *pHighwater.  ^If the
6349** resetFlag is true, then the highest record value is reset after
6350** *pHighwater is written.  ^(Some parameters do not record the highest
6351** value.  For those parameters
6352** nothing is written into *pHighwater and the resetFlag is ignored.)^
6353** ^(Other parameters record only the highwater mark and not the current
6354** value.  For these latter parameters nothing is written into *pCurrent.)^
6355**
6356** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6357** non-zero [error code] on failure.
6358**
6359** This routine is threadsafe but is not atomic.  This routine can be
6360** called while other threads are running the same or different SQLite
6361** interfaces.  However the values returned in *pCurrent and
6362** *pHighwater reflect the status of SQLite at different points in time
6363** and it is possible that another thread might change the parameter
6364** in between the times when *pCurrent and *pHighwater are written.
6365**
6366** See also: [sqlite3_db_status()]
6367*/
6368SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6369
6370
6371/*
6372** CAPI3REF: Status Parameters
6373** KEYWORDS: {status parameters}
6374**
6375** These integer constants designate various run-time status parameters
6376** that can be returned by [sqlite3_status()].
6377**
6378** <dl>
6379** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6380** <dd>This parameter is the current amount of memory checked out
6381** using [sqlite3_malloc()], either directly or indirectly.  The
6382** figure includes calls made to [sqlite3_malloc()] by the application
6383** and internal memory usage by the SQLite library.  Scratch memory
6384** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6385** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6386** this parameter.  The amount returned is the sum of the allocation
6387** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6388**
6389** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6390** <dd>This parameter records the largest memory allocation request
6391** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6392** internal equivalents).  Only the value returned in the
6393** *pHighwater parameter to [sqlite3_status()] is of interest.
6394** The value written into the *pCurrent parameter is undefined.</dd>)^
6395**
6396** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6397** <dd>This parameter records the number of separate memory allocations
6398** currently checked out.</dd>)^
6399**
6400** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6401** <dd>This parameter returns the number of pages used out of the
6402** [pagecache memory allocator] that was configured using
6403** [SQLITE_CONFIG_PAGECACHE].  The
6404** value returned is in pages, not in bytes.</dd>)^
6405**
6406** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6407** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6408** <dd>This parameter returns the number of bytes of page cache
6409** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6410** buffer and where forced to overflow to [sqlite3_malloc()].  The
6411** returned value includes allocations that overflowed because they
6412** where too large (they were larger than the "sz" parameter to
6413** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6414** no space was left in the page cache.</dd>)^
6415**
6416** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6417** <dd>This parameter records the largest memory allocation request
6418** handed to [pagecache memory allocator].  Only the value returned in the
6419** *pHighwater parameter to [sqlite3_status()] is of interest.
6420** The value written into the *pCurrent parameter is undefined.</dd>)^
6421**
6422** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6423** <dd>This parameter returns the number of allocations used out of the
6424** [scratch memory allocator] configured using
6425** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6426** in bytes.  Since a single thread may only have one scratch allocation
6427** outstanding at time, this parameter also reports the number of threads
6428** using scratch memory at the same time.</dd>)^
6429**
6430** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6431** <dd>This parameter returns the number of bytes of scratch memory
6432** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6433** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6434** returned include overflows because the requested allocation was too
6435** larger (that is, because the requested allocation was larger than the
6436** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6437** slots were available.
6438** </dd>)^
6439**
6440** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6441** <dd>This parameter records the largest memory allocation request
6442** handed to [scratch memory allocator].  Only the value returned in the
6443** *pHighwater parameter to [sqlite3_status()] is of interest.
6444** The value written into the *pCurrent parameter is undefined.</dd>)^
6445**
6446** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6447** <dd>This parameter records the deepest parser stack.  It is only
6448** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6449** </dl>
6450**
6451** New status parameters may be added from time to time.
6452*/
6453#define SQLITE_STATUS_MEMORY_USED          0
6454#define SQLITE_STATUS_PAGECACHE_USED       1
6455#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6456#define SQLITE_STATUS_SCRATCH_USED         3
6457#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6458#define SQLITE_STATUS_MALLOC_SIZE          5
6459#define SQLITE_STATUS_PARSER_STACK         6
6460#define SQLITE_STATUS_PAGECACHE_SIZE       7
6461#define SQLITE_STATUS_SCRATCH_SIZE         8
6462#define SQLITE_STATUS_MALLOC_COUNT         9
6463
6464/*
6465** CAPI3REF: Database Connection Status
6466**
6467** ^This interface is used to retrieve runtime status information
6468** about a single [database connection].  ^The first argument is the
6469** database connection object to be interrogated.  ^The second argument
6470** is an integer constant, taken from the set of
6471** [SQLITE_DBSTATUS options], that
6472** determines the parameter to interrogate.  The set of
6473** [SQLITE_DBSTATUS options] is likely
6474** to grow in future releases of SQLite.
6475**
6476** ^The current value of the requested parameter is written into *pCur
6477** and the highest instantaneous value is written into *pHiwtr.  ^If
6478** the resetFlg is true, then the highest instantaneous value is
6479** reset back down to the current value.
6480**
6481** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6482** non-zero [error code] on failure.
6483**
6484** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6485*/
6486SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6487
6488/*
6489** CAPI3REF: Status Parameters for database connections
6490** KEYWORDS: {SQLITE_DBSTATUS options}
6491**
6492** These constants are the available integer "verbs" that can be passed as
6493** the second argument to the [sqlite3_db_status()] interface.
6494**
6495** New verbs may be added in future releases of SQLite. Existing verbs
6496** might be discontinued. Applications should check the return code from
6497** [sqlite3_db_status()] to make sure that the call worked.
6498** The [sqlite3_db_status()] interface will return a non-zero error code
6499** if a discontinued or unsupported verb is invoked.
6500**
6501** <dl>
6502** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6503** <dd>This parameter returns the number of lookaside memory slots currently
6504** checked out.</dd>)^
6505**
6506** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6507** <dd>This parameter returns the number malloc attempts that were
6508** satisfied using lookaside memory. Only the high-water value is meaningful;
6509** the current value is always zero.)^
6510**
6511** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6512** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6513** <dd>This parameter returns the number malloc attempts that might have
6514** been satisfied using lookaside memory but failed due to the amount of
6515** memory requested being larger than the lookaside slot size.
6516** Only the high-water value is meaningful;
6517** the current value is always zero.)^
6518**
6519** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6520** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6521** <dd>This parameter returns the number malloc attempts that might have
6522** been satisfied using lookaside memory but failed due to all lookaside
6523** memory already being in use.
6524** Only the high-water value is meaningful;
6525** the current value is always zero.)^
6526**
6527** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6528** <dd>This parameter returns the approximate number of of bytes of heap
6529** memory used by all pager caches associated with the database connection.)^
6530** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6531**
6532** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6533** <dd>This parameter returns the approximate number of of bytes of heap
6534** memory used to store the schema for all databases associated
6535** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6536** ^The full amount of memory used by the schemas is reported, even if the
6537** schema memory is shared with other database connections due to
6538** [shared cache mode] being enabled.
6539** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6540**
6541** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6542** <dd>This parameter returns the approximate number of of bytes of heap
6543** and lookaside memory used by all prepared statements associated with
6544** the database connection.)^
6545** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6546** </dd>
6547**
6548** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6549** <dd>This parameter returns the number of pager cache hits that have
6550** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6551** is always 0.
6552** </dd>
6553**
6554** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6555** <dd>This parameter returns the number of pager cache misses that have
6556** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6557** is always 0.
6558** </dd>
6559** </dl>
6560*/
6561#define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6562#define SQLITE_DBSTATUS_CACHE_USED           1
6563#define SQLITE_DBSTATUS_SCHEMA_USED          2
6564#define SQLITE_DBSTATUS_STMT_USED            3
6565#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6566#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6567#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6568#define SQLITE_DBSTATUS_CACHE_HIT            7
6569#define SQLITE_DBSTATUS_CACHE_MISS           8
6570#define SQLITE_DBSTATUS_MAX                  8   /* Largest defined DBSTATUS */
6571
6572
6573/*
6574** CAPI3REF: Prepared Statement Status
6575**
6576** ^(Each prepared statement maintains various
6577** [SQLITE_STMTSTATUS counters] that measure the number
6578** of times it has performed specific operations.)^  These counters can
6579** be used to monitor the performance characteristics of the prepared
6580** statements.  For example, if the number of table steps greatly exceeds
6581** the number of table searches or result rows, that would tend to indicate
6582** that the prepared statement is using a full table scan rather than
6583** an index.
6584**
6585** ^(This interface is used to retrieve and reset counter values from
6586** a [prepared statement].  The first argument is the prepared statement
6587** object to be interrogated.  The second argument
6588** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6589** to be interrogated.)^
6590** ^The current value of the requested counter is returned.
6591** ^If the resetFlg is true, then the counter is reset to zero after this
6592** interface call returns.
6593**
6594** See also: [sqlite3_status()] and [sqlite3_db_status()].
6595*/
6596SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6597
6598/*
6599** CAPI3REF: Status Parameters for prepared statements
6600** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6601**
6602** These preprocessor macros define integer codes that name counter
6603** values associated with the [sqlite3_stmt_status()] interface.
6604** The meanings of the various counters are as follows:
6605**
6606** <dl>
6607** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6608** <dd>^This is the number of times that SQLite has stepped forward in
6609** a table as part of a full table scan.  Large numbers for this counter
6610** may indicate opportunities for performance improvement through
6611** careful use of indices.</dd>
6612**
6613** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6614** <dd>^This is the number of sort operations that have occurred.
6615** A non-zero value in this counter may indicate an opportunity to
6616** improvement performance through careful use of indices.</dd>
6617**
6618** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6619** <dd>^This is the number of rows inserted into transient indices that
6620** were created automatically in order to help joins run faster.
6621** A non-zero value in this counter may indicate an opportunity to
6622** improvement performance by adding permanent indices that do not
6623** need to be reinitialized each time the statement is run.</dd>
6624** </dl>
6625*/
6626#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6627#define SQLITE_STMTSTATUS_SORT              2
6628#define SQLITE_STMTSTATUS_AUTOINDEX         3
6629
6630/*
6631** CAPI3REF: Custom Page Cache Object
6632**
6633** The sqlite3_pcache type is opaque.  It is implemented by
6634** the pluggable module.  The SQLite core has no knowledge of
6635** its size or internal structure and never deals with the
6636** sqlite3_pcache object except by holding and passing pointers
6637** to the object.
6638**
6639** See [sqlite3_pcache_methods2] for additional information.
6640*/
6641typedef struct sqlite3_pcache sqlite3_pcache;
6642
6643/*
6644** CAPI3REF: Custom Page Cache Object
6645**
6646** The sqlite3_pcache_page object represents a single page in the
6647** page cache.  The page cache will allocate instances of this
6648** object.  Various methods of the page cache use pointers to instances
6649** of this object as parameters or as their return value.
6650**
6651** See [sqlite3_pcache_methods2] for additional information.
6652*/
6653typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6654struct sqlite3_pcache_page {
6655  void *pBuf;        /* The content of the page */
6656  void *pExtra;      /* Extra information associated with the page */
6657};
6658
6659/*
6660** CAPI3REF: Application Defined Page Cache.
6661** KEYWORDS: {page cache}
6662**
6663** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6664** register an alternative page cache implementation by passing in an
6665** instance of the sqlite3_pcache_methods2 structure.)^
6666** In many applications, most of the heap memory allocated by
6667** SQLite is used for the page cache.
6668** By implementing a
6669** custom page cache using this API, an application can better control
6670** the amount of memory consumed by SQLite, the way in which
6671** that memory is allocated and released, and the policies used to
6672** determine exactly which parts of a database file are cached and for
6673** how long.
6674**
6675** The alternative page cache mechanism is an
6676** extreme measure that is only needed by the most demanding applications.
6677** The built-in page cache is recommended for most uses.
6678**
6679** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6680** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6681** the application may discard the parameter after the call to
6682** [sqlite3_config()] returns.)^
6683**
6684** [[the xInit() page cache method]]
6685** ^(The xInit() method is called once for each effective
6686** call to [sqlite3_initialize()])^
6687** (usually only once during the lifetime of the process). ^(The xInit()
6688** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6689** The intent of the xInit() method is to set up global data structures
6690** required by the custom page cache implementation.
6691** ^(If the xInit() method is NULL, then the
6692** built-in default page cache is used instead of the application defined
6693** page cache.)^
6694**
6695** [[the xShutdown() page cache method]]
6696** ^The xShutdown() method is called by [sqlite3_shutdown()].
6697** It can be used to clean up
6698** any outstanding resources before process shutdown, if required.
6699** ^The xShutdown() method may be NULL.
6700**
6701** ^SQLite automatically serializes calls to the xInit method,
6702** so the xInit method need not be threadsafe.  ^The
6703** xShutdown method is only called from [sqlite3_shutdown()] so it does
6704** not need to be threadsafe either.  All other methods must be threadsafe
6705** in multithreaded applications.
6706**
6707** ^SQLite will never invoke xInit() more than once without an intervening
6708** call to xShutdown().
6709**
6710** [[the xCreate() page cache methods]]
6711** ^SQLite invokes the xCreate() method to construct a new cache instance.
6712** SQLite will typically create one cache instance for each open database file,
6713** though this is not guaranteed. ^The
6714** first parameter, szPage, is the size in bytes of the pages that must
6715** be allocated by the cache.  ^szPage will always a power of two.  ^The
6716** second parameter szExtra is a number of bytes of extra storage
6717** associated with each page cache entry.  ^The szExtra parameter will
6718** a number less than 250.  SQLite will use the
6719** extra szExtra bytes on each page to store metadata about the underlying
6720** database page on disk.  The value passed into szExtra depends
6721** on the SQLite version, the target platform, and how SQLite was compiled.
6722** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6723** created will be used to cache database pages of a file stored on disk, or
6724** false if it is used for an in-memory database. The cache implementation
6725** does not have to do anything special based with the value of bPurgeable;
6726** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6727** never invoke xUnpin() except to deliberately delete a page.
6728** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6729** false will always have the "discard" flag set to true.
6730** ^Hence, a cache created with bPurgeable false will
6731** never contain any unpinned pages.
6732**
6733** [[the xCachesize() page cache method]]
6734** ^(The xCachesize() method may be called at any time by SQLite to set the
6735** suggested maximum cache-size (number of pages stored by) the cache
6736** instance passed as the first argument. This is the value configured using
6737** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6738** parameter, the implementation is not required to do anything with this
6739** value; it is advisory only.
6740**
6741** [[the xPagecount() page cache methods]]
6742** The xPagecount() method must return the number of pages currently
6743** stored in the cache, both pinned and unpinned.
6744**
6745** [[the xFetch() page cache methods]]
6746** The xFetch() method locates a page in the cache and returns a pointer to
6747** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6748** The pBuf element of the returned sqlite3_pcache_page object will be a
6749** pointer to a buffer of szPage bytes used to store the content of a
6750** single database page.  The pExtra element of sqlite3_pcache_page will be
6751** a pointer to the szExtra bytes of extra storage that SQLite has requested
6752** for each entry in the page cache.
6753**
6754** The page to be fetched is determined by the key. ^The minimum key value
6755** is 1.  After it has been retrieved using xFetch, the page is considered
6756** to be "pinned".
6757**
6758** If the requested page is already in the page cache, then the page cache
6759** implementation must return a pointer to the page buffer with its content
6760** intact.  If the requested page is not already in the cache, then the
6761** cache implementation should use the value of the createFlag
6762** parameter to help it determined what action to take:
6763**
6764** <table border=1 width=85% align=center>
6765** <tr><th> createFlag <th> Behaviour when page is not already in cache
6766** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6767** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6768**                 Otherwise return NULL.
6769** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6770**                 NULL if allocating a new page is effectively impossible.
6771** </table>
6772**
6773** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6774** will only use a createFlag of 2 after a prior call with a createFlag of 1
6775** failed.)^  In between the to xFetch() calls, SQLite may
6776** attempt to unpin one or more cache pages by spilling the content of
6777** pinned pages to disk and synching the operating system disk cache.
6778**
6779** [[the xUnpin() page cache method]]
6780** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6781** as its second argument.  If the third parameter, discard, is non-zero,
6782** then the page must be evicted from the cache.
6783** ^If the discard parameter is
6784** zero, then the page may be discarded or retained at the discretion of
6785** page cache implementation. ^The page cache implementation
6786** may choose to evict unpinned pages at any time.
6787**
6788** The cache must not perform any reference counting. A single
6789** call to xUnpin() unpins the page regardless of the number of prior calls
6790** to xFetch().
6791**
6792** [[the xRekey() page cache methods]]
6793** The xRekey() method is used to change the key value associated with the
6794** page passed as the second argument. If the cache
6795** previously contains an entry associated with newKey, it must be
6796** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6797** to be pinned.
6798**
6799** When SQLite calls the xTruncate() method, the cache must discard all
6800** existing cache entries with page numbers (keys) greater than or equal
6801** to the value of the iLimit parameter passed to xTruncate(). If any
6802** of these pages are pinned, they are implicitly unpinned, meaning that
6803** they can be safely discarded.
6804**
6805** [[the xDestroy() page cache method]]
6806** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6807** All resources associated with the specified cache should be freed. ^After
6808** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6809** handle invalid, and will not use it with any other sqlite3_pcache_methods2
6810** functions.
6811**
6812** [[the xShrink() page cache method]]
6813** ^SQLite invokes the xShrink() method when it wants the page cache to
6814** free up as much of heap memory as possible.  The page cache implementation
6815** is not obligated to free any memory, but well-behaved implementations should
6816** do their best.
6817*/
6818typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
6819struct sqlite3_pcache_methods2 {
6820  int iVersion;
6821  void *pArg;
6822  int (*xInit)(void*);
6823  void (*xShutdown)(void*);
6824  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
6825  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6826  int (*xPagecount)(sqlite3_pcache*);
6827  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6828  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
6829  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
6830      unsigned oldKey, unsigned newKey);
6831  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6832  void (*xDestroy)(sqlite3_pcache*);
6833  void (*xShrink)(sqlite3_pcache*);
6834};
6835
6836/*
6837** This is the obsolete pcache_methods object that has now been replaced
6838** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
6839** retained in the header file for backwards compatibility only.
6840*/
6841typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6842struct sqlite3_pcache_methods {
6843  void *pArg;
6844  int (*xInit)(void*);
6845  void (*xShutdown)(void*);
6846  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6847  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6848  int (*xPagecount)(sqlite3_pcache*);
6849  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6850  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6851  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6852  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6853  void (*xDestroy)(sqlite3_pcache*);
6854};
6855
6856
6857/*
6858** CAPI3REF: Online Backup Object
6859**
6860** The sqlite3_backup object records state information about an ongoing
6861** online backup operation.  ^The sqlite3_backup object is created by
6862** a call to [sqlite3_backup_init()] and is destroyed by a call to
6863** [sqlite3_backup_finish()].
6864**
6865** See Also: [Using the SQLite Online Backup API]
6866*/
6867typedef struct sqlite3_backup sqlite3_backup;
6868
6869/*
6870** CAPI3REF: Online Backup API.
6871**
6872** The backup API copies the content of one database into another.
6873** It is useful either for creating backups of databases or
6874** for copying in-memory databases to or from persistent files.
6875**
6876** See Also: [Using the SQLite Online Backup API]
6877**
6878** ^SQLite holds a write transaction open on the destination database file
6879** for the duration of the backup operation.
6880** ^The source database is read-locked only while it is being read;
6881** it is not locked continuously for the entire backup operation.
6882** ^Thus, the backup may be performed on a live source database without
6883** preventing other database connections from
6884** reading or writing to the source database while the backup is underway.
6885**
6886** ^(To perform a backup operation:
6887**   <ol>
6888**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6889**         backup,
6890**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6891**         the data between the two databases, and finally
6892**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
6893**         associated with the backup operation.
6894**   </ol>)^
6895** There should be exactly one call to sqlite3_backup_finish() for each
6896** successful call to sqlite3_backup_init().
6897**
6898** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
6899**
6900** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6901** [database connection] associated with the destination database
6902** and the database name, respectively.
6903** ^The database name is "main" for the main database, "temp" for the
6904** temporary database, or the name specified after the AS keyword in
6905** an [ATTACH] statement for an attached database.
6906** ^The S and M arguments passed to
6907** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6908** and database name of the source database, respectively.
6909** ^The source and destination [database connections] (parameters S and D)
6910** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6911** an error.
6912**
6913** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6914** returned and an error code and error message are stored in the
6915** destination [database connection] D.
6916** ^The error code and message for the failed call to sqlite3_backup_init()
6917** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6918** [sqlite3_errmsg16()] functions.
6919** ^A successful call to sqlite3_backup_init() returns a pointer to an
6920** [sqlite3_backup] object.
6921** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6922** sqlite3_backup_finish() functions to perform the specified backup
6923** operation.
6924**
6925** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
6926**
6927** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6928** the source and destination databases specified by [sqlite3_backup] object B.
6929** ^If N is negative, all remaining source pages are copied.
6930** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6931** are still more pages to be copied, then the function returns [SQLITE_OK].
6932** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6933** from source to destination, then it returns [SQLITE_DONE].
6934** ^If an error occurs while running sqlite3_backup_step(B,N),
6935** then an [error code] is returned. ^As well as [SQLITE_OK] and
6936** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6937** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6938** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6939**
6940** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6941** <ol>
6942** <li> the destination database was opened read-only, or
6943** <li> the destination database is using write-ahead-log journaling
6944** and the destination and source page sizes differ, or
6945** <li> the destination database is an in-memory database and the
6946** destination and source page sizes differ.
6947** </ol>)^
6948**
6949** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6950** the [sqlite3_busy_handler | busy-handler function]
6951** is invoked (if one is specified). ^If the
6952** busy-handler returns non-zero before the lock is available, then
6953** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6954** sqlite3_backup_step() can be retried later. ^If the source
6955** [database connection]
6956** is being used to write to the source database when sqlite3_backup_step()
6957** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6958** case the call to sqlite3_backup_step() can be retried later on. ^(If
6959** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6960** [SQLITE_READONLY] is returned, then
6961** there is no point in retrying the call to sqlite3_backup_step(). These
6962** errors are considered fatal.)^  The application must accept
6963** that the backup operation has failed and pass the backup operation handle
6964** to the sqlite3_backup_finish() to release associated resources.
6965**
6966** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6967** on the destination file. ^The exclusive lock is not released until either
6968** sqlite3_backup_finish() is called or the backup operation is complete
6969** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6970** sqlite3_backup_step() obtains a [shared lock] on the source database that
6971** lasts for the duration of the sqlite3_backup_step() call.
6972** ^Because the source database is not locked between calls to
6973** sqlite3_backup_step(), the source database may be modified mid-way
6974** through the backup process.  ^If the source database is modified by an
6975** external process or via a database connection other than the one being
6976** used by the backup operation, then the backup will be automatically
6977** restarted by the next call to sqlite3_backup_step(). ^If the source
6978** database is modified by the using the same database connection as is used
6979** by the backup operation, then the backup database is automatically
6980** updated at the same time.
6981**
6982** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
6983**
6984** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
6985** application wishes to abandon the backup operation, the application
6986** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6987** ^The sqlite3_backup_finish() interfaces releases all
6988** resources associated with the [sqlite3_backup] object.
6989** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6990** active write-transaction on the destination database is rolled back.
6991** The [sqlite3_backup] object is invalid
6992** and may not be used following a call to sqlite3_backup_finish().
6993**
6994** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6995** sqlite3_backup_step() errors occurred, regardless or whether or not
6996** sqlite3_backup_step() completed.
6997** ^If an out-of-memory condition or IO error occurred during any prior
6998** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6999** sqlite3_backup_finish() returns the corresponding [error code].
7000**
7001** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7002** is not a permanent error and does not affect the return value of
7003** sqlite3_backup_finish().
7004**
7005** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7006** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7007**
7008** ^Each call to sqlite3_backup_step() sets two values inside
7009** the [sqlite3_backup] object: the number of pages still to be backed
7010** up and the total number of pages in the source database file.
7011** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7012** retrieve these two values, respectively.
7013**
7014** ^The values returned by these functions are only updated by
7015** sqlite3_backup_step(). ^If the source database is modified during a backup
7016** operation, then the values are not updated to account for any extra
7017** pages that need to be updated or the size of the source database file
7018** changing.
7019**
7020** <b>Concurrent Usage of Database Handles</b>
7021**
7022** ^The source [database connection] may be used by the application for other
7023** purposes while a backup operation is underway or being initialized.
7024** ^If SQLite is compiled and configured to support threadsafe database
7025** connections, then the source database connection may be used concurrently
7026** from within other threads.
7027**
7028** However, the application must guarantee that the destination
7029** [database connection] is not passed to any other API (by any thread) after
7030** sqlite3_backup_init() is called and before the corresponding call to
7031** sqlite3_backup_finish().  SQLite does not currently check to see
7032** if the application incorrectly accesses the destination [database connection]
7033** and so no error code is reported, but the operations may malfunction
7034** nevertheless.  Use of the destination database connection while a
7035** backup is in progress might also also cause a mutex deadlock.
7036**
7037** If running in [shared cache mode], the application must
7038** guarantee that the shared cache used by the destination database
7039** is not accessed while the backup is running. In practice this means
7040** that the application must guarantee that the disk file being
7041** backed up to is not accessed by any connection within the process,
7042** not just the specific connection that was passed to sqlite3_backup_init().
7043**
7044** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7045** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7046** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7047** APIs are not strictly speaking threadsafe. If they are invoked at the
7048** same time as another thread is invoking sqlite3_backup_step() it is
7049** possible that they return invalid values.
7050*/
7051SQLITE_API sqlite3_backup *sqlite3_backup_init(
7052  sqlite3 *pDest,                        /* Destination database handle */
7053  const char *zDestName,                 /* Destination database name */
7054  sqlite3 *pSource,                      /* Source database handle */
7055  const char *zSourceName                /* Source database name */
7056);
7057SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7058SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7059SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7060SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7061
7062/*
7063** CAPI3REF: Unlock Notification
7064**
7065** ^When running in shared-cache mode, a database operation may fail with
7066** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7067** individual tables within the shared-cache cannot be obtained. See
7068** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7069** ^This API may be used to register a callback that SQLite will invoke
7070** when the connection currently holding the required lock relinquishes it.
7071** ^This API is only available if the library was compiled with the
7072** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7073**
7074** See Also: [Using the SQLite Unlock Notification Feature].
7075**
7076** ^Shared-cache locks are released when a database connection concludes
7077** its current transaction, either by committing it or rolling it back.
7078**
7079** ^When a connection (known as the blocked connection) fails to obtain a
7080** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7081** identity of the database connection (the blocking connection) that
7082** has locked the required resource is stored internally. ^After an
7083** application receives an SQLITE_LOCKED error, it may call the
7084** sqlite3_unlock_notify() method with the blocked connection handle as
7085** the first argument to register for a callback that will be invoked
7086** when the blocking connections current transaction is concluded. ^The
7087** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7088** call that concludes the blocking connections transaction.
7089**
7090** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7091** there is a chance that the blocking connection will have already
7092** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7093** If this happens, then the specified callback is invoked immediately,
7094** from within the call to sqlite3_unlock_notify().)^
7095**
7096** ^If the blocked connection is attempting to obtain a write-lock on a
7097** shared-cache table, and more than one other connection currently holds
7098** a read-lock on the same table, then SQLite arbitrarily selects one of
7099** the other connections to use as the blocking connection.
7100**
7101** ^(There may be at most one unlock-notify callback registered by a
7102** blocked connection. If sqlite3_unlock_notify() is called when the
7103** blocked connection already has a registered unlock-notify callback,
7104** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7105** called with a NULL pointer as its second argument, then any existing
7106** unlock-notify callback is canceled. ^The blocked connections
7107** unlock-notify callback may also be canceled by closing the blocked
7108** connection using [sqlite3_close()].
7109**
7110** The unlock-notify callback is not reentrant. If an application invokes
7111** any sqlite3_xxx API functions from within an unlock-notify callback, a
7112** crash or deadlock may be the result.
7113**
7114** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7115** returns SQLITE_OK.
7116**
7117** <b>Callback Invocation Details</b>
7118**
7119** When an unlock-notify callback is registered, the application provides a
7120** single void* pointer that is passed to the callback when it is invoked.
7121** However, the signature of the callback function allows SQLite to pass
7122** it an array of void* context pointers. The first argument passed to
7123** an unlock-notify callback is a pointer to an array of void* pointers,
7124** and the second is the number of entries in the array.
7125**
7126** When a blocking connections transaction is concluded, there may be
7127** more than one blocked connection that has registered for an unlock-notify
7128** callback. ^If two or more such blocked connections have specified the
7129** same callback function, then instead of invoking the callback function
7130** multiple times, it is invoked once with the set of void* context pointers
7131** specified by the blocked connections bundled together into an array.
7132** This gives the application an opportunity to prioritize any actions
7133** related to the set of unblocked database connections.
7134**
7135** <b>Deadlock Detection</b>
7136**
7137** Assuming that after registering for an unlock-notify callback a
7138** database waits for the callback to be issued before taking any further
7139** action (a reasonable assumption), then using this API may cause the
7140** application to deadlock. For example, if connection X is waiting for
7141** connection Y's transaction to be concluded, and similarly connection
7142** Y is waiting on connection X's transaction, then neither connection
7143** will proceed and the system may remain deadlocked indefinitely.
7144**
7145** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7146** detection. ^If a given call to sqlite3_unlock_notify() would put the
7147** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7148** unlock-notify callback is registered. The system is said to be in
7149** a deadlocked state if connection A has registered for an unlock-notify
7150** callback on the conclusion of connection B's transaction, and connection
7151** B has itself registered for an unlock-notify callback when connection
7152** A's transaction is concluded. ^Indirect deadlock is also detected, so
7153** the system is also considered to be deadlocked if connection B has
7154** registered for an unlock-notify callback on the conclusion of connection
7155** C's transaction, where connection C is waiting on connection A. ^Any
7156** number of levels of indirection are allowed.
7157**
7158** <b>The "DROP TABLE" Exception</b>
7159**
7160** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7161** always appropriate to call sqlite3_unlock_notify(). There is however,
7162** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7163** SQLite checks if there are any currently executing SELECT statements
7164** that belong to the same connection. If there are, SQLITE_LOCKED is
7165** returned. In this case there is no "blocking connection", so invoking
7166** sqlite3_unlock_notify() results in the unlock-notify callback being
7167** invoked immediately. If the application then re-attempts the "DROP TABLE"
7168** or "DROP INDEX" query, an infinite loop might be the result.
7169**
7170** One way around this problem is to check the extended error code returned
7171** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7172** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7173** the special "DROP TABLE/INDEX" case, the extended error code is just
7174** SQLITE_LOCKED.)^
7175*/
7176SQLITE_API int sqlite3_unlock_notify(
7177  sqlite3 *pBlocked,                          /* Waiting connection */
7178  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7179  void *pNotifyArg                            /* Argument to pass to xNotify */
7180);
7181
7182
7183/*
7184** CAPI3REF: String Comparison
7185**
7186** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7187** and extensions to compare the contents of two buffers containing UTF-8
7188** strings in a case-independent fashion, using the same definition of "case
7189** independence" that SQLite uses internally when comparing identifiers.
7190*/
7191SQLITE_API int sqlite3_stricmp(const char *, const char *);
7192SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7193
7194/*
7195** CAPI3REF: Error Logging Interface
7196**
7197** ^The [sqlite3_log()] interface writes a message into the error log
7198** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7199** ^If logging is enabled, the zFormat string and subsequent arguments are
7200** used with [sqlite3_snprintf()] to generate the final output string.
7201**
7202** The sqlite3_log() interface is intended for use by extensions such as
7203** virtual tables, collating functions, and SQL functions.  While there is
7204** nothing to prevent an application from calling sqlite3_log(), doing so
7205** is considered bad form.
7206**
7207** The zFormat string must not be NULL.
7208**
7209** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7210** will not use dynamically allocated memory.  The log message is stored in
7211** a fixed-length buffer on the stack.  If the log message is longer than
7212** a few hundred characters, it will be truncated to the length of the
7213** buffer.
7214*/
7215SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7216
7217/*
7218** CAPI3REF: Write-Ahead Log Commit Hook
7219**
7220** ^The [sqlite3_wal_hook()] function is used to register a callback that
7221** will be invoked each time a database connection commits data to a
7222** [write-ahead log] (i.e. whenever a transaction is committed in
7223** [journal_mode | journal_mode=WAL mode]).
7224**
7225** ^The callback is invoked by SQLite after the commit has taken place and
7226** the associated write-lock on the database released, so the implementation
7227** may read, write or [checkpoint] the database as required.
7228**
7229** ^The first parameter passed to the callback function when it is invoked
7230** is a copy of the third parameter passed to sqlite3_wal_hook() when
7231** registering the callback. ^The second is a copy of the database handle.
7232** ^The third parameter is the name of the database that was written to -
7233** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7234** is the number of pages currently in the write-ahead log file,
7235** including those that were just committed.
7236**
7237** The callback function should normally return [SQLITE_OK].  ^If an error
7238** code is returned, that error will propagate back up through the
7239** SQLite code base to cause the statement that provoked the callback
7240** to report an error, though the commit will have still occurred. If the
7241** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7242** that does not correspond to any valid SQLite error code, the results
7243** are undefined.
7244**
7245** A single database handle may have at most a single write-ahead log callback
7246** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7247** previously registered write-ahead log callback. ^Note that the
7248** [sqlite3_wal_autocheckpoint()] interface and the
7249** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7250** those overwrite any prior [sqlite3_wal_hook()] settings.
7251*/
7252SQLITE_API void *sqlite3_wal_hook(
7253  sqlite3*,
7254  int(*)(void *,sqlite3*,const char*,int),
7255  void*
7256);
7257
7258/*
7259** CAPI3REF: Configure an auto-checkpoint
7260**
7261** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7262** [sqlite3_wal_hook()] that causes any database on [database connection] D
7263** to automatically [checkpoint]
7264** after committing a transaction if there are N or
7265** more frames in the [write-ahead log] file.  ^Passing zero or
7266** a negative value as the nFrame parameter disables automatic
7267** checkpoints entirely.
7268**
7269** ^The callback registered by this function replaces any existing callback
7270** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7271** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7272** configured by this function.
7273**
7274** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7275** from SQL.
7276**
7277** ^Every new [database connection] defaults to having the auto-checkpoint
7278** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7279** pages.  The use of this interface
7280** is only necessary if the default setting is found to be suboptimal
7281** for a particular application.
7282*/
7283SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7284
7285/*
7286** CAPI3REF: Checkpoint a database
7287**
7288** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7289** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7290** empty string, then a checkpoint is run on all databases of
7291** connection D.  ^If the database connection D is not in
7292** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7293**
7294** ^The [wal_checkpoint pragma] can be used to invoke this interface
7295** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7296** [wal_autocheckpoint pragma] can be used to cause this interface to be
7297** run whenever the WAL reaches a certain size threshold.
7298**
7299** See also: [sqlite3_wal_checkpoint_v2()]
7300*/
7301SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7302
7303/*
7304** CAPI3REF: Checkpoint a database
7305**
7306** Run a checkpoint operation on WAL database zDb attached to database
7307** handle db. The specific operation is determined by the value of the
7308** eMode parameter:
7309**
7310** <dl>
7311** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7312**   Checkpoint as many frames as possible without waiting for any database
7313**   readers or writers to finish. Sync the db file if all frames in the log
7314**   are checkpointed. This mode is the same as calling
7315**   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7316**
7317** <dt>SQLITE_CHECKPOINT_FULL<dd>
7318**   This mode blocks (calls the busy-handler callback) until there is no
7319**   database writer and all readers are reading from the most recent database
7320**   snapshot. It then checkpoints all frames in the log file and syncs the
7321**   database file. This call blocks database writers while it is running,
7322**   but not database readers.
7323**
7324** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7325**   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7326**   checkpointing the log file it blocks (calls the busy-handler callback)
7327**   until all readers are reading from the database file only. This ensures
7328**   that the next client to write to the database file restarts the log file
7329**   from the beginning. This call blocks database writers while it is running,
7330**   but not database readers.
7331** </dl>
7332**
7333** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7334** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7335** the total number of checkpointed frames (including any that were already
7336** checkpointed when this function is called). *pnLog and *pnCkpt may be
7337** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7338** If no values are available because of an error, they are both set to -1
7339** before returning to communicate this to the caller.
7340**
7341** All calls obtain an exclusive "checkpoint" lock on the database file. If
7342** any other process is running a checkpoint operation at the same time, the
7343** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7344** busy-handler configured, it will not be invoked in this case.
7345**
7346** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7347** "writer" lock on the database file. If the writer lock cannot be obtained
7348** immediately, and a busy-handler is configured, it is invoked and the writer
7349** lock retried until either the busy-handler returns 0 or the lock is
7350** successfully obtained. The busy-handler is also invoked while waiting for
7351** database readers as described above. If the busy-handler returns 0 before
7352** the writer lock is obtained or while waiting for database readers, the
7353** checkpoint operation proceeds from that point in the same way as
7354** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7355** without blocking any further. SQLITE_BUSY is returned in this case.
7356**
7357** If parameter zDb is NULL or points to a zero length string, then the
7358** specified operation is attempted on all WAL databases. In this case the
7359** values written to output parameters *pnLog and *pnCkpt are undefined. If
7360** an SQLITE_BUSY error is encountered when processing one or more of the
7361** attached WAL databases, the operation is still attempted on any remaining
7362** attached databases and SQLITE_BUSY is returned to the caller. If any other
7363** error occurs while processing an attached database, processing is abandoned
7364** and the error code returned to the caller immediately. If no error
7365** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7366** databases, SQLITE_OK is returned.
7367**
7368** If database zDb is the name of an attached database that is not in WAL
7369** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7370** zDb is not NULL (or a zero length string) and is not the name of any
7371** attached database, SQLITE_ERROR is returned to the caller.
7372*/
7373SQLITE_API int sqlite3_wal_checkpoint_v2(
7374  sqlite3 *db,                    /* Database handle */
7375  const char *zDb,                /* Name of attached database (or NULL) */
7376  int eMode,                      /* SQLITE_CHECKPOINT_* value */
7377  int *pnLog,                     /* OUT: Size of WAL log in frames */
7378  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7379);
7380
7381/*
7382** CAPI3REF: Checkpoint operation parameters
7383**
7384** These constants can be used as the 3rd parameter to
7385** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7386** documentation for additional information about the meaning and use of
7387** each of these values.
7388*/
7389#define SQLITE_CHECKPOINT_PASSIVE 0
7390#define SQLITE_CHECKPOINT_FULL    1
7391#define SQLITE_CHECKPOINT_RESTART 2
7392
7393/*
7394** CAPI3REF: Virtual Table Interface Configuration
7395**
7396** This function may be called by either the [xConnect] or [xCreate] method
7397** of a [virtual table] implementation to configure
7398** various facets of the virtual table interface.
7399**
7400** If this interface is invoked outside the context of an xConnect or
7401** xCreate virtual table method then the behavior is undefined.
7402**
7403** At present, there is only one option that may be configured using
7404** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7405** may be added in the future.
7406*/
7407SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7408
7409/*
7410** CAPI3REF: Virtual Table Configuration Options
7411**
7412** These macros define the various options to the
7413** [sqlite3_vtab_config()] interface that [virtual table] implementations
7414** can use to customize and optimize their behavior.
7415**
7416** <dl>
7417** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7418** <dd>Calls of the form
7419** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7420** where X is an integer.  If X is zero, then the [virtual table] whose
7421** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7422** support constraints.  In this configuration (which is the default) if
7423** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7424** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7425** specified as part of the users SQL statement, regardless of the actual
7426** ON CONFLICT mode specified.
7427**
7428** If X is non-zero, then the virtual table implementation guarantees
7429** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7430** any modifications to internal or persistent data structures have been made.
7431** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7432** is able to roll back a statement or database transaction, and abandon
7433** or continue processing the current SQL statement as appropriate.
7434** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7435** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7436** had been ABORT.
7437**
7438** Virtual table implementations that are required to handle OR REPLACE
7439** must do so within the [xUpdate] method. If a call to the
7440** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7441** CONFLICT policy is REPLACE, the virtual table implementation should
7442** silently replace the appropriate rows within the xUpdate callback and
7443** return SQLITE_OK. Or, if this is not possible, it may return
7444** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7445** constraint handling.
7446** </dl>
7447*/
7448#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7449
7450/*
7451** CAPI3REF: Determine The Virtual Table Conflict Policy
7452**
7453** This function may only be called from within a call to the [xUpdate] method
7454** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7455** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7456** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7457** of the SQL statement that triggered the call to the [xUpdate] method of the
7458** [virtual table].
7459*/
7460SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7461
7462/*
7463** CAPI3REF: Conflict resolution modes
7464**
7465** These constants are returned by [sqlite3_vtab_on_conflict()] to
7466** inform a [virtual table] implementation what the [ON CONFLICT] mode
7467** is for the SQL statement being evaluated.
7468**
7469** Note that the [SQLITE_IGNORE] constant is also used as a potential
7470** return value from the [sqlite3_set_authorizer()] callback and that
7471** [SQLITE_ABORT] is also a [result code].
7472*/
7473#define SQLITE_ROLLBACK 1
7474/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7475#define SQLITE_FAIL     3
7476/* #define SQLITE_ABORT 4  // Also an error code */
7477#define SQLITE_REPLACE  5
7478
7479
7480
7481/*
7482** Undo the hack that converts floating point types to integer for
7483** builds on processors without floating point support.
7484*/
7485#ifdef SQLITE_OMIT_FLOATING_POINT
7486# undef double
7487#endif
7488
7489#if 0
7490}  /* End of the 'extern "C"' block */
7491#endif
7492#endif
7493
7494/*
7495** 2010 August 30
7496**
7497** The author disclaims copyright to this source code.  In place of
7498** a legal notice, here is a blessing:
7499**
7500**    May you do good and not evil.
7501**    May you find forgiveness for yourself and forgive others.
7502**    May you share freely, never taking more than you give.
7503**
7504*************************************************************************
7505*/
7506
7507#ifndef _SQLITE3RTREE_H_
7508#define _SQLITE3RTREE_H_
7509
7510
7511#if 0
7512extern "C" {
7513#endif
7514
7515typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7516
7517/*
7518** Register a geometry callback named zGeom that can be used as part of an
7519** R-Tree geometry query as follows:
7520**
7521**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7522*/
7523SQLITE_API int sqlite3_rtree_geometry_callback(
7524  sqlite3 *db,
7525  const char *zGeom,
7526  int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
7527  void *pContext
7528);
7529
7530
7531/*
7532** A pointer to a structure of the following type is passed as the first
7533** argument to callbacks registered using rtree_geometry_callback().
7534*/
7535struct sqlite3_rtree_geometry {
7536  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7537  int nParam;                     /* Size of array aParam[] */
7538  double *aParam;                 /* Parameters passed to SQL geom function */
7539  void *pUser;                    /* Callback implementation user data */
7540  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7541};
7542
7543
7544#if 0
7545}  /* end of the 'extern "C"' block */
7546#endif
7547
7548#endif  /* ifndef _SQLITE3RTREE_H_ */
7549
7550
7551/************** End of sqlite3.h *********************************************/
7552/************** Continuing where we left off in sqliteInt.h ******************/
7553/************** Include hash.h in the middle of sqliteInt.h ******************/
7554/************** Begin file hash.h ********************************************/
7555/*
7556** 2001 September 22
7557**
7558** The author disclaims copyright to this source code.  In place of
7559** a legal notice, here is a blessing:
7560**
7561**    May you do good and not evil.
7562**    May you find forgiveness for yourself and forgive others.
7563**    May you share freely, never taking more than you give.
7564**
7565*************************************************************************
7566** This is the header file for the generic hash-table implemenation
7567** used in SQLite.
7568*/
7569#ifndef _SQLITE_HASH_H_
7570#define _SQLITE_HASH_H_
7571
7572/* Forward declarations of structures. */
7573typedef struct Hash Hash;
7574typedef struct HashElem HashElem;
7575
7576/* A complete hash table is an instance of the following structure.
7577** The internals of this structure are intended to be opaque -- client
7578** code should not attempt to access or modify the fields of this structure
7579** directly.  Change this structure only by using the routines below.
7580** However, some of the "procedures" and "functions" for modifying and
7581** accessing this structure are really macros, so we can't really make
7582** this structure opaque.
7583**
7584** All elements of the hash table are on a single doubly-linked list.
7585** Hash.first points to the head of this list.
7586**
7587** There are Hash.htsize buckets.  Each bucket points to a spot in
7588** the global doubly-linked list.  The contents of the bucket are the
7589** element pointed to plus the next _ht.count-1 elements in the list.
7590**
7591** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7592** by a linear search of the global list.  For small tables, the
7593** Hash.ht table is never allocated because if there are few elements
7594** in the table, it is faster to do a linear search than to manage
7595** the hash table.
7596*/
7597struct Hash {
7598  unsigned int htsize;      /* Number of buckets in the hash table */
7599  unsigned int count;       /* Number of entries in this table */
7600  HashElem *first;          /* The first element of the array */
7601  struct _ht {              /* the hash table */
7602    int count;                 /* Number of entries with this hash */
7603    HashElem *chain;           /* Pointer to first entry with this hash */
7604  } *ht;
7605};
7606
7607/* Each element in the hash table is an instance of the following
7608** structure.  All elements are stored on a single doubly-linked list.
7609**
7610** Again, this structure is intended to be opaque, but it can't really
7611** be opaque because it is used by macros.
7612*/
7613struct HashElem {
7614  HashElem *next, *prev;       /* Next and previous elements in the table */
7615  void *data;                  /* Data associated with this element */
7616  const char *pKey; int nKey;  /* Key associated with this element */
7617};
7618
7619/*
7620** Access routines.  To delete, insert a NULL pointer.
7621*/
7622SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7623SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7624SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7625SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7626
7627/*
7628** Macros for looping over all elements of a hash table.  The idiom is
7629** like this:
7630**
7631**   Hash h;
7632**   HashElem *p;
7633**   ...
7634**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7635**     SomeStructure *pData = sqliteHashData(p);
7636**     // do something with pData
7637**   }
7638*/
7639#define sqliteHashFirst(H)  ((H)->first)
7640#define sqliteHashNext(E)   ((E)->next)
7641#define sqliteHashData(E)   ((E)->data)
7642/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7643/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7644
7645/*
7646** Number of entries in a hash table
7647*/
7648/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7649
7650#endif /* _SQLITE_HASH_H_ */
7651
7652/************** End of hash.h ************************************************/
7653/************** Continuing where we left off in sqliteInt.h ******************/
7654/************** Include parse.h in the middle of sqliteInt.h *****************/
7655/************** Begin file parse.h *******************************************/
7656#define TK_SEMI                            1
7657#define TK_EXPLAIN                         2
7658#define TK_QUERY                           3
7659#define TK_PLAN                            4
7660#define TK_BEGIN                           5
7661#define TK_TRANSACTION                     6
7662#define TK_DEFERRED                        7
7663#define TK_IMMEDIATE                       8
7664#define TK_EXCLUSIVE                       9
7665#define TK_COMMIT                         10
7666#define TK_END                            11
7667#define TK_ROLLBACK                       12
7668#define TK_SAVEPOINT                      13
7669#define TK_RELEASE                        14
7670#define TK_TO                             15
7671#define TK_TABLE                          16
7672#define TK_CREATE                         17
7673#define TK_IF                             18
7674#define TK_NOT                            19
7675#define TK_EXISTS                         20
7676#define TK_TEMP                           21
7677#define TK_LP                             22
7678#define TK_RP                             23
7679#define TK_AS                             24
7680#define TK_COMMA                          25
7681#define TK_ID                             26
7682#define TK_INDEXED                        27
7683#define TK_ABORT                          28
7684#define TK_ACTION                         29
7685#define TK_AFTER                          30
7686#define TK_ANALYZE                        31
7687#define TK_ASC                            32
7688#define TK_ATTACH                         33
7689#define TK_BEFORE                         34
7690#define TK_BY                             35
7691#define TK_CASCADE                        36
7692#define TK_CAST                           37
7693#define TK_COLUMNKW                       38
7694#define TK_CONFLICT                       39
7695#define TK_DATABASE                       40
7696#define TK_DESC                           41
7697#define TK_DETACH                         42
7698#define TK_EACH                           43
7699#define TK_FAIL                           44
7700#define TK_FOR                            45
7701#define TK_IGNORE                         46
7702#define TK_INITIALLY                      47
7703#define TK_INSTEAD                        48
7704#define TK_LIKE_KW                        49
7705#define TK_MATCH                          50
7706#define TK_NO                             51
7707#define TK_KEY                            52
7708#define TK_OF                             53
7709#define TK_OFFSET                         54
7710#define TK_PRAGMA                         55
7711#define TK_RAISE                          56
7712#define TK_REPLACE                        57
7713#define TK_RESTRICT                       58
7714#define TK_ROW                            59
7715#define TK_TRIGGER                        60
7716#define TK_VACUUM                         61
7717#define TK_VIEW                           62
7718#define TK_VIRTUAL                        63
7719#define TK_REINDEX                        64
7720#define TK_RENAME                         65
7721#define TK_CTIME_KW                       66
7722#define TK_ANY                            67
7723#define TK_OR                             68
7724#define TK_AND                            69
7725#define TK_IS                             70
7726#define TK_BETWEEN                        71
7727#define TK_IN                             72
7728#define TK_ISNULL                         73
7729#define TK_NOTNULL                        74
7730#define TK_NE                             75
7731#define TK_EQ                             76
7732#define TK_GT                             77
7733#define TK_LE                             78
7734#define TK_LT                             79
7735#define TK_GE                             80
7736#define TK_ESCAPE                         81
7737#define TK_BITAND                         82
7738#define TK_BITOR                          83
7739#define TK_LSHIFT                         84
7740#define TK_RSHIFT                         85
7741#define TK_PLUS                           86
7742#define TK_MINUS                          87
7743#define TK_STAR                           88
7744#define TK_SLASH                          89
7745#define TK_REM                            90
7746#define TK_CONCAT                         91
7747#define TK_COLLATE                        92
7748#define TK_BITNOT                         93
7749#define TK_STRING                         94
7750#define TK_JOIN_KW                        95
7751#define TK_CONSTRAINT                     96
7752#define TK_DEFAULT                        97
7753#define TK_NULL                           98
7754#define TK_PRIMARY                        99
7755#define TK_UNIQUE                         100
7756#define TK_CHECK                          101
7757#define TK_REFERENCES                     102
7758#define TK_AUTOINCR                       103
7759#define TK_ON                             104
7760#define TK_INSERT                         105
7761#define TK_DELETE                         106
7762#define TK_UPDATE                         107
7763#define TK_SET                            108
7764#define TK_DEFERRABLE                     109
7765#define TK_FOREIGN                        110
7766#define TK_DROP                           111
7767#define TK_UNION                          112
7768#define TK_ALL                            113
7769#define TK_EXCEPT                         114
7770#define TK_INTERSECT                      115
7771#define TK_SELECT                         116
7772#define TK_DISTINCT                       117
7773#define TK_DOT                            118
7774#define TK_FROM                           119
7775#define TK_JOIN                           120
7776#define TK_USING                          121
7777#define TK_ORDER                          122
7778#define TK_GROUP                          123
7779#define TK_HAVING                         124
7780#define TK_LIMIT                          125
7781#define TK_WHERE                          126
7782#define TK_INTO                           127
7783#define TK_VALUES                         128
7784#define TK_INTEGER                        129
7785#define TK_FLOAT                          130
7786#define TK_BLOB                           131
7787#define TK_REGISTER                       132
7788#define TK_VARIABLE                       133
7789#define TK_CASE                           134
7790#define TK_WHEN                           135
7791#define TK_THEN                           136
7792#define TK_ELSE                           137
7793#define TK_INDEX                          138
7794#define TK_ALTER                          139
7795#define TK_ADD                            140
7796#define TK_TO_TEXT                        141
7797#define TK_TO_BLOB                        142
7798#define TK_TO_NUMERIC                     143
7799#define TK_TO_INT                         144
7800#define TK_TO_REAL                        145
7801#define TK_ISNOT                          146
7802#define TK_END_OF_FILE                    147
7803#define TK_ILLEGAL                        148
7804#define TK_SPACE                          149
7805#define TK_UNCLOSED_STRING                150
7806#define TK_FUNCTION                       151
7807#define TK_COLUMN                         152
7808#define TK_AGG_FUNCTION                   153
7809#define TK_AGG_COLUMN                     154
7810#define TK_CONST_FUNC                     155
7811#define TK_UMINUS                         156
7812#define TK_UPLUS                          157
7813
7814/************** End of parse.h ***********************************************/
7815/************** Continuing where we left off in sqliteInt.h ******************/
7816#include <stdio.h>
7817#include <stdlib.h>
7818#include <string.h>
7819#include <assert.h>
7820#include <stddef.h>
7821
7822/*
7823** If compiling for a processor that lacks floating point support,
7824** substitute integer for floating-point
7825*/
7826#ifdef SQLITE_OMIT_FLOATING_POINT
7827# define double sqlite_int64
7828# define float sqlite_int64
7829# define LONGDOUBLE_TYPE sqlite_int64
7830# ifndef SQLITE_BIG_DBL
7831#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7832# endif
7833# define SQLITE_OMIT_DATETIME_FUNCS 1
7834# define SQLITE_OMIT_TRACE 1
7835# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7836# undef SQLITE_HAVE_ISNAN
7837#endif
7838#ifndef SQLITE_BIG_DBL
7839# define SQLITE_BIG_DBL (1e99)
7840#endif
7841
7842/*
7843** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7844** afterward. Having this macro allows us to cause the C compiler
7845** to omit code used by TEMP tables without messy #ifndef statements.
7846*/
7847#ifdef SQLITE_OMIT_TEMPDB
7848#define OMIT_TEMPDB 1
7849#else
7850#define OMIT_TEMPDB 0
7851#endif
7852
7853/*
7854** The "file format" number is an integer that is incremented whenever
7855** the VDBE-level file format changes.  The following macros define the
7856** the default file format for new databases and the maximum file format
7857** that the library can read.
7858*/
7859#define SQLITE_MAX_FILE_FORMAT 4
7860#ifndef SQLITE_DEFAULT_FILE_FORMAT
7861# define SQLITE_DEFAULT_FILE_FORMAT 4
7862#endif
7863
7864/*
7865** Determine whether triggers are recursive by default.  This can be
7866** changed at run-time using a pragma.
7867*/
7868#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7869# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7870#endif
7871
7872/*
7873** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7874** on the command-line
7875*/
7876#ifndef SQLITE_TEMP_STORE
7877# define SQLITE_TEMP_STORE 1
7878#endif
7879
7880/*
7881** GCC does not define the offsetof() macro so we'll have to do it
7882** ourselves.
7883*/
7884#ifndef offsetof
7885#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7886#endif
7887
7888/*
7889** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7890** not, there are still machines out there that use EBCDIC.)
7891*/
7892#if 'A' == '\301'
7893# define SQLITE_EBCDIC 1
7894#else
7895# define SQLITE_ASCII 1
7896#endif
7897
7898/*
7899** Integers of known sizes.  These typedefs might change for architectures
7900** where the sizes very.  Preprocessor macros are available so that the
7901** types can be conveniently redefined at compile-type.  Like this:
7902**
7903**         cc '-DUINTPTR_TYPE=long long int' ...
7904*/
7905#ifndef UINT32_TYPE
7906# ifdef HAVE_UINT32_T
7907#  define UINT32_TYPE uint32_t
7908# else
7909#  define UINT32_TYPE unsigned int
7910# endif
7911#endif
7912#ifndef UINT16_TYPE
7913# ifdef HAVE_UINT16_T
7914#  define UINT16_TYPE uint16_t
7915# else
7916#  define UINT16_TYPE unsigned short int
7917# endif
7918#endif
7919#ifndef INT16_TYPE
7920# ifdef HAVE_INT16_T
7921#  define INT16_TYPE int16_t
7922# else
7923#  define INT16_TYPE short int
7924# endif
7925#endif
7926#ifndef UINT8_TYPE
7927# ifdef HAVE_UINT8_T
7928#  define UINT8_TYPE uint8_t
7929# else
7930#  define UINT8_TYPE unsigned char
7931# endif
7932#endif
7933#ifndef INT8_TYPE
7934# ifdef HAVE_INT8_T
7935#  define INT8_TYPE int8_t
7936# else
7937#  define INT8_TYPE signed char
7938# endif
7939#endif
7940#ifndef LONGDOUBLE_TYPE
7941# define LONGDOUBLE_TYPE long double
7942#endif
7943typedef sqlite_int64 i64;          /* 8-byte signed integer */
7944typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7945typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7946typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7947typedef INT16_TYPE i16;            /* 2-byte signed integer */
7948typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7949typedef INT8_TYPE i8;              /* 1-byte signed integer */
7950
7951/*
7952** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7953** that can be stored in a u32 without loss of data.  The value
7954** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7955** have to specify the value in the less intuitive manner shown:
7956*/
7957#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
7958
7959/*
7960** The datatype used to store estimates of the number of rows in a
7961** table or index.  This is an unsigned integer type.  For 99.9% of
7962** the world, a 32-bit integer is sufficient.  But a 64-bit integer
7963** can be used at compile-time if desired.
7964*/
7965#ifdef SQLITE_64BIT_STATS
7966 typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
7967#else
7968 typedef u32 tRowcnt;    /* 32-bit is the default */
7969#endif
7970
7971/*
7972** Macros to determine whether the machine is big or little endian,
7973** evaluated at runtime.
7974*/
7975#ifdef SQLITE_AMALGAMATION
7976SQLITE_PRIVATE const int sqlite3one = 1;
7977#else
7978SQLITE_PRIVATE const int sqlite3one;
7979#endif
7980#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7981                             || defined(__x86_64) || defined(__x86_64__)
7982# define SQLITE_BIGENDIAN    0
7983# define SQLITE_LITTLEENDIAN 1
7984# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7985#else
7986# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7987# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7988# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7989#endif
7990
7991/*
7992** Constants for the largest and smallest possible 64-bit signed integers.
7993** These macros are designed to work correctly on both 32-bit and 64-bit
7994** compilers.
7995*/
7996#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7997#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7998
7999/*
8000** Round up a number to the next larger multiple of 8.  This is used
8001** to force 8-byte alignment on 64-bit architectures.
8002*/
8003#define ROUND8(x)     (((x)+7)&~7)
8004
8005/*
8006** Round down to the nearest multiple of 8
8007*/
8008#define ROUNDDOWN8(x) ((x)&~7)
8009
8010/*
8011** Assert that the pointer X is aligned to an 8-byte boundary.  This
8012** macro is used only within assert() to verify that the code gets
8013** all alignment restrictions correct.
8014**
8015** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8016** underlying malloc() implemention might return us 4-byte aligned
8017** pointers.  In that case, only verify 4-byte alignment.
8018*/
8019#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8020# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
8021#else
8022# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
8023#endif
8024
8025
8026/*
8027** An instance of the following structure is used to store the busy-handler
8028** callback for a given sqlite handle.
8029**
8030** The sqlite.busyHandler member of the sqlite struct contains the busy
8031** callback for the database handle. Each pager opened via the sqlite
8032** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8033** callback is currently invoked only from within pager.c.
8034*/
8035typedef struct BusyHandler BusyHandler;
8036struct BusyHandler {
8037  int (*xFunc)(void *,int);  /* The busy callback */
8038  void *pArg;                /* First arg to busy callback */
8039  int nBusy;                 /* Incremented with each busy call */
8040};
8041
8042/*
8043** Name of the master database table.  The master database table
8044** is a special table that holds the names and attributes of all
8045** user tables and indices.
8046*/
8047#define MASTER_NAME       "sqlite_master"
8048#define TEMP_MASTER_NAME  "sqlite_temp_master"
8049
8050/*
8051** The root-page of the master database table.
8052*/
8053#define MASTER_ROOT       1
8054
8055/*
8056** The name of the schema table.
8057*/
8058#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8059
8060/*
8061** A convenience macro that returns the number of elements in
8062** an array.
8063*/
8064#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
8065
8066/*
8067** The following value as a destructor means to use sqlite3DbFree().
8068** The sqlite3DbFree() routine requires two parameters instead of the
8069** one parameter that destructors normally want.  So we have to introduce
8070** this magic value that the code knows to handle differently.  Any
8071** pointer will work here as long as it is distinct from SQLITE_STATIC
8072** and SQLITE_TRANSIENT.
8073*/
8074#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
8075
8076/*
8077** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8078** not support Writable Static Data (WSD) such as global and static variables.
8079** All variables must either be on the stack or dynamically allocated from
8080** the heap.  When WSD is unsupported, the variable declarations scattered
8081** throughout the SQLite code must become constants instead.  The SQLITE_WSD
8082** macro is used for this purpose.  And instead of referencing the variable
8083** directly, we use its constant as a key to lookup the run-time allocated
8084** buffer that holds real variable.  The constant is also the initializer
8085** for the run-time allocated buffer.
8086**
8087** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8088** macros become no-ops and have zero performance impact.
8089*/
8090#ifdef SQLITE_OMIT_WSD
8091  #define SQLITE_WSD const
8092  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8093  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8094SQLITE_API   int sqlite3_wsd_init(int N, int J);
8095SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
8096#else
8097  #define SQLITE_WSD
8098  #define GLOBAL(t,v) v
8099  #define sqlite3GlobalConfig sqlite3Config
8100#endif
8101
8102/*
8103** The following macros are used to suppress compiler warnings and to
8104** make it clear to human readers when a function parameter is deliberately
8105** left unused within the body of a function. This usually happens when
8106** a function is called via a function pointer. For example the
8107** implementation of an SQL aggregate step callback may not use the
8108** parameter indicating the number of arguments passed to the aggregate,
8109** if it knows that this is enforced elsewhere.
8110**
8111** When a function parameter is not used at all within the body of a function,
8112** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8113** However, these macros may also be used to suppress warnings related to
8114** parameters that may or may not be used depending on compilation options.
8115** For example those parameters only used in assert() statements. In these
8116** cases the parameters are named as per the usual conventions.
8117*/
8118#define UNUSED_PARAMETER(x) (void)(x)
8119#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8120
8121/*
8122** Forward references to structures
8123*/
8124typedef struct AggInfo AggInfo;
8125typedef struct AuthContext AuthContext;
8126typedef struct AutoincInfo AutoincInfo;
8127typedef struct Bitvec Bitvec;
8128typedef struct CollSeq CollSeq;
8129typedef struct Column Column;
8130typedef struct Db Db;
8131typedef struct Schema Schema;
8132typedef struct Expr Expr;
8133typedef struct ExprList ExprList;
8134typedef struct ExprSpan ExprSpan;
8135typedef struct FKey FKey;
8136typedef struct FuncDestructor FuncDestructor;
8137typedef struct FuncDef FuncDef;
8138typedef struct FuncDefHash FuncDefHash;
8139typedef struct IdList IdList;
8140typedef struct Index Index;
8141typedef struct IndexSample IndexSample;
8142typedef struct KeyClass KeyClass;
8143typedef struct KeyInfo KeyInfo;
8144typedef struct Lookaside Lookaside;
8145typedef struct LookasideSlot LookasideSlot;
8146typedef struct Module Module;
8147typedef struct NameContext NameContext;
8148typedef struct Parse Parse;
8149typedef struct RowSet RowSet;
8150typedef struct Savepoint Savepoint;
8151typedef struct Select Select;
8152typedef struct SrcList SrcList;
8153typedef struct StrAccum StrAccum;
8154typedef struct Table Table;
8155typedef struct TableLock TableLock;
8156typedef struct Token Token;
8157typedef struct Trigger Trigger;
8158typedef struct TriggerPrg TriggerPrg;
8159typedef struct TriggerStep TriggerStep;
8160typedef struct UnpackedRecord UnpackedRecord;
8161typedef struct VTable VTable;
8162typedef struct VtabCtx VtabCtx;
8163typedef struct Walker Walker;
8164typedef struct WherePlan WherePlan;
8165typedef struct WhereInfo WhereInfo;
8166typedef struct WhereLevel WhereLevel;
8167
8168/*
8169** Defer sourcing vdbe.h and btree.h until after the "u8" and
8170** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8171** pointer types (i.e. FuncDef) defined above.
8172*/
8173/************** Include btree.h in the middle of sqliteInt.h *****************/
8174/************** Begin file btree.h *******************************************/
8175/*
8176** 2001 September 15
8177**
8178** The author disclaims copyright to this source code.  In place of
8179** a legal notice, here is a blessing:
8180**
8181**    May you do good and not evil.
8182**    May you find forgiveness for yourself and forgive others.
8183**    May you share freely, never taking more than you give.
8184**
8185*************************************************************************
8186** This header file defines the interface that the sqlite B-Tree file
8187** subsystem.  See comments in the source code for a detailed description
8188** of what each interface routine does.
8189*/
8190#ifndef _BTREE_H_
8191#define _BTREE_H_
8192
8193/* TODO: This definition is just included so other modules compile. It
8194** needs to be revisited.
8195*/
8196#define SQLITE_N_BTREE_META 10
8197
8198/*
8199** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8200** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8201*/
8202#ifndef SQLITE_DEFAULT_AUTOVACUUM
8203  #define SQLITE_DEFAULT_AUTOVACUUM 0
8204#endif
8205
8206#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8207#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8208#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8209
8210/*
8211** Forward declarations of structure
8212*/
8213typedef struct Btree Btree;
8214typedef struct BtCursor BtCursor;
8215typedef struct BtShared BtShared;
8216
8217
8218SQLITE_PRIVATE int sqlite3BtreeOpen(
8219  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
8220  const char *zFilename,   /* Name of database file to open */
8221  sqlite3 *db,             /* Associated database connection */
8222  Btree **ppBtree,         /* Return open Btree* here */
8223  int flags,               /* Flags */
8224  int vfsFlags             /* Flags passed through to VFS open */
8225);
8226
8227/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8228** following values.
8229**
8230** NOTE:  These values must match the corresponding PAGER_ values in
8231** pager.h.
8232*/
8233#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8234#define BTREE_MEMORY        2  /* This is an in-memory DB */
8235#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
8236#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
8237
8238SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8239SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8240SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
8241SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8242SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8243SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8244SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8245SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8246SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8247SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8248SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8249SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8250SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8251SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8252SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8253SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8254SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8255SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8256SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8257SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8258SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8259SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8260SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8261SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8262SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8263SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8264
8265SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8266SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8267SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8268
8269SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8270
8271/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8272** of the flags shown below.
8273**
8274** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8275** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8276** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8277** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8278** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8279** indices.)
8280*/
8281#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8282#define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8283
8284SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8285SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8286SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8287
8288SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8289SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8290
8291/*
8292** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8293** should be one of the following values. The integer values are assigned
8294** to constants so that the offset of the corresponding field in an
8295** SQLite database header may be found using the following formula:
8296**
8297**   offset = 36 + (idx * 4)
8298**
8299** For example, the free-page-count field is located at byte offset 36 of
8300** the database file header. The incr-vacuum-flag field is located at
8301** byte offset 64 (== 36+4*7).
8302*/
8303#define BTREE_FREE_PAGE_COUNT     0
8304#define BTREE_SCHEMA_VERSION      1
8305#define BTREE_FILE_FORMAT         2
8306#define BTREE_DEFAULT_CACHE_SIZE  3
8307#define BTREE_LARGEST_ROOT_PAGE   4
8308#define BTREE_TEXT_ENCODING       5
8309#define BTREE_USER_VERSION        6
8310#define BTREE_INCR_VACUUM         7
8311
8312SQLITE_PRIVATE int sqlite3BtreeCursor(
8313  Btree*,                              /* BTree containing table to open */
8314  int iTable,                          /* Index of root page */
8315  int wrFlag,                          /* 1 for writing.  0 for read-only */
8316  struct KeyInfo*,                     /* First argument to compare function */
8317  BtCursor *pCursor                    /* Space to write cursor structure */
8318);
8319SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8320SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8321
8322SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8323SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8324  BtCursor*,
8325  UnpackedRecord *pUnKey,
8326  i64 intKey,
8327  int bias,
8328  int *pRes
8329);
8330SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8331SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8332SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8333                                  const void *pData, int nData,
8334                                  int nZero, int bias, int seekResult);
8335SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8336SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8337SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8338SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8339SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8340SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8341SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8342SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8343SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8344SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8345SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8346SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8347SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8348
8349SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8350SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8351
8352SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8353SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8354SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8355
8356SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8357
8358#ifndef NDEBUG
8359SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8360#endif
8361
8362#ifndef SQLITE_OMIT_BTREECOUNT
8363SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8364#endif
8365
8366#ifdef SQLITE_TEST
8367SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8368SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8369#endif
8370
8371#ifndef SQLITE_OMIT_WAL
8372SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8373#endif
8374
8375/*
8376** If we are not using shared cache, then there is no need to
8377** use mutexes to access the BtShared structures.  So make the
8378** Enter and Leave procedures no-ops.
8379*/
8380#ifndef SQLITE_OMIT_SHARED_CACHE
8381SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8382SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8383#else
8384# define sqlite3BtreeEnter(X)
8385# define sqlite3BtreeEnterAll(X)
8386#endif
8387
8388#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8389SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
8390SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8391SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8392SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8393SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8394#ifndef NDEBUG
8395  /* These routines are used inside assert() statements only. */
8396SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8397SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8398SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8399#endif
8400#else
8401
8402# define sqlite3BtreeSharable(X) 0
8403# define sqlite3BtreeLeave(X)
8404# define sqlite3BtreeEnterCursor(X)
8405# define sqlite3BtreeLeaveCursor(X)
8406# define sqlite3BtreeLeaveAll(X)
8407
8408# define sqlite3BtreeHoldsMutex(X) 1
8409# define sqlite3BtreeHoldsAllMutexes(X) 1
8410# define sqlite3SchemaMutexHeld(X,Y,Z) 1
8411#endif
8412
8413
8414#endif /* _BTREE_H_ */
8415
8416/************** End of btree.h ***********************************************/
8417/************** Continuing where we left off in sqliteInt.h ******************/
8418/************** Include vdbe.h in the middle of sqliteInt.h ******************/
8419/************** Begin file vdbe.h ********************************************/
8420/*
8421** 2001 September 15
8422**
8423** The author disclaims copyright to this source code.  In place of
8424** a legal notice, here is a blessing:
8425**
8426**    May you do good and not evil.
8427**    May you find forgiveness for yourself and forgive others.
8428**    May you share freely, never taking more than you give.
8429**
8430*************************************************************************
8431** Header file for the Virtual DataBase Engine (VDBE)
8432**
8433** This header defines the interface to the virtual database engine
8434** or VDBE.  The VDBE implements an abstract machine that runs a
8435** simple program to access and modify the underlying database.
8436*/
8437#ifndef _SQLITE_VDBE_H_
8438#define _SQLITE_VDBE_H_
8439/* #include <stdio.h> */
8440
8441/*
8442** A single VDBE is an opaque structure named "Vdbe".  Only routines
8443** in the source file sqliteVdbe.c are allowed to see the insides
8444** of this structure.
8445*/
8446typedef struct Vdbe Vdbe;
8447
8448/*
8449** The names of the following types declared in vdbeInt.h are required
8450** for the VdbeOp definition.
8451*/
8452typedef struct VdbeFunc VdbeFunc;
8453typedef struct Mem Mem;
8454typedef struct SubProgram SubProgram;
8455
8456/*
8457** A single instruction of the virtual machine has an opcode
8458** and as many as three operands.  The instruction is recorded
8459** as an instance of the following structure:
8460*/
8461struct VdbeOp {
8462  u8 opcode;          /* What operation to perform */
8463  signed char p4type; /* One of the P4_xxx constants for p4 */
8464  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8465  u8 p5;              /* Fifth parameter is an unsigned character */
8466  int p1;             /* First operand */
8467  int p2;             /* Second parameter (often the jump destination) */
8468  int p3;             /* The third parameter */
8469  union {             /* fourth parameter */
8470    int i;                 /* Integer value if p4type==P4_INT32 */
8471    void *p;               /* Generic pointer */
8472    char *z;               /* Pointer to data for string (char array) types */
8473    i64 *pI64;             /* Used when p4type is P4_INT64 */
8474    double *pReal;         /* Used when p4type is P4_REAL */
8475    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8476    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8477    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8478    Mem *pMem;             /* Used when p4type is P4_MEM */
8479    VTable *pVtab;         /* Used when p4type is P4_VTAB */
8480    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8481    int *ai;               /* Used when p4type is P4_INTARRAY */
8482    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8483    int (*xAdvance)(BtCursor *, int *);
8484  } p4;
8485#ifdef SQLITE_DEBUG
8486  char *zComment;          /* Comment to improve readability */
8487#endif
8488#ifdef VDBE_PROFILE
8489  int cnt;                 /* Number of times this instruction was executed */
8490  u64 cycles;              /* Total time spent executing this instruction */
8491#endif
8492};
8493typedef struct VdbeOp VdbeOp;
8494
8495
8496/*
8497** A sub-routine used to implement a trigger program.
8498*/
8499struct SubProgram {
8500  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8501  int nOp;                      /* Elements in aOp[] */
8502  int nMem;                     /* Number of memory cells required */
8503  int nCsr;                     /* Number of cursors required */
8504  int nOnce;                    /* Number of OP_Once instructions */
8505  void *token;                  /* id that may be used to recursive triggers */
8506  SubProgram *pNext;            /* Next sub-program already visited */
8507};
8508
8509/*
8510** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8511** it takes up less space.
8512*/
8513struct VdbeOpList {
8514  u8 opcode;          /* What operation to perform */
8515  signed char p1;     /* First operand */
8516  signed char p2;     /* Second parameter (often the jump destination) */
8517  signed char p3;     /* Third parameter */
8518};
8519typedef struct VdbeOpList VdbeOpList;
8520
8521/*
8522** Allowed values of VdbeOp.p4type
8523*/
8524#define P4_NOTUSED    0   /* The P4 parameter is not used */
8525#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8526#define P4_STATIC   (-2)  /* Pointer to a static string */
8527#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8528#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8529#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8530#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8531#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8532#define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8533#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8534#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8535#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8536#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8537#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8538#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8539#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8540#define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8541
8542/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8543** is made.  That copy is freed when the Vdbe is finalized.  But if the
8544** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8545** gets freed when the Vdbe is finalized so it still should be obtained
8546** from a single sqliteMalloc().  But no copy is made and the calling
8547** function should *not* try to free the KeyInfo.
8548*/
8549#define P4_KEYINFO_HANDOFF (-16)
8550#define P4_KEYINFO_STATIC  (-17)
8551
8552/*
8553** The Vdbe.aColName array contains 5n Mem structures, where n is the
8554** number of columns of data returned by the statement.
8555*/
8556#define COLNAME_NAME     0
8557#define COLNAME_DECLTYPE 1
8558#define COLNAME_DATABASE 2
8559#define COLNAME_TABLE    3
8560#define COLNAME_COLUMN   4
8561#ifdef SQLITE_ENABLE_COLUMN_METADATA
8562# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8563#else
8564# ifdef SQLITE_OMIT_DECLTYPE
8565#   define COLNAME_N      1      /* Store only the name */
8566# else
8567#   define COLNAME_N      2      /* Store the name and decltype */
8568# endif
8569#endif
8570
8571/*
8572** The following macro converts a relative address in the p2 field
8573** of a VdbeOp structure into a negative number so that
8574** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8575** the macro again restores the address.
8576*/
8577#define ADDR(X)  (-1-(X))
8578
8579/*
8580** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8581** header file that defines a number for each opcode used by the VDBE.
8582*/
8583/************** Include opcodes.h in the middle of vdbe.h ********************/
8584/************** Begin file opcodes.h *****************************************/
8585/* Automatically generated.  Do not edit */
8586/* See the mkopcodeh.awk script for details */
8587#define OP_Goto                                 1
8588#define OP_Gosub                                2
8589#define OP_Return                               3
8590#define OP_Yield                                4
8591#define OP_HaltIfNull                           5
8592#define OP_Halt                                 6
8593#define OP_Integer                              7
8594#define OP_Int64                                8
8595#define OP_Real                               130   /* same as TK_FLOAT    */
8596#define OP_String8                             94   /* same as TK_STRING   */
8597#define OP_String                               9
8598#define OP_Null                                10
8599#define OP_Blob                                11
8600#define OP_Variable                            12
8601#define OP_Move                                13
8602#define OP_Copy                                14
8603#define OP_SCopy                               15
8604#define OP_ResultRow                           16
8605#define OP_Concat                              91   /* same as TK_CONCAT   */
8606#define OP_Add                                 86   /* same as TK_PLUS     */
8607#define OP_Subtract                            87   /* same as TK_MINUS    */
8608#define OP_Multiply                            88   /* same as TK_STAR     */
8609#define OP_Divide                              89   /* same as TK_SLASH    */
8610#define OP_Remainder                           90   /* same as TK_REM      */
8611#define OP_CollSeq                             17
8612#define OP_Function                            18
8613#define OP_BitAnd                              82   /* same as TK_BITAND   */
8614#define OP_BitOr                               83   /* same as TK_BITOR    */
8615#define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8616#define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8617#define OP_AddImm                              20
8618#define OP_MustBeInt                           21
8619#define OP_RealAffinity                        22
8620#define OP_ToText                             141   /* same as TK_TO_TEXT  */
8621#define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8622#define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8623#define OP_ToInt                              144   /* same as TK_TO_INT   */
8624#define OP_ToReal                             145   /* same as TK_TO_REAL  */
8625#define OP_Eq                                  76   /* same as TK_EQ       */
8626#define OP_Ne                                  75   /* same as TK_NE       */
8627#define OP_Lt                                  79   /* same as TK_LT       */
8628#define OP_Le                                  78   /* same as TK_LE       */
8629#define OP_Gt                                  77   /* same as TK_GT       */
8630#define OP_Ge                                  80   /* same as TK_GE       */
8631#define OP_Permutation                         23
8632#define OP_Compare                             24
8633#define OP_Jump                                25
8634#define OP_And                                 69   /* same as TK_AND      */
8635#define OP_Or                                  68   /* same as TK_OR       */
8636#define OP_Not                                 19   /* same as TK_NOT      */
8637#define OP_BitNot                              93   /* same as TK_BITNOT   */
8638#define OP_Once                                26
8639#define OP_If                                  27
8640#define OP_IfNot                               28
8641#define OP_IsNull                              73   /* same as TK_ISNULL   */
8642#define OP_NotNull                             74   /* same as TK_NOTNULL  */
8643#define OP_Column                              29
8644#define OP_Affinity                            30
8645#define OP_MakeRecord                          31
8646#define OP_Count                               32
8647#define OP_Savepoint                           33
8648#define OP_AutoCommit                          34
8649#define OP_Transaction                         35
8650#define OP_ReadCookie                          36
8651#define OP_SetCookie                           37
8652#define OP_VerifyCookie                        38
8653#define OP_OpenRead                            39
8654#define OP_OpenWrite                           40
8655#define OP_OpenAutoindex                       41
8656#define OP_OpenEphemeral                       42
8657#define OP_SorterOpen                          43
8658#define OP_OpenPseudo                          44
8659#define OP_Close                               45
8660#define OP_SeekLt                              46
8661#define OP_SeekLe                              47
8662#define OP_SeekGe                              48
8663#define OP_SeekGt                              49
8664#define OP_Seek                                50
8665#define OP_NotFound                            51
8666#define OP_Found                               52
8667#define OP_IsUnique                            53
8668#define OP_NotExists                           54
8669#define OP_Sequence                            55
8670#define OP_NewRowid                            56
8671#define OP_Insert                              57
8672#define OP_InsertInt                           58
8673#define OP_Delete                              59
8674#define OP_ResetCount                          60
8675#define OP_SorterCompare                       61
8676#define OP_SorterData                          62
8677#define OP_RowKey                              63
8678#define OP_RowData                             64
8679#define OP_Rowid                               65
8680#define OP_NullRow                             66
8681#define OP_Last                                67
8682#define OP_SorterSort                          70
8683#define OP_Sort                                71
8684#define OP_Rewind                              72
8685#define OP_SorterNext                          81
8686#define OP_Prev                                92
8687#define OP_Next                                95
8688#define OP_SorterInsert                        96
8689#define OP_IdxInsert                           97
8690#define OP_IdxDelete                           98
8691#define OP_IdxRowid                            99
8692#define OP_IdxLT                              100
8693#define OP_IdxGE                              101
8694#define OP_Destroy                            102
8695#define OP_Clear                              103
8696#define OP_CreateIndex                        104
8697#define OP_CreateTable                        105
8698#define OP_ParseSchema                        106
8699#define OP_LoadAnalysis                       107
8700#define OP_DropTable                          108
8701#define OP_DropIndex                          109
8702#define OP_DropTrigger                        110
8703#define OP_IntegrityCk                        111
8704#define OP_RowSetAdd                          112
8705#define OP_RowSetRead                         113
8706#define OP_RowSetTest                         114
8707#define OP_Program                            115
8708#define OP_Param                              116
8709#define OP_FkCounter                          117
8710#define OP_FkIfZero                           118
8711#define OP_MemMax                             119
8712#define OP_IfPos                              120
8713#define OP_IfNeg                              121
8714#define OP_IfZero                             122
8715#define OP_AggStep                            123
8716#define OP_AggFinal                           124
8717#define OP_Checkpoint                         125
8718#define OP_JournalMode                        126
8719#define OP_Vacuum                             127
8720#define OP_IncrVacuum                         128
8721#define OP_Expire                             129
8722#define OP_TableLock                          131
8723#define OP_VBegin                             132
8724#define OP_VCreate                            133
8725#define OP_VDestroy                           134
8726#define OP_VOpen                              135
8727#define OP_VFilter                            136
8728#define OP_VColumn                            137
8729#define OP_VNext                              138
8730#define OP_VRename                            139
8731#define OP_VUpdate                            140
8732#define OP_Pagecount                          146
8733#define OP_MaxPgcnt                           147
8734#define OP_Trace                              148
8735#define OP_Noop                               149
8736#define OP_Explain                            150
8737
8738
8739/* Properties such as "out2" or "jump" that are specified in
8740** comments following the "case" for each opcode in the vdbe.c
8741** are encoded into bitvectors as follows:
8742*/
8743#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8744#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8745#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8746#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8747#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8748#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8749#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8750#define OPFLG_INITIALIZER {\
8751/*   0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
8752/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8753/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8754/*  24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
8755/*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
8756/*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
8757/*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
8758/*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8759/*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
8760/*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8761/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8762/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
8763/*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8764/* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8765/* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
8766/* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
8767/* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8768/* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
8769/* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
8770
8771/************** End of opcodes.h *********************************************/
8772/************** Continuing where we left off in vdbe.h ***********************/
8773
8774/*
8775** Prototypes for the VDBE interface.  See comments on the implementation
8776** for a description of what each of these routines does.
8777*/
8778SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8779SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8780SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8781SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8782SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8783SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8784SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8785SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8786SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
8787SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
8788SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
8789SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
8790SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8791SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8792SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
8793SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8794SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8795SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8796SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8797SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8798SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8799SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8800SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
8801SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8802SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8803SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8804#ifdef SQLITE_DEBUG
8805SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8806SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8807#endif
8808SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8809SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
8810SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8811SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8812SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8813SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8814SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8815SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8816SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8817SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8818SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8819SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8820#ifndef SQLITE_OMIT_TRACE
8821SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8822#endif
8823
8824SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
8825SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8826SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
8827
8828#ifndef SQLITE_OMIT_TRIGGER
8829SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8830#endif
8831
8832
8833#ifndef NDEBUG
8834SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8835# define VdbeComment(X)  sqlite3VdbeComment X
8836SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8837# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8838#else
8839# define VdbeComment(X)
8840# define VdbeNoopComment(X)
8841#endif
8842
8843#endif
8844
8845/************** End of vdbe.h ************************************************/
8846/************** Continuing where we left off in sqliteInt.h ******************/
8847/************** Include pager.h in the middle of sqliteInt.h *****************/
8848/************** Begin file pager.h *******************************************/
8849/*
8850** 2001 September 15
8851**
8852** The author disclaims copyright to this source code.  In place of
8853** a legal notice, here is a blessing:
8854**
8855**    May you do good and not evil.
8856**    May you find forgiveness for yourself and forgive others.
8857**    May you share freely, never taking more than you give.
8858**
8859*************************************************************************
8860** This header file defines the interface that the sqlite page cache
8861** subsystem.  The page cache subsystem reads and writes a file a page
8862** at a time and provides a journal for rollback.
8863*/
8864
8865#ifndef _PAGER_H_
8866#define _PAGER_H_
8867
8868/*
8869** Default maximum size for persistent journal files. A negative
8870** value means no limit. This value may be overridden using the
8871** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8872*/
8873#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8874  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8875#endif
8876
8877/*
8878** The type used to represent a page number.  The first page in a file
8879** is called page 1.  0 is used to represent "not a page".
8880*/
8881typedef u32 Pgno;
8882
8883/*
8884** Each open file is managed by a separate instance of the "Pager" structure.
8885*/
8886typedef struct Pager Pager;
8887
8888/*
8889** Handle type for pages.
8890*/
8891typedef struct PgHdr DbPage;
8892
8893/*
8894** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8895** reserved for working around a windows/posix incompatibility). It is
8896** used in the journal to signify that the remainder of the journal file
8897** is devoted to storing a master journal name - there are no more pages to
8898** roll back. See comments for function writeMasterJournal() in pager.c
8899** for details.
8900*/
8901#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8902
8903/*
8904** Allowed values for the flags parameter to sqlite3PagerOpen().
8905**
8906** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8907*/
8908#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8909#define PAGER_MEMORY        0x0002    /* In-memory database */
8910
8911/*
8912** Valid values for the second argument to sqlite3PagerLockingMode().
8913*/
8914#define PAGER_LOCKINGMODE_QUERY      -1
8915#define PAGER_LOCKINGMODE_NORMAL      0
8916#define PAGER_LOCKINGMODE_EXCLUSIVE   1
8917
8918/*
8919** Numeric constants that encode the journalmode.
8920*/
8921#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8922#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8923#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8924#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8925#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8926#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8927#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8928
8929/*
8930** The remainder of this file contains the declarations of the functions
8931** that make up the Pager sub-system API. See source code comments for
8932** a detailed description of each routine.
8933*/
8934
8935/* Open and close a Pager connection. */
8936SQLITE_PRIVATE int sqlite3PagerOpen(
8937  sqlite3_vfs*,
8938  Pager **ppPager,
8939  const char*,
8940  int,
8941  int,
8942  int,
8943  void(*)(DbPage*)
8944);
8945SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8946SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8947
8948/* Functions used to configure a Pager object. */
8949SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8950SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8951SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8952SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8953SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
8954SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8955SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8956SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8957SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8958SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8959SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8960SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8961
8962/* Functions used to obtain and release page references. */
8963SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8964#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8965SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8966SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8967SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8968
8969/* Operations on page references. */
8970SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8971SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8972SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8973SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8974SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
8975SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
8976
8977/* Functions used to manage pager transactions and savepoints. */
8978SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8979SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8980SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8981SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8982SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8983SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8984SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8985SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8986SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8987SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8988
8989SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
8990SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8991SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8992SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8993SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8994#ifdef SQLITE_ENABLE_ZIPVFS
8995SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
8996#endif
8997
8998/* Functions used to query pager state and configuration. */
8999SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9000SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9001SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9002SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
9003SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9004SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9005SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9006SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9007SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9008SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9009SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9010SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9011
9012/* Functions used to truncate the database file. */
9013SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9014
9015#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9016SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9017#endif
9018
9019/* Functions to support testing and debugging. */
9020#if !defined(NDEBUG) || defined(SQLITE_TEST)
9021SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
9022SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
9023#endif
9024#ifdef SQLITE_TEST
9025SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
9026SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
9027  void disable_simulated_io_errors(void);
9028  void enable_simulated_io_errors(void);
9029#else
9030# define disable_simulated_io_errors()
9031# define enable_simulated_io_errors()
9032#endif
9033
9034#endif /* _PAGER_H_ */
9035
9036/************** End of pager.h ***********************************************/
9037/************** Continuing where we left off in sqliteInt.h ******************/
9038/************** Include pcache.h in the middle of sqliteInt.h ****************/
9039/************** Begin file pcache.h ******************************************/
9040/*
9041** 2008 August 05
9042**
9043** The author disclaims copyright to this source code.  In place of
9044** a legal notice, here is a blessing:
9045**
9046**    May you do good and not evil.
9047**    May you find forgiveness for yourself and forgive others.
9048**    May you share freely, never taking more than you give.
9049**
9050*************************************************************************
9051** This header file defines the interface that the sqlite page cache
9052** subsystem.
9053*/
9054
9055#ifndef _PCACHE_H_
9056
9057typedef struct PgHdr PgHdr;
9058typedef struct PCache PCache;
9059
9060/*
9061** Every page in the cache is controlled by an instance of the following
9062** structure.
9063*/
9064struct PgHdr {
9065  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
9066  void *pData;                   /* Page data */
9067  void *pExtra;                  /* Extra content */
9068  PgHdr *pDirty;                 /* Transient list of dirty pages */
9069  Pager *pPager;                 /* The pager this page is part of */
9070  Pgno pgno;                     /* Page number for this page */
9071#ifdef SQLITE_CHECK_PAGES
9072  u32 pageHash;                  /* Hash of page content */
9073#endif
9074  u16 flags;                     /* PGHDR flags defined below */
9075
9076  /**********************************************************************
9077  ** Elements above are public.  All that follows is private to pcache.c
9078  ** and should not be accessed by other modules.
9079  */
9080  i16 nRef;                      /* Number of users of this page */
9081  PCache *pCache;                /* Cache that owns this page */
9082
9083  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
9084  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
9085};
9086
9087/* Bit values for PgHdr.flags */
9088#define PGHDR_DIRTY             0x002  /* Page has changed */
9089#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
9090                                       ** writing this page to the database */
9091#define PGHDR_NEED_READ         0x008  /* Content is unread */
9092#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
9093#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
9094
9095/* Initialize and shutdown the page cache subsystem */
9096SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9097SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9098
9099/* Page cache buffer management:
9100** These routines implement SQLITE_CONFIG_PAGECACHE.
9101*/
9102SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9103
9104/* Create a new pager cache.
9105** Under memory stress, invoke xStress to try to make pages clean.
9106** Only clean and unpinned pages can be reclaimed.
9107*/
9108SQLITE_PRIVATE void sqlite3PcacheOpen(
9109  int szPage,                    /* Size of every page */
9110  int szExtra,                   /* Extra space associated with each page */
9111  int bPurgeable,                /* True if pages are on backing store */
9112  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9113  void *pStress,                 /* Argument to xStress */
9114  PCache *pToInit                /* Preallocated space for the PCache */
9115);
9116
9117/* Modify the page-size after the cache has been created. */
9118SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9119
9120/* Return the size in bytes of a PCache object.  Used to preallocate
9121** storage space.
9122*/
9123SQLITE_PRIVATE int sqlite3PcacheSize(void);
9124
9125/* One release per successful fetch.  Page is pinned until released.
9126** Reference counted.
9127*/
9128SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9129SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9130
9131SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
9132SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
9133SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
9134SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
9135
9136/* Change a page number.  Used by incr-vacuum. */
9137SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9138
9139/* Remove all pages with pgno>x.  Reset the cache if x==0 */
9140SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9141
9142/* Get a list of all dirty pages in the cache, sorted by page number */
9143SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9144
9145/* Reset and close the cache object */
9146SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9147
9148/* Clear flags from pages of the page cache */
9149SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9150
9151/* Discard the contents of the cache */
9152SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9153
9154/* Return the total number of outstanding page references */
9155SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9156
9157/* Increment the reference count of an existing page */
9158SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9159
9160SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9161
9162/* Return the total number of pages stored in the cache */
9163SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9164
9165#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9166/* Iterate through all dirty pages currently stored in the cache. This
9167** interface is only available if SQLITE_CHECK_PAGES is defined when the
9168** library is built.
9169*/
9170SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9171#endif
9172
9173/* Set and get the suggested cache-size for the specified pager-cache.
9174**
9175** If no global maximum is configured, then the system attempts to limit
9176** the total number of pages cached by purgeable pager-caches to the sum
9177** of the suggested cache-sizes.
9178*/
9179SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9180#ifdef SQLITE_TEST
9181SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9182#endif
9183
9184/* Free up as much memory as possible from the page cache */
9185SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9186
9187#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9188/* Try to return memory used by the pcache module to the main memory heap */
9189SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9190#endif
9191
9192#ifdef SQLITE_TEST
9193SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9194#endif
9195
9196SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9197
9198#endif /* _PCACHE_H_ */
9199
9200/************** End of pcache.h **********************************************/
9201/************** Continuing where we left off in sqliteInt.h ******************/
9202
9203/************** Include os.h in the middle of sqliteInt.h ********************/
9204/************** Begin file os.h **********************************************/
9205/*
9206** 2001 September 16
9207**
9208** The author disclaims copyright to this source code.  In place of
9209** a legal notice, here is a blessing:
9210**
9211**    May you do good and not evil.
9212**    May you find forgiveness for yourself and forgive others.
9213**    May you share freely, never taking more than you give.
9214**
9215******************************************************************************
9216**
9217** This header file (together with is companion C source-code file
9218** "os.c") attempt to abstract the underlying operating system so that
9219** the SQLite library will work on both POSIX and windows systems.
9220**
9221** This header file is #include-ed by sqliteInt.h and thus ends up
9222** being included by every source file.
9223*/
9224#ifndef _SQLITE_OS_H_
9225#define _SQLITE_OS_H_
9226
9227/*
9228** Figure out if we are dealing with Unix, Windows, or some other
9229** operating system.  After the following block of preprocess macros,
9230** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
9231** will defined to either 1 or 0.  One of the four will be 1.  The other
9232** three will be 0.
9233*/
9234#if defined(SQLITE_OS_OTHER)
9235# if SQLITE_OS_OTHER==1
9236#   undef SQLITE_OS_UNIX
9237#   define SQLITE_OS_UNIX 0
9238#   undef SQLITE_OS_WIN
9239#   define SQLITE_OS_WIN 0
9240#   undef SQLITE_OS_OS2
9241#   define SQLITE_OS_OS2 0
9242# else
9243#   undef SQLITE_OS_OTHER
9244# endif
9245#endif
9246#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9247# define SQLITE_OS_OTHER 0
9248# ifndef SQLITE_OS_WIN
9249#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9250#     define SQLITE_OS_WIN 1
9251#     define SQLITE_OS_UNIX 0
9252#     define SQLITE_OS_OS2 0
9253#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
9254#     define SQLITE_OS_WIN 0
9255#     define SQLITE_OS_UNIX 0
9256#     define SQLITE_OS_OS2 1
9257#   else
9258#     define SQLITE_OS_WIN 0
9259#     define SQLITE_OS_UNIX 1
9260#     define SQLITE_OS_OS2 0
9261#  endif
9262# else
9263#  define SQLITE_OS_UNIX 0
9264#  define SQLITE_OS_OS2 0
9265# endif
9266#else
9267# ifndef SQLITE_OS_WIN
9268#  define SQLITE_OS_WIN 0
9269# endif
9270#endif
9271
9272/*
9273** Define the maximum size of a temporary filename
9274*/
9275#if SQLITE_OS_WIN
9276# include <windows.h>
9277# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
9278#elif SQLITE_OS_OS2
9279# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
9280#  include <os2safe.h> /* has to be included before os2.h for linking to work */
9281# endif
9282# define INCL_DOSDATETIME
9283# define INCL_DOSFILEMGR
9284# define INCL_DOSERRORS
9285# define INCL_DOSMISC
9286# define INCL_DOSPROCESS
9287# define INCL_DOSMODULEMGR
9288# define INCL_DOSSEMAPHORES
9289# include <os2.h>
9290# include <uconv.h>
9291# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
9292#else
9293# define SQLITE_TEMPNAME_SIZE 200
9294#endif
9295
9296/*
9297** Determine if we are dealing with Windows NT.
9298**
9299** We ought to be able to determine if we are compiling for win98 or winNT
9300** using the _WIN32_WINNT macro as follows:
9301**
9302** #if defined(_WIN32_WINNT)
9303** # define SQLITE_OS_WINNT 1
9304** #else
9305** # define SQLITE_OS_WINNT 0
9306** #endif
9307**
9308** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
9309** so the above test does not work.  We'll just assume that everything is
9310** winNT unless the programmer explicitly says otherwise by setting
9311** SQLITE_OS_WINNT to 0.
9312*/
9313#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
9314# define SQLITE_OS_WINNT 1
9315#endif
9316
9317/*
9318** Determine if we are dealing with WindowsCE - which has a much
9319** reduced API.
9320*/
9321#if defined(_WIN32_WCE)
9322# define SQLITE_OS_WINCE 1
9323#else
9324# define SQLITE_OS_WINCE 0
9325#endif
9326
9327/* If the SET_FULLSYNC macro is not defined above, then make it
9328** a no-op
9329*/
9330#ifndef SET_FULLSYNC
9331# define SET_FULLSYNC(x,y)
9332#endif
9333
9334/*
9335** The default size of a disk sector
9336*/
9337#ifndef SQLITE_DEFAULT_SECTOR_SIZE
9338# define SQLITE_DEFAULT_SECTOR_SIZE 4096
9339#endif
9340
9341/*
9342** Temporary files are named starting with this prefix followed by 16 random
9343** alphanumeric characters, and no file extension. They are stored in the
9344** OS's standard temporary file directory, and are deleted prior to exit.
9345** If sqlite is being embedded in another program, you may wish to change the
9346** prefix to reflect your program's name, so that if your program exits
9347** prematurely, old temporary files can be easily identified. This can be done
9348** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9349**
9350** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9351** Mcafee started using SQLite in their anti-virus product and it
9352** started putting files with the "sqlite" name in the c:/temp folder.
9353** This annoyed many windows users.  Those users would then do a
9354** Google search for "sqlite", find the telephone numbers of the
9355** developers and call to wake them up at night and complain.
9356** For this reason, the default name prefix is changed to be "sqlite"
9357** spelled backwards.  So the temp files are still identified, but
9358** anybody smart enough to figure out the code is also likely smart
9359** enough to know that calling the developer will not help get rid
9360** of the file.
9361*/
9362#ifndef SQLITE_TEMP_FILE_PREFIX
9363# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9364#endif
9365
9366/*
9367** The following values may be passed as the second argument to
9368** sqlite3OsLock(). The various locks exhibit the following semantics:
9369**
9370** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9371** RESERVED:  A single process may hold a RESERVED lock on a file at
9372**            any time. Other processes may hold and obtain new SHARED locks.
9373** PENDING:   A single process may hold a PENDING lock on a file at
9374**            any one time. Existing SHARED locks may persist, but no new
9375**            SHARED locks may be obtained by other processes.
9376** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9377**
9378** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9379** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9380** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9381** sqlite3OsLock().
9382*/
9383#define NO_LOCK         0
9384#define SHARED_LOCK     1
9385#define RESERVED_LOCK   2
9386#define PENDING_LOCK    3
9387#define EXCLUSIVE_LOCK  4
9388
9389/*
9390** File Locking Notes:  (Mostly about windows but also some info for Unix)
9391**
9392** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9393** those functions are not available.  So we use only LockFile() and
9394** UnlockFile().
9395**
9396** LockFile() prevents not just writing but also reading by other processes.
9397** A SHARED_LOCK is obtained by locking a single randomly-chosen
9398** byte out of a specific range of bytes. The lock byte is obtained at
9399** random so two separate readers can probably access the file at the
9400** same time, unless they are unlucky and choose the same lock byte.
9401** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9402** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9403** a single byte of the file that is designated as the reserved lock byte.
9404** A PENDING_LOCK is obtained by locking a designated byte different from
9405** the RESERVED_LOCK byte.
9406**
9407** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9408** which means we can use reader/writer locks.  When reader/writer locks
9409** are used, the lock is placed on the same range of bytes that is used
9410** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9411** will support two or more Win95 readers or two or more WinNT readers.
9412** But a single Win95 reader will lock out all WinNT readers and a single
9413** WinNT reader will lock out all other Win95 readers.
9414**
9415** The following #defines specify the range of bytes used for locking.
9416** SHARED_SIZE is the number of bytes available in the pool from which
9417** a random byte is selected for a shared lock.  The pool of bytes for
9418** shared locks begins at SHARED_FIRST.
9419**
9420** The same locking strategy and
9421** byte ranges are used for Unix.  This leaves open the possiblity of having
9422** clients on win95, winNT, and unix all talking to the same shared file
9423** and all locking correctly.  To do so would require that samba (or whatever
9424** tool is being used for file sharing) implements locks correctly between
9425** windows and unix.  I'm guessing that isn't likely to happen, but by
9426** using the same locking range we are at least open to the possibility.
9427**
9428** Locking in windows is manditory.  For this reason, we cannot store
9429** actual data in the bytes used for locking.  The pager never allocates
9430** the pages involved in locking therefore.  SHARED_SIZE is selected so
9431** that all locks will fit on a single page even at the minimum page size.
9432** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9433** is set high so that we don't have to allocate an unused page except
9434** for very large databases.  But one should test the page skipping logic
9435** by setting PENDING_BYTE low and running the entire regression suite.
9436**
9437** Changing the value of PENDING_BYTE results in a subtly incompatible
9438** file format.  Depending on how it is changed, you might not notice
9439** the incompatibility right away, even running a full regression test.
9440** The default location of PENDING_BYTE is the first byte past the
9441** 1GB boundary.
9442**
9443*/
9444#ifdef SQLITE_OMIT_WSD
9445# define PENDING_BYTE     (0x40000000)
9446#else
9447# define PENDING_BYTE      sqlite3PendingByte
9448#endif
9449#define RESERVED_BYTE     (PENDING_BYTE+1)
9450#define SHARED_FIRST      (PENDING_BYTE+2)
9451#define SHARED_SIZE       510
9452
9453/*
9454** Wrapper around OS specific sqlite3_os_init() function.
9455*/
9456SQLITE_PRIVATE int sqlite3OsInit(void);
9457
9458/*
9459** Functions for accessing sqlite3_file methods
9460*/
9461SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9462SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9463SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9464SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9465SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9466SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9467SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9468SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9469SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9470SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9471SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
9472#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9473SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9474SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9475SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9476SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9477SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9478SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9479
9480
9481/*
9482** Functions for accessing sqlite3_vfs methods
9483*/
9484SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9485SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9486SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9487SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9488#ifndef SQLITE_OMIT_LOAD_EXTENSION
9489SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9490SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9491SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9492SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9493#endif /* SQLITE_OMIT_LOAD_EXTENSION */
9494SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9495SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9496SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9497
9498/*
9499** Convenience functions for opening and closing files using
9500** sqlite3_malloc() to obtain space for the file-handle structure.
9501*/
9502SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9503SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9504
9505#endif /* _SQLITE_OS_H_ */
9506
9507/************** End of os.h **************************************************/
9508/************** Continuing where we left off in sqliteInt.h ******************/
9509/************** Include mutex.h in the middle of sqliteInt.h *****************/
9510/************** Begin file mutex.h *******************************************/
9511/*
9512** 2007 August 28
9513**
9514** The author disclaims copyright to this source code.  In place of
9515** a legal notice, here is a blessing:
9516**
9517**    May you do good and not evil.
9518**    May you find forgiveness for yourself and forgive others.
9519**    May you share freely, never taking more than you give.
9520**
9521*************************************************************************
9522**
9523** This file contains the common header for all mutex implementations.
9524** The sqliteInt.h header #includes this file so that it is available
9525** to all source files.  We break it out in an effort to keep the code
9526** better organized.
9527**
9528** NOTE:  source files should *not* #include this header file directly.
9529** Source files should #include the sqliteInt.h file and let that file
9530** include this one indirectly.
9531*/
9532
9533
9534/*
9535** Figure out what version of the code to use.  The choices are
9536**
9537**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9538**                             mutexes implemention cannot be overridden
9539**                             at start-time.
9540**
9541**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9542**                             mutual exclusion is provided.  But this
9543**                             implementation can be overridden at
9544**                             start-time.
9545**
9546**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9547**
9548**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9549**
9550**   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
9551*/
9552#if !SQLITE_THREADSAFE
9553# define SQLITE_MUTEX_OMIT
9554#endif
9555#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9556#  if SQLITE_OS_UNIX
9557#    define SQLITE_MUTEX_PTHREADS
9558#  elif SQLITE_OS_WIN
9559#    define SQLITE_MUTEX_W32
9560#  elif SQLITE_OS_OS2
9561#    define SQLITE_MUTEX_OS2
9562#  else
9563#    define SQLITE_MUTEX_NOOP
9564#  endif
9565#endif
9566
9567#ifdef SQLITE_MUTEX_OMIT
9568/*
9569** If this is a no-op implementation, implement everything as macros.
9570*/
9571#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9572#define sqlite3_mutex_free(X)
9573#define sqlite3_mutex_enter(X)
9574#define sqlite3_mutex_try(X)      SQLITE_OK
9575#define sqlite3_mutex_leave(X)
9576#define sqlite3_mutex_held(X)     ((void)(X),1)
9577#define sqlite3_mutex_notheld(X)  ((void)(X),1)
9578#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9579#define sqlite3MutexInit()        SQLITE_OK
9580#define sqlite3MutexEnd()
9581#define MUTEX_LOGIC(X)
9582#else
9583#define MUTEX_LOGIC(X)            X
9584#endif /* defined(SQLITE_MUTEX_OMIT) */
9585
9586/************** End of mutex.h ***********************************************/
9587/************** Continuing where we left off in sqliteInt.h ******************/
9588
9589
9590/*
9591** Each database file to be accessed by the system is an instance
9592** of the following structure.  There are normally two of these structures
9593** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9594** aDb[1] is the database file used to hold temporary tables.  Additional
9595** databases may be attached.
9596*/
9597struct Db {
9598  char *zName;         /* Name of this database */
9599  Btree *pBt;          /* The B*Tree structure for this database file */
9600  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9601  u8 safety_level;     /* How aggressive at syncing data to disk */
9602  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9603};
9604
9605/*
9606** An instance of the following structure stores a database schema.
9607**
9608** Most Schema objects are associated with a Btree.  The exception is
9609** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9610** In shared cache mode, a single Schema object can be shared by multiple
9611** Btrees that refer to the same underlying BtShared object.
9612**
9613** Schema objects are automatically deallocated when the last Btree that
9614** references them is destroyed.   The TEMP Schema is manually freed by
9615** sqlite3_close().
9616*
9617** A thread must be holding a mutex on the corresponding Btree in order
9618** to access Schema content.  This implies that the thread must also be
9619** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9620** For a TEMP Schema, only the connection mutex is required.
9621*/
9622struct Schema {
9623  int schema_cookie;   /* Database schema version number for this file */
9624  int iGeneration;     /* Generation counter.  Incremented with each change */
9625  Hash tblHash;        /* All tables indexed by name */
9626  Hash idxHash;        /* All (named) indices indexed by name */
9627  Hash trigHash;       /* All triggers indexed by name */
9628  Hash fkeyHash;       /* All foreign keys by referenced table name */
9629  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9630  u8 file_format;      /* Schema format version for this file */
9631  u8 enc;              /* Text encoding used by this database */
9632  u16 flags;           /* Flags associated with this schema */
9633  int cache_size;      /* Number of pages to use in the cache */
9634};
9635
9636/*
9637** These macros can be used to test, set, or clear bits in the
9638** Db.pSchema->flags field.
9639*/
9640#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9641#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9642#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9643#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9644
9645/*
9646** Allowed values for the DB.pSchema->flags field.
9647**
9648** The DB_SchemaLoaded flag is set after the database schema has been
9649** read into internal hash tables.
9650**
9651** DB_UnresetViews means that one or more views have column names that
9652** have been filled out.  If the schema changes, these column names might
9653** changes and so the view will need to be reset.
9654*/
9655#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9656#define DB_UnresetViews    0x0002  /* Some views have defined column names */
9657#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9658
9659/*
9660** The number of different kinds of things that can be limited
9661** using the sqlite3_limit() interface.
9662*/
9663#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9664
9665/*
9666** Lookaside malloc is a set of fixed-size buffers that can be used
9667** to satisfy small transient memory allocation requests for objects
9668** associated with a particular database connection.  The use of
9669** lookaside malloc provides a significant performance enhancement
9670** (approx 10%) by avoiding numerous malloc/free requests while parsing
9671** SQL statements.
9672**
9673** The Lookaside structure holds configuration information about the
9674** lookaside malloc subsystem.  Each available memory allocation in
9675** the lookaside subsystem is stored on a linked list of LookasideSlot
9676** objects.
9677**
9678** Lookaside allocations are only allowed for objects that are associated
9679** with a particular database connection.  Hence, schema information cannot
9680** be stored in lookaside because in shared cache mode the schema information
9681** is shared by multiple database connections.  Therefore, while parsing
9682** schema information, the Lookaside.bEnabled flag is cleared so that
9683** lookaside allocations are not used to construct the schema objects.
9684*/
9685struct Lookaside {
9686  u16 sz;                 /* Size of each buffer in bytes */
9687  u8 bEnabled;            /* False to disable new lookaside allocations */
9688  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9689  int nOut;               /* Number of buffers currently checked out */
9690  int mxOut;              /* Highwater mark for nOut */
9691  int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9692  LookasideSlot *pFree;   /* List of available buffers */
9693  void *pStart;           /* First byte of available memory space */
9694  void *pEnd;             /* First byte past end of available space */
9695};
9696struct LookasideSlot {
9697  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9698};
9699
9700/*
9701** A hash table for function definitions.
9702**
9703** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9704** Collisions are on the FuncDef.pHash chain.
9705*/
9706struct FuncDefHash {
9707  FuncDef *a[23];       /* Hash table for functions */
9708};
9709
9710/*
9711** Each database connection is an instance of the following structure.
9712*/
9713struct sqlite3 {
9714  sqlite3_vfs *pVfs;            /* OS Interface */
9715  struct Vdbe *pVdbe;           /* List of active virtual machines */
9716  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9717  sqlite3_mutex *mutex;         /* Connection mutex */
9718  Db *aDb;                      /* All backends */
9719  int nDb;                      /* Number of backends currently in use */
9720  int flags;                    /* Miscellaneous flags. See below */
9721  i64 lastRowid;                /* ROWID of most recent insert (see above) */
9722  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
9723  int errCode;                  /* Most recent error code (SQLITE_*) */
9724  int errMask;                  /* & result codes with this before returning */
9725  u8 autoCommit;                /* The auto-commit flag. */
9726  u8 temp_store;                /* 1: file 2: memory 0: default */
9727  u8 mallocFailed;              /* True if we have seen a malloc failure */
9728  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9729  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9730  u8 suppressErr;               /* Do not issue error messages if true */
9731  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
9732  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9733  int nextPagesize;             /* Pagesize after VACUUM if >0 */
9734  u32 magic;                    /* Magic number for detect library misuse */
9735  int nChange;                  /* Value returned by sqlite3_changes() */
9736  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9737  int aLimit[SQLITE_N_LIMIT];   /* Limits */
9738  struct sqlite3InitInfo {      /* Information used during initialization */
9739    int newTnum;                /* Rootpage of table being initialized */
9740    u8 iDb;                     /* Which db file is being initialized */
9741    u8 busy;                    /* TRUE if currently initializing */
9742    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9743  } init;
9744  int activeVdbeCnt;            /* Number of VDBEs currently executing */
9745  int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9746  int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9747  int nExtension;               /* Number of loaded extensions */
9748  void **aExtension;            /* Array of shared library handles */
9749  void (*xTrace)(void*,const char*);        /* Trace function */
9750  void *pTraceArg;                          /* Argument to the trace function */
9751  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9752  void *pProfileArg;                        /* Argument to profile function */
9753  void *pCommitArg;                 /* Argument to xCommitCallback() */
9754  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9755  void *pRollbackArg;               /* Argument to xRollbackCallback() */
9756  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9757  void *pUpdateArg;
9758  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9759#ifndef SQLITE_OMIT_WAL
9760  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9761  void *pWalArg;
9762#endif
9763  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9764  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9765  void *pCollNeededArg;
9766  sqlite3_value *pErr;          /* Most recent error message */
9767  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9768  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9769  union {
9770    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9771    double notUsed1;            /* Spacer */
9772  } u1;
9773  Lookaside lookaside;          /* Lookaside malloc configuration */
9774#ifndef SQLITE_OMIT_AUTHORIZATION
9775  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9776                                /* Access authorization function */
9777  void *pAuthArg;               /* 1st argument to the access auth function */
9778#endif
9779#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9780  int (*xProgress)(void *);     /* The progress callback */
9781  void *pProgressArg;           /* Argument to the progress callback */
9782  int nProgressOps;             /* Number of opcodes for progress callback */
9783#endif
9784#ifndef SQLITE_OMIT_VIRTUALTABLE
9785  int nVTrans;                  /* Allocated size of aVTrans */
9786  Hash aModule;                 /* populated by sqlite3_create_module() */
9787  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
9788  VTable **aVTrans;             /* Virtual tables with open transactions */
9789  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9790#endif
9791  FuncDefHash aFunc;            /* Hash table of connection functions */
9792  Hash aCollSeq;                /* All collating sequences */
9793  BusyHandler busyHandler;      /* Busy callback */
9794  Db aDbStatic[2];              /* Static space for the 2 default backends */
9795  Savepoint *pSavepoint;        /* List of active savepoints */
9796  int busyTimeout;              /* Busy handler timeout, in msec */
9797  int nSavepoint;               /* Number of non-transaction savepoints */
9798  int nStatement;               /* Number of nested statement-transactions  */
9799  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9800  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9801
9802#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9803  /* The following variables are all protected by the STATIC_MASTER
9804  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
9805  **
9806  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9807  ** unlock so that it can proceed.
9808  **
9809  ** When X.pBlockingConnection==Y, that means that something that X tried
9810  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9811  ** held by Y.
9812  */
9813  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9814  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9815  void *pUnlockArg;                     /* Argument to xUnlockNotify */
9816  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9817  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9818#endif
9819};
9820
9821/*
9822** A macro to discover the encoding of a database.
9823*/
9824#define ENC(db) ((db)->aDb[0].pSchema->enc)
9825
9826/*
9827** Possible values for the sqlite3.flags.
9828*/
9829#define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9830#define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9831#define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
9832#define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
9833#define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
9834                                          /*   DELETE, or UPDATE and return */
9835                                          /*   the count using a callback. */
9836#define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
9837                                          /*   result set is empty */
9838#define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9839#define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9840#define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
9841                         /*   0x00020000  Unused */
9842#define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9843#define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
9844#define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9845#define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
9846#define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9847#define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
9848#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9849#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
9850#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9851#define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
9852#define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9853#define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
9854#define SQLITE_EnableTrigger  0x40000000  /* True to enable triggers */
9855
9856/*
9857** Bits of the sqlite3.flags field that are used by the
9858** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9859** These must be the low-order bits of the flags field.
9860*/
9861#define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
9862#define SQLITE_ColumnCache    0x02        /* Disable the column cache */
9863#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
9864#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
9865#define SQLITE_IndexCover     0x10        /* Disable index covering table */
9866#define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9867#define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
9868#define SQLITE_IdxRealAsInt   0x80        /* Store REAL as INT in indices */
9869#define SQLITE_DistinctOpt    0x80        /* DISTINCT using indexes */
9870#define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9871
9872/*
9873** Possible values for the sqlite.magic field.
9874** The numbers are obtained at random and have no special meaning, other
9875** than being distinct from one another.
9876*/
9877#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9878#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9879#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9880#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9881#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9882
9883/*
9884** Each SQL function is defined by an instance of the following
9885** structure.  A pointer to this structure is stored in the sqlite.aFunc
9886** hash table.  When multiple functions have the same name, the hash table
9887** points to a linked list of these structures.
9888*/
9889struct FuncDef {
9890  i16 nArg;            /* Number of arguments.  -1 means unlimited */
9891  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9892  u8 flags;            /* Some combination of SQLITE_FUNC_* */
9893  void *pUserData;     /* User data parameter */
9894  FuncDef *pNext;      /* Next function with same name */
9895  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9896  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9897  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9898  char *zName;         /* SQL name of the function. */
9899  FuncDef *pHash;      /* Next with a different name but the same hash */
9900  FuncDestructor *pDestructor;   /* Reference counted destructor function */
9901};
9902
9903/*
9904** This structure encapsulates a user-function destructor callback (as
9905** configured using create_function_v2()) and a reference counter. When
9906** create_function_v2() is called to create a function with a destructor,
9907** a single object of this type is allocated. FuncDestructor.nRef is set to
9908** the number of FuncDef objects created (either 1 or 3, depending on whether
9909** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9910** member of each of the new FuncDef objects is set to point to the allocated
9911** FuncDestructor.
9912**
9913** Thereafter, when one of the FuncDef objects is deleted, the reference
9914** count on this object is decremented. When it reaches 0, the destructor
9915** is invoked and the FuncDestructor structure freed.
9916*/
9917struct FuncDestructor {
9918  int nRef;
9919  void (*xDestroy)(void *);
9920  void *pUserData;
9921};
9922
9923/*
9924** Possible values for FuncDef.flags
9925*/
9926#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9927#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9928#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9929#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9930#define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9931#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9932
9933/*
9934** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9935** used to create the initializers for the FuncDef structures.
9936**
9937**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9938**     Used to create a scalar function definition of a function zName
9939**     implemented by C function xFunc that accepts nArg arguments. The
9940**     value passed as iArg is cast to a (void*) and made available
9941**     as the user-data (sqlite3_user_data()) for the function. If
9942**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9943**
9944**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9945**     Used to create an aggregate function definition implemented by
9946**     the C functions xStep and xFinal. The first four parameters
9947**     are interpreted in the same way as the first 4 parameters to
9948**     FUNCTION().
9949**
9950**   LIKEFUNC(zName, nArg, pArg, flags)
9951**     Used to create a scalar function definition of a function zName
9952**     that accepts nArg arguments and is implemented by a call to C
9953**     function likeFunc. Argument pArg is cast to a (void *) and made
9954**     available as the function user-data (sqlite3_user_data()). The
9955**     FuncDef.flags variable is set to the value passed as the flags
9956**     parameter.
9957*/
9958#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9959  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9960   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9961#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9962  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9963   pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9964#define LIKEFUNC(zName, nArg, arg, flags) \
9965  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9966#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9967  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9968   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9969
9970/*
9971** All current savepoints are stored in a linked list starting at
9972** sqlite3.pSavepoint. The first element in the list is the most recently
9973** opened savepoint. Savepoints are added to the list by the vdbe
9974** OP_Savepoint instruction.
9975*/
9976struct Savepoint {
9977  char *zName;                        /* Savepoint name (nul-terminated) */
9978  i64 nDeferredCons;                  /* Number of deferred fk violations */
9979  Savepoint *pNext;                   /* Parent savepoint (if any) */
9980};
9981
9982/*
9983** The following are used as the second parameter to sqlite3Savepoint(),
9984** and as the P1 argument to the OP_Savepoint instruction.
9985*/
9986#define SAVEPOINT_BEGIN      0
9987#define SAVEPOINT_RELEASE    1
9988#define SAVEPOINT_ROLLBACK   2
9989
9990
9991/*
9992** Each SQLite module (virtual table definition) is defined by an
9993** instance of the following structure, stored in the sqlite3.aModule
9994** hash table.
9995*/
9996struct Module {
9997  const sqlite3_module *pModule;       /* Callback pointers */
9998  const char *zName;                   /* Name passed to create_module() */
9999  void *pAux;                          /* pAux passed to create_module() */
10000  void (*xDestroy)(void *);            /* Module destructor function */
10001};
10002
10003/*
10004** information about each column of an SQL table is held in an instance
10005** of this structure.
10006*/
10007struct Column {
10008  char *zName;     /* Name of this column */
10009  Expr *pDflt;     /* Default value of this column */
10010  char *zDflt;     /* Original text of the default value */
10011  char *zType;     /* Data type for this column */
10012  char *zColl;     /* Collating sequence.  If NULL, use the default */
10013  u8 notNull;      /* True if there is a NOT NULL constraint */
10014  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
10015  char affinity;   /* One of the SQLITE_AFF_... values */
10016#ifndef SQLITE_OMIT_VIRTUALTABLE
10017  u8 isHidden;     /* True if this column is 'hidden' */
10018#endif
10019};
10020
10021/*
10022** A "Collating Sequence" is defined by an instance of the following
10023** structure. Conceptually, a collating sequence consists of a name and
10024** a comparison routine that defines the order of that sequence.
10025**
10026** There may two separate implementations of the collation function, one
10027** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
10028** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
10029** native byte order. When a collation sequence is invoked, SQLite selects
10030** the version that will require the least expensive encoding
10031** translations, if any.
10032**
10033** The CollSeq.pUser member variable is an extra parameter that passed in
10034** as the first argument to the UTF-8 comparison function, xCmp.
10035** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
10036** xCmp16.
10037**
10038** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
10039** collating sequence is undefined.  Indices built on an undefined
10040** collating sequence may not be read or written.
10041*/
10042struct CollSeq {
10043  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10044  u8 enc;               /* Text encoding handled by xCmp() */
10045  void *pUser;          /* First argument to xCmp() */
10046  int (*xCmp)(void*,int, const void*, int, const void*);
10047  void (*xDel)(void*);  /* Destructor for pUser */
10048};
10049
10050/*
10051** A sort order can be either ASC or DESC.
10052*/
10053#define SQLITE_SO_ASC       0  /* Sort in ascending order */
10054#define SQLITE_SO_DESC      1  /* Sort in ascending order */
10055
10056/*
10057** Column affinity types.
10058**
10059** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10060** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10061** the speed a little by numbering the values consecutively.
10062**
10063** But rather than start with 0 or 1, we begin with 'a'.  That way,
10064** when multiple affinity types are concatenated into a string and
10065** used as the P4 operand, they will be more readable.
10066**
10067** Note also that the numeric types are grouped together so that testing
10068** for a numeric type is a single comparison.
10069*/
10070#define SQLITE_AFF_TEXT     'a'
10071#define SQLITE_AFF_NONE     'b'
10072#define SQLITE_AFF_NUMERIC  'c'
10073#define SQLITE_AFF_INTEGER  'd'
10074#define SQLITE_AFF_REAL     'e'
10075
10076#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10077
10078/*
10079** The SQLITE_AFF_MASK values masks off the significant bits of an
10080** affinity value.
10081*/
10082#define SQLITE_AFF_MASK     0x67
10083
10084/*
10085** Additional bit values that can be ORed with an affinity without
10086** changing the affinity.
10087*/
10088#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
10089#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
10090#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10091
10092/*
10093** An object of this type is created for each virtual table present in
10094** the database schema.
10095**
10096** If the database schema is shared, then there is one instance of this
10097** structure for each database connection (sqlite3*) that uses the shared
10098** schema. This is because each database connection requires its own unique
10099** instance of the sqlite3_vtab* handle used to access the virtual table
10100** implementation. sqlite3_vtab* handles can not be shared between
10101** database connections, even when the rest of the in-memory database
10102** schema is shared, as the implementation often stores the database
10103** connection handle passed to it via the xConnect() or xCreate() method
10104** during initialization internally. This database connection handle may
10105** then be used by the virtual table implementation to access real tables
10106** within the database. So that they appear as part of the callers
10107** transaction, these accesses need to be made via the same database
10108** connection as that used to execute SQL operations on the virtual table.
10109**
10110** All VTable objects that correspond to a single table in a shared
10111** database schema are initially stored in a linked-list pointed to by
10112** the Table.pVTable member variable of the corresponding Table object.
10113** When an sqlite3_prepare() operation is required to access the virtual
10114** table, it searches the list for the VTable that corresponds to the
10115** database connection doing the preparing so as to use the correct
10116** sqlite3_vtab* handle in the compiled query.
10117**
10118** When an in-memory Table object is deleted (for example when the
10119** schema is being reloaded for some reason), the VTable objects are not
10120** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
10121** immediately. Instead, they are moved from the Table.pVTable list to
10122** another linked list headed by the sqlite3.pDisconnect member of the
10123** corresponding sqlite3 structure. They are then deleted/xDisconnected
10124** next time a statement is prepared using said sqlite3*. This is done
10125** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10126** Refer to comments above function sqlite3VtabUnlockList() for an
10127** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10128** list without holding the corresponding sqlite3.mutex mutex.
10129**
10130** The memory for objects of this type is always allocated by
10131** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
10132** the first argument.
10133*/
10134struct VTable {
10135  sqlite3 *db;              /* Database connection associated with this table */
10136  Module *pMod;             /* Pointer to module implementation */
10137  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
10138  int nRef;                 /* Number of pointers to this structure */
10139  u8 bConstraint;           /* True if constraints are supported */
10140  int iSavepoint;           /* Depth of the SAVEPOINT stack */
10141  VTable *pNext;            /* Next in linked list (see above) */
10142};
10143
10144/*
10145** Each SQL table is represented in memory by an instance of the
10146** following structure.
10147**
10148** Table.zName is the name of the table.  The case of the original
10149** CREATE TABLE statement is stored, but case is not significant for
10150** comparisons.
10151**
10152** Table.nCol is the number of columns in this table.  Table.aCol is a
10153** pointer to an array of Column structures, one for each column.
10154**
10155** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10156** the column that is that key.   Otherwise Table.iPKey is negative.  Note
10157** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10158** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
10159** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
10160** is generated for each row of the table.  TF_HasPrimaryKey is set if
10161** the table has any PRIMARY KEY, INTEGER or otherwise.
10162**
10163** Table.tnum is the page number for the root BTree page of the table in the
10164** database file.  If Table.iDb is the index of the database table backend
10165** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
10166** holds temporary tables and indices.  If TF_Ephemeral is set
10167** then the table is stored in a file that is automatically deleted
10168** when the VDBE cursor to the table is closed.  In this case Table.tnum
10169** refers VDBE cursor number that holds the table open, not to the root
10170** page number.  Transient tables are used to hold the results of a
10171** sub-query that appears instead of a real table name in the FROM clause
10172** of a SELECT statement.
10173*/
10174struct Table {
10175  char *zName;         /* Name of the table or view */
10176  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10177  int nCol;            /* Number of columns in this table */
10178  Column *aCol;        /* Information about each column */
10179  Index *pIndex;       /* List of SQL indexes on this table. */
10180  int tnum;            /* Root BTree node for this table (see note above) */
10181  tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
10182  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10183  u16 nRef;            /* Number of pointers to this Table */
10184  u8 tabFlags;         /* Mask of TF_* values */
10185  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10186  FKey *pFKey;         /* Linked list of all foreign keys in this table */
10187  char *zColAff;       /* String defining the affinity of each column */
10188#ifndef SQLITE_OMIT_CHECK
10189  Expr *pCheck;        /* The AND of all CHECK constraints */
10190#endif
10191#ifndef SQLITE_OMIT_ALTERTABLE
10192  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10193#endif
10194#ifndef SQLITE_OMIT_VIRTUALTABLE
10195  VTable *pVTable;     /* List of VTable objects. */
10196  int nModuleArg;      /* Number of arguments to the module */
10197  char **azModuleArg;  /* Text of all module args. [0] is module name */
10198#endif
10199  Trigger *pTrigger;   /* List of triggers stored in pSchema */
10200  Schema *pSchema;     /* Schema that contains this table */
10201  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10202};
10203
10204/*
10205** Allowed values for Tabe.tabFlags.
10206*/
10207#define TF_Readonly        0x01    /* Read-only system table */
10208#define TF_Ephemeral       0x02    /* An ephemeral table */
10209#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10210#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10211#define TF_Virtual         0x10    /* Is a virtual table */
10212
10213
10214/*
10215** Test to see whether or not a table is a virtual table.  This is
10216** done as a macro so that it will be optimized out when virtual
10217** table support is omitted from the build.
10218*/
10219#ifndef SQLITE_OMIT_VIRTUALTABLE
10220#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10221#  define IsHiddenColumn(X) ((X)->isHidden)
10222#else
10223#  define IsVirtual(X)      0
10224#  define IsHiddenColumn(X) 0
10225#endif
10226
10227/*
10228** Each foreign key constraint is an instance of the following structure.
10229**
10230** A foreign key is associated with two tables.  The "from" table is
10231** the table that contains the REFERENCES clause that creates the foreign
10232** key.  The "to" table is the table that is named in the REFERENCES clause.
10233** Consider this example:
10234**
10235**     CREATE TABLE ex1(
10236**       a INTEGER PRIMARY KEY,
10237**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10238**     );
10239**
10240** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10241**
10242** Each REFERENCES clause generates an instance of the following structure
10243** which is attached to the from-table.  The to-table need not exist when
10244** the from-table is created.  The existence of the to-table is not checked.
10245*/
10246struct FKey {
10247  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10248  FKey *pNextFrom;  /* Next foreign key in pFrom */
10249  char *zTo;        /* Name of table that the key points to (aka: Parent) */
10250  FKey *pNextTo;    /* Next foreign key on table named zTo */
10251  FKey *pPrevTo;    /* Previous foreign key on table named zTo */
10252  int nCol;         /* Number of columns in this key */
10253  /* EV: R-30323-21917 */
10254  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10255  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10256  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10257  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10258    int iFrom;         /* Index of column in pFrom */
10259    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10260  } aCol[1];        /* One entry for each of nCol column s */
10261};
10262
10263/*
10264** SQLite supports many different ways to resolve a constraint
10265** error.  ROLLBACK processing means that a constraint violation
10266** causes the operation in process to fail and for the current transaction
10267** to be rolled back.  ABORT processing means the operation in process
10268** fails and any prior changes from that one operation are backed out,
10269** but the transaction is not rolled back.  FAIL processing means that
10270** the operation in progress stops and returns an error code.  But prior
10271** changes due to the same operation are not backed out and no rollback
10272** occurs.  IGNORE means that the particular row that caused the constraint
10273** error is not inserted or updated.  Processing continues and no error
10274** is returned.  REPLACE means that preexisting database rows that caused
10275** a UNIQUE constraint violation are removed so that the new insert or
10276** update can proceed.  Processing continues and no error is reported.
10277**
10278** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10279** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10280** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10281** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10282** referenced table row is propagated into the row that holds the
10283** foreign key.
10284**
10285** The following symbolic values are used to record which type
10286** of action to take.
10287*/
10288#define OE_None     0   /* There is no constraint to check */
10289#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10290#define OE_Abort    2   /* Back out changes but do no rollback transaction */
10291#define OE_Fail     3   /* Stop the operation but leave all prior changes */
10292#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10293#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10294
10295#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10296#define OE_SetNull  7   /* Set the foreign key value to NULL */
10297#define OE_SetDflt  8   /* Set the foreign key value to its default */
10298#define OE_Cascade  9   /* Cascade the changes */
10299
10300#define OE_Default  99  /* Do whatever the default action is */
10301
10302
10303/*
10304** An instance of the following structure is passed as the first
10305** argument to sqlite3VdbeKeyCompare and is used to control the
10306** comparison of the two index keys.
10307*/
10308struct KeyInfo {
10309  sqlite3 *db;        /* The database connection */
10310  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10311  u16 nField;         /* Number of entries in aColl[] */
10312  u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10313  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10314};
10315
10316/*
10317** An instance of the following structure holds information about a
10318** single index record that has already been parsed out into individual
10319** values.
10320**
10321** A record is an object that contains one or more fields of data.
10322** Records are used to store the content of a table row and to store
10323** the key of an index.  A blob encoding of a record is created by
10324** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10325** OP_Column opcode.
10326**
10327** This structure holds a record that has already been disassembled
10328** into its constituent fields.
10329*/
10330struct UnpackedRecord {
10331  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10332  u16 nField;         /* Number of entries in apMem[] */
10333  u8 flags;           /* Boolean settings.  UNPACKED_... below */
10334  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10335  Mem *aMem;          /* Values */
10336};
10337
10338/*
10339** Allowed values of UnpackedRecord.flags
10340*/
10341#define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
10342#define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
10343#define UNPACKED_PREFIX_SEARCH 0x04  /* Ignore final (rowid) field */
10344
10345/*
10346** Each SQL index is represented in memory by an
10347** instance of the following structure.
10348**
10349** The columns of the table that are to be indexed are described
10350** by the aiColumn[] field of this structure.  For example, suppose
10351** we have the following table and index:
10352**
10353**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10354**     CREATE INDEX Ex2 ON Ex1(c3,c1);
10355**
10356** In the Table structure describing Ex1, nCol==3 because there are
10357** three columns in the table.  In the Index structure describing
10358** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10359** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
10360** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10361** The second column to be indexed (c1) has an index of 0 in
10362** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10363**
10364** The Index.onError field determines whether or not the indexed columns
10365** must be unique and what to do if they are not.  When Index.onError=OE_None,
10366** it means this is not a unique index.  Otherwise it is a unique index
10367** and the value of Index.onError indicate the which conflict resolution
10368** algorithm to employ whenever an attempt is made to insert a non-unique
10369** element.
10370*/
10371struct Index {
10372  char *zName;     /* Name of this index */
10373  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
10374  tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
10375  Table *pTable;   /* The SQL table being indexed */
10376  char *zColAff;   /* String defining the affinity of each column */
10377  Index *pNext;    /* The next index associated with the same table */
10378  Schema *pSchema; /* Schema containing this index */
10379  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
10380  char **azColl;   /* Array of collation sequence names for index */
10381  int nColumn;     /* Number of columns in the table used by this index */
10382  int tnum;        /* Page containing root of this index in database file */
10383  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10384  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
10385  u8 bUnordered;   /* Use this index for == or IN queries only */
10386#ifdef SQLITE_ENABLE_STAT3
10387  int nSample;             /* Number of elements in aSample[] */
10388  tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
10389  IndexSample *aSample;    /* Samples of the left-most key */
10390#endif
10391};
10392
10393/*
10394** Each sample stored in the sqlite_stat3 table is represented in memory
10395** using a structure of this type.  See documentation at the top of the
10396** analyze.c source file for additional information.
10397*/
10398struct IndexSample {
10399  union {
10400    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10401    double r;       /* Value if eType is SQLITE_FLOAT */
10402    i64 i;          /* Value if eType is SQLITE_INTEGER */
10403  } u;
10404  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10405  int nByte;        /* Size in byte of text or blob. */
10406  tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
10407  tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
10408  tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
10409};
10410
10411/*
10412** Each token coming out of the lexer is an instance of
10413** this structure.  Tokens are also used as part of an expression.
10414**
10415** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10416** may contain random values.  Do not make any assumptions about Token.dyn
10417** and Token.n when Token.z==0.
10418*/
10419struct Token {
10420  const char *z;     /* Text of the token.  Not NULL-terminated! */
10421  unsigned int n;    /* Number of characters in this token */
10422};
10423
10424/*
10425** An instance of this structure contains information needed to generate
10426** code for a SELECT that contains aggregate functions.
10427**
10428** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10429** pointer to this structure.  The Expr.iColumn field is the index in
10430** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10431** code for that node.
10432**
10433** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10434** original Select structure that describes the SELECT statement.  These
10435** fields do not need to be freed when deallocating the AggInfo structure.
10436*/
10437struct AggInfo {
10438  u8 directMode;          /* Direct rendering mode means take data directly
10439                          ** from source tables rather than from accumulators */
10440  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10441                          ** than the source table */
10442  int sortingIdx;         /* Cursor number of the sorting index */
10443  int sortingIdxPTab;     /* Cursor number of pseudo-table */
10444  int nSortingColumn;     /* Number of columns in the sorting index */
10445  ExprList *pGroupBy;     /* The group by clause */
10446  struct AggInfo_col {    /* For each column used in source tables */
10447    Table *pTab;             /* Source table */
10448    int iTable;              /* Cursor number of the source table */
10449    int iColumn;             /* Column number within the source table */
10450    int iSorterColumn;       /* Column number in the sorting index */
10451    int iMem;                /* Memory location that acts as accumulator */
10452    Expr *pExpr;             /* The original expression */
10453  } *aCol;
10454  int nColumn;            /* Number of used entries in aCol[] */
10455  int nAccumulator;       /* Number of columns that show through to the output.
10456                          ** Additional columns are used only as parameters to
10457                          ** aggregate functions */
10458  struct AggInfo_func {   /* For each aggregate function */
10459    Expr *pExpr;             /* Expression encoding the function */
10460    FuncDef *pFunc;          /* The aggregate function implementation */
10461    int iMem;                /* Memory location that acts as accumulator */
10462    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10463  } *aFunc;
10464  int nFunc;              /* Number of entries in aFunc[] */
10465};
10466
10467/*
10468** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10469** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10470** than 32767 we have to make it 32-bit.  16-bit is preferred because
10471** it uses less memory in the Expr object, which is a big memory user
10472** in systems with lots of prepared statements.  And few applications
10473** need more than about 10 or 20 variables.  But some extreme users want
10474** to have prepared statements with over 32767 variables, and for them
10475** the option is available (at compile-time).
10476*/
10477#if SQLITE_MAX_VARIABLE_NUMBER<=32767
10478typedef i16 ynVar;
10479#else
10480typedef int ynVar;
10481#endif
10482
10483/*
10484** Each node of an expression in the parse tree is an instance
10485** of this structure.
10486**
10487** Expr.op is the opcode. The integer parser token codes are reused
10488** as opcodes here. For example, the parser defines TK_GE to be an integer
10489** code representing the ">=" operator. This same integer code is reused
10490** to represent the greater-than-or-equal-to operator in the expression
10491** tree.
10492**
10493** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
10494** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10495** the expression is a variable (TK_VARIABLE), then Expr.token contains the
10496** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10497** then Expr.token contains the name of the function.
10498**
10499** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10500** binary operator. Either or both may be NULL.
10501**
10502** Expr.x.pList is a list of arguments if the expression is an SQL function,
10503** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10504** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10505** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10506** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
10507** valid.
10508**
10509** An expression of the form ID or ID.ID refers to a column in a table.
10510** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10511** the integer cursor number of a VDBE cursor pointing to that table and
10512** Expr.iColumn is the column number for the specific column.  If the
10513** expression is used as a result in an aggregate SELECT, then the
10514** value is also stored in the Expr.iAgg column in the aggregate so that
10515** it can be accessed after all aggregates are computed.
10516**
10517** If the expression is an unbound variable marker (a question mark
10518** character '?' in the original SQL) then the Expr.iTable holds the index
10519** number for that variable.
10520**
10521** If the expression is a subquery then Expr.iColumn holds an integer
10522** register number containing the result of the subquery.  If the
10523** subquery gives a constant result, then iTable is -1.  If the subquery
10524** gives a different answer at different times during statement processing
10525** then iTable is the address of a subroutine that computes the subquery.
10526**
10527** If the Expr is of type OP_Column, and the table it is selecting from
10528** is a disk table or the "old.*" pseudo-table, then pTab points to the
10529** corresponding table definition.
10530**
10531** ALLOCATION NOTES:
10532**
10533** Expr objects can use a lot of memory space in database schema.  To
10534** help reduce memory requirements, sometimes an Expr object will be
10535** truncated.  And to reduce the number of memory allocations, sometimes
10536** two or more Expr objects will be stored in a single memory allocation,
10537** together with Expr.zToken strings.
10538**
10539** If the EP_Reduced and EP_TokenOnly flags are set when
10540** an Expr object is truncated.  When EP_Reduced is set, then all
10541** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10542** are contained within the same memory allocation.  Note, however, that
10543** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10544** allocated, regardless of whether or not EP_Reduced is set.
10545*/
10546struct Expr {
10547  u8 op;                 /* Operation performed by this node */
10548  char affinity;         /* The affinity of the column or 0 if not a column */
10549  u16 flags;             /* Various flags.  EP_* See below */
10550  union {
10551    char *zToken;          /* Token value. Zero terminated and dequoted */
10552    int iValue;            /* Non-negative integer value if EP_IntValue */
10553  } u;
10554
10555  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10556  ** space is allocated for the fields below this point. An attempt to
10557  ** access them will result in a segfault or malfunction.
10558  *********************************************************************/
10559
10560  Expr *pLeft;           /* Left subnode */
10561  Expr *pRight;          /* Right subnode */
10562  union {
10563    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10564    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10565  } x;
10566  CollSeq *pColl;        /* The collation type of the column or 0 */
10567
10568  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10569  ** space is allocated for the fields below this point. An attempt to
10570  ** access them will result in a segfault or malfunction.
10571  *********************************************************************/
10572
10573  int iTable;            /* TK_COLUMN: cursor number of table holding column
10574                         ** TK_REGISTER: register number
10575                         ** TK_TRIGGER: 1 -> new, 0 -> old */
10576  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10577                         ** TK_VARIABLE: variable number (always >= 1). */
10578  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10579  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10580  u8 flags2;             /* Second set of flags.  EP2_... */
10581  u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
10582  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10583  Table *pTab;           /* Table for TK_COLUMN expressions. */
10584#if SQLITE_MAX_EXPR_DEPTH>0
10585  int nHeight;           /* Height of the tree headed by this node */
10586#endif
10587};
10588
10589/*
10590** The following are the meanings of bits in the Expr.flags field.
10591*/
10592#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10593#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10594#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10595#define EP_Error      0x0008  /* Expression contains one or more errors */
10596#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10597#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10598#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10599#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10600#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10601#define EP_FixedDest  0x0200  /* Result needed in a specific register */
10602#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10603#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10604#define EP_Hint       0x1000  /* Optimizer hint. Not required for correctness */
10605#define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10606#define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10607#define EP_Static     0x8000  /* Held in memory not obtained from malloc() */
10608
10609/*
10610** The following are the meanings of bits in the Expr.flags2 field.
10611*/
10612#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10613#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10614
10615/*
10616** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10617** flag on an expression structure.  This flag is used for VV&A only.  The
10618** routine is implemented as a macro that only works when in debugging mode,
10619** so as not to burden production code.
10620*/
10621#ifdef SQLITE_DEBUG
10622# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10623#else
10624# define ExprSetIrreducible(X)
10625#endif
10626
10627/*
10628** These macros can be used to test, set, or clear bits in the
10629** Expr.flags field.
10630*/
10631#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10632#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10633#define ExprSetProperty(E,P)     (E)->flags|=(P)
10634#define ExprClearProperty(E,P)   (E)->flags&=~(P)
10635
10636/*
10637** Macros to determine the number of bytes required by a normal Expr
10638** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
10639** and an Expr struct with the EP_TokenOnly flag set.
10640*/
10641#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10642#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10643#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10644
10645/*
10646** Flags passed to the sqlite3ExprDup() function. See the header comment
10647** above sqlite3ExprDup() for details.
10648*/
10649#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10650
10651/*
10652** A list of expressions.  Each expression may optionally have a
10653** name.  An expr/name combination can be used in several ways, such
10654** as the list of "expr AS ID" fields following a "SELECT" or in the
10655** list of "ID = expr" items in an UPDATE.  A list of expressions can
10656** also be used as the argument to a function, in which case the a.zName
10657** field is not used.
10658*/
10659struct ExprList {
10660  int nExpr;             /* Number of expressions on the list */
10661  int iECursor;          /* VDBE Cursor associated with this ExprList */
10662  struct ExprList_item { /* For each expression in the list */
10663    Expr *pExpr;           /* The list of expressions */
10664    char *zName;           /* Token associated with this expression */
10665    char *zSpan;           /* Original text of the expression */
10666    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10667    u8 done;               /* A flag to indicate when processing is finished */
10668    u16 iOrderByCol;       /* For ORDER BY, column number in result set */
10669    u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10670  } *a;                  /* Alloc a power of two greater or equal to nExpr */
10671};
10672
10673/*
10674** An instance of this structure is used by the parser to record both
10675** the parse tree for an expression and the span of input text for an
10676** expression.
10677*/
10678struct ExprSpan {
10679  Expr *pExpr;          /* The expression parse tree */
10680  const char *zStart;   /* First character of input text */
10681  const char *zEnd;     /* One character past the end of input text */
10682};
10683
10684/*
10685** An instance of this structure can hold a simple list of identifiers,
10686** such as the list "a,b,c" in the following statements:
10687**
10688**      INSERT INTO t(a,b,c) VALUES ...;
10689**      CREATE INDEX idx ON t(a,b,c);
10690**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10691**
10692** The IdList.a.idx field is used when the IdList represents the list of
10693** column names after a table name in an INSERT statement.  In the statement
10694**
10695**     INSERT INTO t(a,b,c) ...
10696**
10697** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10698*/
10699struct IdList {
10700  struct IdList_item {
10701    char *zName;      /* Name of the identifier */
10702    int idx;          /* Index in some Table.aCol[] of a column named zName */
10703  } *a;
10704  int nId;         /* Number of identifiers on the list */
10705};
10706
10707/*
10708** The bitmask datatype defined below is used for various optimizations.
10709**
10710** Changing this from a 64-bit to a 32-bit type limits the number of
10711** tables in a join to 32 instead of 64.  But it also reduces the size
10712** of the library by 738 bytes on ix86.
10713*/
10714typedef u64 Bitmask;
10715
10716/*
10717** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10718*/
10719#define BMS  ((int)(sizeof(Bitmask)*8))
10720
10721/*
10722** The following structure describes the FROM clause of a SELECT statement.
10723** Each table or subquery in the FROM clause is a separate element of
10724** the SrcList.a[] array.
10725**
10726** With the addition of multiple database support, the following structure
10727** can also be used to describe a particular table such as the table that
10728** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10729** such a table must be a simple name: ID.  But in SQLite, the table can
10730** now be identified by a database name, a dot, then the table name: ID.ID.
10731**
10732** The jointype starts out showing the join type between the current table
10733** and the next table on the list.  The parser builds the list this way.
10734** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10735** jointype expresses the join between the table and the previous table.
10736**
10737** In the colUsed field, the high-order bit (bit 63) is set if the table
10738** contains more than 63 columns and the 64-th or later column is used.
10739*/
10740struct SrcList {
10741  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10742  i16 nAlloc;      /* Number of entries allocated in a[] below */
10743  struct SrcList_item {
10744    char *zDatabase;  /* Name of database holding this table */
10745    char *zName;      /* Name of the table */
10746    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10747    Table *pTab;      /* An SQL table corresponding to zName */
10748    Select *pSelect;  /* A SELECT statement used in place of a table name */
10749    int addrFillSub;  /* Address of subroutine to manifest a subquery */
10750    int regReturn;    /* Register holding return address of addrFillSub */
10751    u8 jointype;      /* Type of join between this able and the previous */
10752    u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10753    u8 isCorrelated;  /* True if sub-query is correlated */
10754#ifndef SQLITE_OMIT_EXPLAIN
10755    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10756#endif
10757    int iCursor;      /* The VDBE cursor number used to access this table */
10758    Expr *pOn;        /* The ON clause of a join */
10759    IdList *pUsing;   /* The USING clause of a join */
10760    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10761    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10762    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10763  } a[1];             /* One entry for each identifier on the list */
10764};
10765
10766/*
10767** Permitted values of the SrcList.a.jointype field
10768*/
10769#define JT_INNER     0x0001    /* Any kind of inner or cross join */
10770#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10771#define JT_NATURAL   0x0004    /* True for a "natural" join */
10772#define JT_LEFT      0x0008    /* Left outer join */
10773#define JT_RIGHT     0x0010    /* Right outer join */
10774#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10775#define JT_ERROR     0x0040    /* unknown or unsupported join type */
10776
10777
10778/*
10779** A WherePlan object holds information that describes a lookup
10780** strategy.
10781**
10782** This object is intended to be opaque outside of the where.c module.
10783** It is included here only so that that compiler will know how big it
10784** is.  None of the fields in this object should be used outside of
10785** the where.c module.
10786**
10787** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10788** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10789** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10790** case that more than one of these conditions is true.
10791*/
10792struct WherePlan {
10793  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10794  u32 nEq;                       /* Number of == constraints */
10795  double nRow;                   /* Estimated number of rows (for EQP) */
10796  union {
10797    Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10798    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10799    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10800  } u;
10801};
10802
10803/*
10804** For each nested loop in a WHERE clause implementation, the WhereInfo
10805** structure contains a single instance of this structure.  This structure
10806** is intended to be private the the where.c module and should not be
10807** access or modified by other modules.
10808**
10809** The pIdxInfo field is used to help pick the best index on a
10810** virtual table.  The pIdxInfo pointer contains indexing
10811** information for the i-th table in the FROM clause before reordering.
10812** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10813** All other information in the i-th WhereLevel object for the i-th table
10814** after FROM clause ordering.
10815*/
10816struct WhereLevel {
10817  WherePlan plan;       /* query plan for this element of the FROM clause */
10818  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10819  int iTabCur;          /* The VDBE cursor used to access the table */
10820  int iIdxCur;          /* The VDBE cursor used to access pIdx */
10821  int addrBrk;          /* Jump here to break out of the loop */
10822  int addrNxt;          /* Jump here to start the next IN combination */
10823  int addrCont;         /* Jump here to continue with the next loop cycle */
10824  int addrFirst;        /* First instruction of interior of the loop */
10825  u8 iFrom;             /* Which entry in the FROM clause */
10826  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10827  int p1, p2;           /* Operands of the opcode used to ends the loop */
10828  union {               /* Information that depends on plan.wsFlags */
10829    struct {
10830      int nIn;              /* Number of entries in aInLoop[] */
10831      struct InLoop {
10832        int iCur;              /* The VDBE cursor used by this IN operator */
10833        int addrInTop;         /* Top of the IN loop */
10834      } *aInLoop;           /* Information about each nested IN operator */
10835    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10836  } u;
10837
10838  /* The following field is really not part of the current level.  But
10839  ** we need a place to cache virtual table index information for each
10840  ** virtual table in the FROM clause and the WhereLevel structure is
10841  ** a convenient place since there is one WhereLevel for each FROM clause
10842  ** element.
10843  */
10844  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10845};
10846
10847/*
10848** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10849** and the WhereInfo.wctrlFlags member.
10850*/
10851#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10852#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10853#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10854#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10855#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10856#define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
10857#define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
10858#define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
10859#define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
10860
10861/*
10862** The WHERE clause processing routine has two halves.  The
10863** first part does the start of the WHERE loop and the second
10864** half does the tail of the WHERE loop.  An instance of
10865** this structure is returned by the first half and passed
10866** into the second half to give some continuity.
10867*/
10868struct WhereInfo {
10869  Parse *pParse;       /* Parsing and code generating context */
10870  u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10871  u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10872  u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10873  u8 eDistinct;
10874  SrcList *pTabList;             /* List of tables in the join */
10875  int iTop;                      /* The very beginning of the WHERE loop */
10876  int iContinue;                 /* Jump here to continue with next record */
10877  int iBreak;                    /* Jump here to break out of the loop */
10878  int nLevel;                    /* Number of nested loop */
10879  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10880  double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10881  double nRowOut;                /* Estimated number of output rows */
10882  WhereLevel a[1];               /* Information about each nest loop in WHERE */
10883};
10884
10885#define WHERE_DISTINCT_UNIQUE 1
10886#define WHERE_DISTINCT_ORDERED 2
10887
10888/*
10889** A NameContext defines a context in which to resolve table and column
10890** names.  The context consists of a list of tables (the pSrcList) field and
10891** a list of named expression (pEList).  The named expression list may
10892** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10893** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10894** pEList corresponds to the result set of a SELECT and is NULL for
10895** other statements.
10896**
10897** NameContexts can be nested.  When resolving names, the inner-most
10898** context is searched first.  If no match is found, the next outer
10899** context is checked.  If there is still no match, the next context
10900** is checked.  This process continues until either a match is found
10901** or all contexts are check.  When a match is found, the nRef member of
10902** the context containing the match is incremented.
10903**
10904** Each subquery gets a new NameContext.  The pNext field points to the
10905** NameContext in the parent query.  Thus the process of scanning the
10906** NameContext list corresponds to searching through successively outer
10907** subqueries looking for a match.
10908*/
10909struct NameContext {
10910  Parse *pParse;       /* The parser */
10911  SrcList *pSrcList;   /* One or more tables used to resolve names */
10912  ExprList *pEList;    /* Optional list of named expressions */
10913  int nRef;            /* Number of names resolved by this context */
10914  int nErr;            /* Number of errors encountered while resolving names */
10915  u8 allowAgg;         /* Aggregate functions allowed here */
10916  u8 hasAgg;           /* True if aggregates are seen */
10917  u8 isCheck;          /* True if resolving names in a CHECK constraint */
10918  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10919  AggInfo *pAggInfo;   /* Information about aggregates at this level */
10920  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10921};
10922
10923/*
10924** An instance of the following structure contains all information
10925** needed to generate code for a single SELECT statement.
10926**
10927** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10928** If there is a LIMIT clause, the parser sets nLimit to the value of the
10929** limit and nOffset to the value of the offset (or 0 if there is not
10930** offset).  But later on, nLimit and nOffset become the memory locations
10931** in the VDBE that record the limit and offset counters.
10932**
10933** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10934** These addresses must be stored so that we can go back and fill in
10935** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10936** the number of columns in P2 can be computed at the same time
10937** as the OP_OpenEphm instruction is coded because not
10938** enough information about the compound query is known at that point.
10939** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10940** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10941** sequences for the ORDER BY clause.
10942*/
10943struct Select {
10944  ExprList *pEList;      /* The fields of the result */
10945  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10946  char affinity;         /* MakeRecord with this affinity for SRT_Set */
10947  u16 selFlags;          /* Various SF_* values */
10948  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10949  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10950  double nSelectRow;     /* Estimated number of result rows */
10951  SrcList *pSrc;         /* The FROM clause */
10952  Expr *pWhere;          /* The WHERE clause */
10953  ExprList *pGroupBy;    /* The GROUP BY clause */
10954  Expr *pHaving;         /* The HAVING clause */
10955  ExprList *pOrderBy;    /* The ORDER BY clause */
10956  Select *pPrior;        /* Prior select in a compound select statement */
10957  Select *pNext;         /* Next select to the left in a compound */
10958  Select *pRightmost;    /* Right-most select in a compound select statement */
10959  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10960  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10961};
10962
10963/*
10964** Allowed values for Select.selFlags.  The "SF" prefix stands for
10965** "Select Flag".
10966*/
10967#define SF_Distinct        0x01  /* Output should be DISTINCT */
10968#define SF_Resolved        0x02  /* Identifiers have been resolved */
10969#define SF_Aggregate       0x04  /* Contains aggregate functions */
10970#define SF_UsesEphemeral   0x08  /* Uses the OpenEphemeral opcode */
10971#define SF_Expanded        0x10  /* sqlite3SelectExpand() called on this */
10972#define SF_HasTypeInfo     0x20  /* FROM subqueries have Table metadata */
10973#define SF_UseSorter       0x40  /* Sort using a sorter */
10974#define SF_Values          0x80  /* Synthesized from VALUES clause */
10975
10976
10977/*
10978** The results of a select can be distributed in several ways.  The
10979** "SRT" prefix means "SELECT Result Type".
10980*/
10981#define SRT_Union        1  /* Store result as keys in an index */
10982#define SRT_Except       2  /* Remove result from a UNION index */
10983#define SRT_Exists       3  /* Store 1 if the result is not empty */
10984#define SRT_Discard      4  /* Do not save the results anywhere */
10985
10986/* The ORDER BY clause is ignored for all of the above */
10987#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10988
10989#define SRT_Output       5  /* Output each row of result */
10990#define SRT_Mem          6  /* Store result in a memory cell */
10991#define SRT_Set          7  /* Store results as keys in an index */
10992#define SRT_Table        8  /* Store result as data with an automatic rowid */
10993#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10994#define SRT_Coroutine   10  /* Generate a single row of result */
10995
10996/*
10997** A structure used to customize the behavior of sqlite3Select(). See
10998** comments above sqlite3Select() for details.
10999*/
11000typedef struct SelectDest SelectDest;
11001struct SelectDest {
11002  u8 eDest;         /* How to dispose of the results */
11003  u8 affinity;      /* Affinity used when eDest==SRT_Set */
11004  int iParm;        /* A parameter used by the eDest disposal method */
11005  int iMem;         /* Base register where results are written */
11006  int nMem;         /* Number of registers allocated */
11007};
11008
11009/*
11010** During code generation of statements that do inserts into AUTOINCREMENT
11011** tables, the following information is attached to the Table.u.autoInc.p
11012** pointer of each autoincrement table to record some side information that
11013** the code generator needs.  We have to keep per-table autoincrement
11014** information in case inserts are down within triggers.  Triggers do not
11015** normally coordinate their activities, but we do need to coordinate the
11016** loading and saving of autoincrement information.
11017*/
11018struct AutoincInfo {
11019  AutoincInfo *pNext;   /* Next info block in a list of them all */
11020  Table *pTab;          /* Table this info block refers to */
11021  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11022  int regCtr;           /* Memory register holding the rowid counter */
11023};
11024
11025/*
11026** Size of the column cache
11027*/
11028#ifndef SQLITE_N_COLCACHE
11029# define SQLITE_N_COLCACHE 10
11030#endif
11031
11032/*
11033** At least one instance of the following structure is created for each
11034** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11035** statement. All such objects are stored in the linked list headed at
11036** Parse.pTriggerPrg and deleted once statement compilation has been
11037** completed.
11038**
11039** A Vdbe sub-program that implements the body and WHEN clause of trigger
11040** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11041** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11042** The Parse.pTriggerPrg list never contains two entries with the same
11043** values for both pTrigger and orconf.
11044**
11045** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11046** accessed (or set to 0 for triggers fired as a result of INSERT
11047** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11048** a mask of new.* columns used by the program.
11049*/
11050struct TriggerPrg {
11051  Trigger *pTrigger;      /* Trigger this program was coded from */
11052  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
11053  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
11054  int orconf;             /* Default ON CONFLICT policy */
11055  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
11056};
11057
11058/*
11059** The yDbMask datatype for the bitmask of all attached databases.
11060*/
11061#if SQLITE_MAX_ATTACHED>30
11062  typedef sqlite3_uint64 yDbMask;
11063#else
11064  typedef unsigned int yDbMask;
11065#endif
11066
11067/*
11068** An SQL parser context.  A copy of this structure is passed through
11069** the parser and down into all the parser action routine in order to
11070** carry around information that is global to the entire parse.
11071**
11072** The structure is divided into two parts.  When the parser and code
11073** generate call themselves recursively, the first part of the structure
11074** is constant but the second part is reset at the beginning and end of
11075** each recursion.
11076**
11077** The nTableLock and aTableLock variables are only used if the shared-cache
11078** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11079** used to store the set of table-locks required by the statement being
11080** compiled. Function sqlite3TableLock() is used to add entries to the
11081** list.
11082*/
11083struct Parse {
11084  sqlite3 *db;         /* The main database structure */
11085  char *zErrMsg;       /* An error message */
11086  Vdbe *pVdbe;         /* An engine for executing database bytecode */
11087  int rc;              /* Return code from execution */
11088  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
11089  u8 checkSchema;      /* Causes schema cookie check after an error */
11090  u8 nested;           /* Number of nested calls to the parser/code generator */
11091  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
11092  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
11093  u8 nColCache;        /* Number of entries in aColCache[] */
11094  u8 iColCache;        /* Next entry in aColCache[] to replace */
11095  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
11096  u8 mayAbort;         /* True if statement may throw an ABORT exception */
11097  int aTempReg[8];     /* Holding area for temporary registers */
11098  int nRangeReg;       /* Size of the temporary register block */
11099  int iRangeReg;       /* First register in temporary register block */
11100  int nErr;            /* Number of errors seen */
11101  int nTab;            /* Number of previously allocated VDBE cursors */
11102  int nMem;            /* Number of memory cells used so far */
11103  int nSet;            /* Number of sets used so far */
11104  int nOnce;           /* Number of OP_Once instructions so far */
11105  int ckBase;          /* Base register of data during check constraints */
11106  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11107  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
11108  struct yColCache {
11109    int iTable;           /* Table cursor number */
11110    int iColumn;          /* Table column number */
11111    u8 tempReg;           /* iReg is a temp register that needs to be freed */
11112    int iLevel;           /* Nesting level */
11113    int iReg;             /* Reg with value of this column. 0 means none. */
11114    int lru;              /* Least recently used entry has the smallest value */
11115  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
11116  yDbMask writeMask;   /* Start a write transaction on these databases */
11117  yDbMask cookieMask;  /* Bitmask of schema verified databases */
11118  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
11119  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
11120  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
11121  int regRoot;         /* Register holding root page number for new objects */
11122  int nMaxArg;         /* Max args passed to user function by sub-program */
11123#ifndef SQLITE_OMIT_SHARED_CACHE
11124  int nTableLock;        /* Number of locks in aTableLock */
11125  TableLock *aTableLock; /* Required table locks for shared-cache mode */
11126#endif
11127  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
11128
11129  /* Information used while coding trigger programs. */
11130  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
11131  Table *pTriggerTab;  /* Table triggers are being coded for */
11132  double nQueryLoop;   /* Estimated number of iterations of a query */
11133  u32 oldmask;         /* Mask of old.* columns referenced */
11134  u32 newmask;         /* Mask of new.* columns referenced */
11135  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
11136  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
11137  u8 disableTriggers;  /* True to disable triggers */
11138
11139  /* Above is constant between recursions.  Below is reset before and after
11140  ** each recursion */
11141
11142  int nVar;                 /* Number of '?' variables seen in the SQL so far */
11143  int nzVar;                /* Number of available slots in azVar[] */
11144  u8 explain;               /* True if the EXPLAIN flag is found on the query */
11145#ifndef SQLITE_OMIT_VIRTUALTABLE
11146  u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
11147  int nVtabLock;            /* Number of virtual tables to lock */
11148#endif
11149  int nAlias;               /* Number of aliased result set columns */
11150  int nHeight;              /* Expression tree height of current sub-select */
11151#ifndef SQLITE_OMIT_EXPLAIN
11152  int iSelectId;            /* ID of current select for EXPLAIN output */
11153  int iNextSelectId;        /* Next available select ID for EXPLAIN output */
11154#endif
11155  char **azVar;             /* Pointers to names of parameters */
11156  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
11157  int *aAlias;              /* Register used to hold aliased result */
11158  const char *zTail;        /* All SQL text past the last semicolon parsed */
11159  Table *pNewTable;         /* A table being constructed by CREATE TABLE */
11160  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
11161  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11162  Token sNameToken;         /* Token with unqualified schema object name */
11163  Token sLastToken;         /* The last token parsed */
11164#ifndef SQLITE_OMIT_VIRTUALTABLE
11165  Token sArg;               /* Complete text of a module argument */
11166  Table **apVtabLock;       /* Pointer to virtual tables needing locking */
11167#endif
11168  Table *pZombieTab;        /* List of Table objects to delete after code gen */
11169  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
11170};
11171
11172/*
11173** Return true if currently inside an sqlite3_declare_vtab() call.
11174*/
11175#ifdef SQLITE_OMIT_VIRTUALTABLE
11176  #define IN_DECLARE_VTAB 0
11177#else
11178  #define IN_DECLARE_VTAB (pParse->declareVtab)
11179#endif
11180
11181/*
11182** An instance of the following structure can be declared on a stack and used
11183** to save the Parse.zAuthContext value so that it can be restored later.
11184*/
11185struct AuthContext {
11186  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11187  Parse *pParse;              /* The Parse structure */
11188};
11189
11190/*
11191** Bitfield flags for P5 value in OP_Insert and OP_Delete
11192*/
11193#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11194#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11195#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11196#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11197#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11198#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11199
11200/*
11201 * Each trigger present in the database schema is stored as an instance of
11202 * struct Trigger.
11203 *
11204 * Pointers to instances of struct Trigger are stored in two ways.
11205 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
11206 *    database). This allows Trigger structures to be retrieved by name.
11207 * 2. All triggers associated with a single table form a linked list, using the
11208 *    pNext member of struct Trigger. A pointer to the first element of the
11209 *    linked list is stored as the "pTrigger" member of the associated
11210 *    struct Table.
11211 *
11212 * The "step_list" member points to the first element of a linked list
11213 * containing the SQL statements specified as the trigger program.
11214 */
11215struct Trigger {
11216  char *zName;            /* The name of the trigger                        */
11217  char *table;            /* The table or view to which the trigger applies */
11218  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11219  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11220  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11221  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11222                             the <column-list> is stored here */
11223  Schema *pSchema;        /* Schema containing the trigger */
11224  Schema *pTabSchema;     /* Schema containing the table */
11225  TriggerStep *step_list; /* Link list of trigger program steps             */
11226  Trigger *pNext;         /* Next trigger associated with the table */
11227};
11228
11229/*
11230** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11231** determine which.
11232**
11233** If there are multiple triggers, you might of some BEFORE and some AFTER.
11234** In that cases, the constants below can be ORed together.
11235*/
11236#define TRIGGER_BEFORE  1
11237#define TRIGGER_AFTER   2
11238
11239/*
11240 * An instance of struct TriggerStep is used to store a single SQL statement
11241 * that is a part of a trigger-program.
11242 *
11243 * Instances of struct TriggerStep are stored in a singly linked list (linked
11244 * using the "pNext" member) referenced by the "step_list" member of the
11245 * associated struct Trigger instance. The first element of the linked list is
11246 * the first step of the trigger-program.
11247 *
11248 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11249 * "SELECT" statement. The meanings of the other members is determined by the
11250 * value of "op" as follows:
11251 *
11252 * (op == TK_INSERT)
11253 * orconf    -> stores the ON CONFLICT algorithm
11254 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11255 *              this stores a pointer to the SELECT statement. Otherwise NULL.
11256 * target    -> A token holding the quoted name of the table to insert into.
11257 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11258 *              this stores values to be inserted. Otherwise NULL.
11259 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
11260 *              statement, then this stores the column-names to be
11261 *              inserted into.
11262 *
11263 * (op == TK_DELETE)
11264 * target    -> A token holding the quoted name of the table to delete from.
11265 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11266 *              Otherwise NULL.
11267 *
11268 * (op == TK_UPDATE)
11269 * target    -> A token holding the quoted name of the table to update rows of.
11270 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11271 *              Otherwise NULL.
11272 * pExprList -> A list of the columns to update and the expressions to update
11273 *              them to. See sqlite3Update() documentation of "pChanges"
11274 *              argument.
11275 *
11276 */
11277struct TriggerStep {
11278  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11279  u8 orconf;           /* OE_Rollback etc. */
11280  Trigger *pTrig;      /* The trigger that this step is a part of */
11281  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11282  Token target;        /* Target table for DELETE, UPDATE, INSERT */
11283  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11284  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11285  IdList *pIdList;     /* Column names for INSERT */
11286  TriggerStep *pNext;  /* Next in the link-list */
11287  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11288};
11289
11290/*
11291** The following structure contains information used by the sqliteFix...
11292** routines as they walk the parse tree to make database references
11293** explicit.
11294*/
11295typedef struct DbFixer DbFixer;
11296struct DbFixer {
11297  Parse *pParse;      /* The parsing context.  Error messages written here */
11298  const char *zDb;    /* Make sure all objects are contained in this database */
11299  const char *zType;  /* Type of the container - used for error messages */
11300  const Token *pName; /* Name of the container - used for error messages */
11301};
11302
11303/*
11304** An objected used to accumulate the text of a string where we
11305** do not necessarily know how big the string will be in the end.
11306*/
11307struct StrAccum {
11308  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11309  char *zBase;         /* A base allocation.  Not from malloc. */
11310  char *zText;         /* The string collected so far */
11311  int  nChar;          /* Length of the string so far */
11312  int  nAlloc;         /* Amount of space allocated in zText */
11313  int  mxAlloc;        /* Maximum allowed string length */
11314  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11315  u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11316  u8   tooBig;         /* Becomes true if string size exceeds limits */
11317};
11318
11319/*
11320** A pointer to this structure is used to communicate information
11321** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11322*/
11323typedef struct {
11324  sqlite3 *db;        /* The database being initialized */
11325  char **pzErrMsg;    /* Error message stored here */
11326  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11327  int rc;             /* Result code stored here */
11328} InitData;
11329
11330/*
11331** Structure containing global configuration data for the SQLite library.
11332**
11333** This structure also contains some state information.
11334*/
11335struct Sqlite3Config {
11336  int bMemstat;                     /* True to enable memory status */
11337  int bCoreMutex;                   /* True to enable core mutexing */
11338  int bFullMutex;                   /* True to enable full mutexing */
11339  int bOpenUri;                     /* True to interpret filenames as URIs */
11340  int mxStrlen;                     /* Maximum string length */
11341  int szLookaside;                  /* Default lookaside buffer size */
11342  int nLookaside;                   /* Default lookaside buffer count */
11343  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11344  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11345  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
11346  void *pHeap;                      /* Heap storage space */
11347  int nHeap;                        /* Size of pHeap[] */
11348  int mnReq, mxReq;                 /* Min and max heap requests sizes */
11349  void *pScratch;                   /* Scratch memory */
11350  int szScratch;                    /* Size of each scratch buffer */
11351  int nScratch;                     /* Number of scratch buffers */
11352  void *pPage;                      /* Page cache memory */
11353  int szPage;                       /* Size of each page in pPage[] */
11354  int nPage;                        /* Number of pages in pPage[] */
11355  int mxParserStack;                /* maximum depth of the parser stack */
11356  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11357  /* The above might be initialized to non-zero.  The following need to always
11358  ** initially be zero, however. */
11359  int isInit;                       /* True after initialization has finished */
11360  int inProgress;                   /* True while initialization in progress */
11361  int isMutexInit;                  /* True after mutexes are initialized */
11362  int isMallocInit;                 /* True after malloc is initialized */
11363  int isPCacheInit;                 /* True after malloc is initialized */
11364  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11365  int nRefInitMutex;                /* Number of users of pInitMutex */
11366  void (*xLog)(void*,int,const char*); /* Function for logging */
11367  void *pLogArg;                       /* First argument to xLog() */
11368  int bLocaltimeFault;              /* True to fail localtime() calls */
11369};
11370
11371/*
11372** Context pointer passed down through the tree-walk.
11373*/
11374struct Walker {
11375  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11376  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11377  Parse *pParse;                            /* Parser context.  */
11378  union {                                   /* Extra data for callback */
11379    NameContext *pNC;                          /* Naming context */
11380    int i;                                     /* Integer value */
11381  } u;
11382};
11383
11384/* Forward declarations */
11385SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11386SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11387SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11388SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11389SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11390
11391/*
11392** Return code from the parse-tree walking primitives and their
11393** callbacks.
11394*/
11395#define WRC_Continue    0   /* Continue down into children */
11396#define WRC_Prune       1   /* Omit children but continue walking siblings */
11397#define WRC_Abort       2   /* Abandon the tree walk */
11398
11399/*
11400** Assuming zIn points to the first byte of a UTF-8 character,
11401** advance zIn to point to the first byte of the next UTF-8 character.
11402*/
11403#define SQLITE_SKIP_UTF8(zIn) {                        \
11404  if( (*(zIn++))>=0xc0 ){                              \
11405    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11406  }                                                    \
11407}
11408
11409/*
11410** The SQLITE_*_BKPT macros are substitutes for the error codes with
11411** the same name but without the _BKPT suffix.  These macros invoke
11412** routines that report the line-number on which the error originated
11413** using sqlite3_log().  The routines also provide a convenient place
11414** to set a debugger breakpoint.
11415*/
11416SQLITE_PRIVATE int sqlite3CorruptError(int);
11417SQLITE_PRIVATE int sqlite3MisuseError(int);
11418SQLITE_PRIVATE int sqlite3CantopenError(int);
11419#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11420#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11421#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11422
11423
11424/*
11425** FTS4 is really an extension for FTS3.  It is enabled using the
11426** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11427** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11428*/
11429#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11430# define SQLITE_ENABLE_FTS3
11431#endif
11432
11433/*
11434** The ctype.h header is needed for non-ASCII systems.  It is also
11435** needed by FTS3 when FTS3 is included in the amalgamation.
11436*/
11437#if !defined(SQLITE_ASCII) || \
11438    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11439# include <ctype.h>
11440#endif
11441
11442/*
11443** The following macros mimic the standard library functions toupper(),
11444** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11445** sqlite versions only work for ASCII characters, regardless of locale.
11446*/
11447#ifdef SQLITE_ASCII
11448# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11449# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11450# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11451# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11452# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11453# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11454# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11455#else
11456# define sqlite3Toupper(x)   toupper((unsigned char)(x))
11457# define sqlite3Isspace(x)   isspace((unsigned char)(x))
11458# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11459# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11460# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11461# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11462# define sqlite3Tolower(x)   tolower((unsigned char)(x))
11463#endif
11464
11465/*
11466** Internal function prototypes
11467*/
11468#define sqlite3StrICmp sqlite3_stricmp
11469SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11470#define sqlite3StrNICmp sqlite3_strnicmp
11471
11472SQLITE_PRIVATE int sqlite3MallocInit(void);
11473SQLITE_PRIVATE void sqlite3MallocEnd(void);
11474SQLITE_PRIVATE void *sqlite3Malloc(int);
11475SQLITE_PRIVATE void *sqlite3MallocZero(int);
11476SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11477SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11478SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11479SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11480SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11481SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11482SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11483SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11484SQLITE_PRIVATE int sqlite3MallocSize(void*);
11485SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11486SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11487SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11488SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11489SQLITE_PRIVATE void sqlite3PageFree(void*);
11490SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11491SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11492SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11493
11494/*
11495** On systems with ample stack space and that support alloca(), make
11496** use of alloca() to obtain space for large automatic objects.  By default,
11497** obtain space from malloc().
11498**
11499** The alloca() routine never returns NULL.  This will cause code paths
11500** that deal with sqlite3StackAlloc() failures to be unreachable.
11501*/
11502#ifdef SQLITE_USE_ALLOCA
11503# define sqlite3StackAllocRaw(D,N)   alloca(N)
11504# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11505# define sqlite3StackFree(D,P)
11506#else
11507# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
11508# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
11509# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
11510#endif
11511
11512#ifdef SQLITE_ENABLE_MEMSYS3
11513SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11514#endif
11515#ifdef SQLITE_ENABLE_MEMSYS5
11516SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11517#endif
11518
11519
11520#ifndef SQLITE_MUTEX_OMIT
11521SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11522SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11523SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
11524SQLITE_PRIVATE   int sqlite3MutexInit(void);
11525SQLITE_PRIVATE   int sqlite3MutexEnd(void);
11526#endif
11527
11528SQLITE_PRIVATE int sqlite3StatusValue(int);
11529SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11530SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11531
11532#ifndef SQLITE_OMIT_FLOATING_POINT
11533SQLITE_PRIVATE   int sqlite3IsNaN(double);
11534#else
11535# define sqlite3IsNaN(X)  0
11536#endif
11537
11538SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11539#ifndef SQLITE_OMIT_TRACE
11540SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11541#endif
11542SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11543SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11544SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11545#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11546SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
11547#endif
11548#if defined(SQLITE_TEST)
11549SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
11550#endif
11551
11552/* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
11553#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
11554SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
11555SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
11556SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
11557SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
11558SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
11559SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
11560SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
11561SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
11562SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
11563SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
11564#else
11565# define sqlite3ExplainBegin(X)
11566# define sqlite3ExplainSelect(A,B)
11567# define sqlite3ExplainExpr(A,B)
11568# define sqlite3ExplainExprList(A,B)
11569# define sqlite3ExplainFinish(X)
11570# define sqlite3VdbeExplanation(X) 0
11571#endif
11572
11573
11574SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11575SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11576SQLITE_PRIVATE int sqlite3Dequote(char*);
11577SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11578SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11579SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11580SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11581SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11582SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11583SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11584SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
11585SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11586SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11587SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11588SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11589SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11590SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11591SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11592SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11593SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11594SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11595SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11596SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11597SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11598SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11599SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11600SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
11601SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11602SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11603SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11604SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11605SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11606SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11607SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11608SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11609SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11610SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11611SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11612SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11613SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11614SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11615                    sqlite3_vfs**,char**,char **);
11616SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
11617SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
11618
11619SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11620SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11621SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11622SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11623SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11624SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11625SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11626
11627SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11628SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11629SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11630SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11631SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11632
11633SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11634
11635#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11636SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11637#else
11638# define sqlite3ViewGetColumnNames(A,B) 0
11639#endif
11640
11641SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11642SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
11643SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11644#ifndef SQLITE_OMIT_AUTOINCREMENT
11645SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11646SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11647#else
11648# define sqlite3AutoincrementBegin(X)
11649# define sqlite3AutoincrementEnd(X)
11650#endif
11651SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11652SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
11653SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11654SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11655SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11656SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11657SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11658                                      Token*, Select*, Expr*, IdList*);
11659SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11660SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11661SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11662SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11663SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11664SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11665SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11666                        Token*, int, int);
11667SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11668SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11669SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11670                         Expr*,ExprList*,int,Expr*,Expr*);
11671SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11672SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11673SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11674SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11675#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11676SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11677#endif
11678SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11679SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11680SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**,ExprList*,u16);
11681SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11682SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11683SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11684SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11685SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11686SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11687SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11688SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11689SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11690SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11691SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11692SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11693SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11694SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11695SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11696SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11697SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11698SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11699SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11700SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11701SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11702SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11703SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11704SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11705SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11706SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11707SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11708SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11709SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11710SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11711SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11712SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11713SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11714SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11715SQLITE_PRIVATE void sqlite3PrngResetState(void);
11716SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
11717SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11718SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11719SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11720SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11721SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11722SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11723SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11724SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11725SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11726SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11727SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11728SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11729SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11730SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11731SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11732SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11733SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11734SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11735SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11736                                     int*,int,int,int,int,int*);
11737SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11738SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11739SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11740SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11741SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11742SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11743SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11744SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11745SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11746SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11747SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11748SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11749SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
11750SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11751SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11752SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11753SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11754SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11755SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11756
11757#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11758SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11759#endif
11760
11761#ifndef SQLITE_OMIT_TRIGGER
11762SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11763                           Expr*,int, int);
11764SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11765SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11766SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11767SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11768SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
11769SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11770                            int, int, int);
11771SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11772  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11773SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11774SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11775SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11776                                        ExprList*,Select*,u8);
11777SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11778SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11779SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11780SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11781SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11782# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11783#else
11784# define sqlite3TriggersExist(B,C,D,E,F) 0
11785# define sqlite3DeleteTrigger(A,B)
11786# define sqlite3DropTriggerPtr(A,B)
11787# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11788# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11789# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11790# define sqlite3TriggerList(X, Y) 0
11791# define sqlite3ParseToplevel(p) p
11792# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11793#endif
11794
11795SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11796SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11797SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11798#ifndef SQLITE_OMIT_AUTHORIZATION
11799SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11800SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11801SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11802SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
11803SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11804#else
11805# define sqlite3AuthRead(a,b,c,d)
11806# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
11807# define sqlite3AuthContextPush(a,b,c)
11808# define sqlite3AuthContextPop(a)  ((void)(a))
11809#endif
11810SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11811SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11812SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11813SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11814SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11815SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11816SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11817SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11818SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11819SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11820SQLITE_PRIVATE int sqlite3Atoi(const char*);
11821SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11822SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11823SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8*, const u8**);
11824
11825/*
11826** Routines to read and write variable-length integers.  These used to
11827** be defined locally, but now we use the varint routines in the util.c
11828** file.  Code should use the MACRO forms below, as the Varint32 versions
11829** are coded to assume the single byte case is already handled (which
11830** the MACRO form does).
11831*/
11832SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11833SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11834SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11835SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11836SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11837
11838/*
11839** The header of a record consists of a sequence variable-length integers.
11840** These integers are almost always small and are encoded as a single byte.
11841** The following macros take advantage this fact to provide a fast encode
11842** and decode of the integers in a record header.  It is faster for the common
11843** case where the integer is a single byte.  It is a little slower when the
11844** integer is two or more bytes.  But overall it is faster.
11845**
11846** The following expressions are equivalent:
11847**
11848**     x = sqlite3GetVarint32( A, &B );
11849**     x = sqlite3PutVarint32( A, B );
11850**
11851**     x = getVarint32( A, B );
11852**     x = putVarint32( A, B );
11853**
11854*/
11855#define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11856#define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11857#define getVarint    sqlite3GetVarint
11858#define putVarint    sqlite3PutVarint
11859
11860
11861SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11862SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11863SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11864SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11865SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11866SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11867SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11868SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11869SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
11870SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11871SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11872SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11873SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11874SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11875SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11876SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11877SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11878SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11879SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11880SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11881SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
11882SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
11883SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
11884SQLITE_PRIVATE int sqlite3AbsInt32(int);
11885#ifdef SQLITE_ENABLE_8_3_NAMES
11886SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
11887#else
11888# define sqlite3FileSuffix3(X,Y)
11889#endif
11890SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
11891
11892SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11893SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11894SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
11895                        void(*)(void*));
11896SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11897SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11898SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11899#ifdef SQLITE_ENABLE_STAT3
11900SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11901#endif
11902SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11903SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11904#ifndef SQLITE_AMALGAMATION
11905SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11906SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11907SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11908SQLITE_PRIVATE const Token sqlite3IntTokens[];
11909SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11910SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11911#ifndef SQLITE_OMIT_WSD
11912SQLITE_PRIVATE int sqlite3PendingByte;
11913#endif
11914#endif
11915SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
11916SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11917SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11918SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11919SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11920SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11921SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11922SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11923SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11924SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11925SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11926SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11927SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11928SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11929SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11930SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11931SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11932SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11933SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11934SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11935SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11936SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11937SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11938SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11939SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11940SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11941SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11942SQLITE_PRIVATE void sqlite3SchemaClear(void *);
11943SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11944SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11945SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11946SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
11947  void (*)(sqlite3_context*,int,sqlite3_value **),
11948  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11949  FuncDestructor *pDestructor
11950);
11951SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11952SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11953
11954SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11955SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11956SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
11957SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11958SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11959SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11960SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11961
11962SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11963SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11964
11965/*
11966** The interface to the LEMON-generated parser
11967*/
11968SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11969SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11970SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11971#ifdef YYTRACKMAXSTACKDEPTH
11972SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
11973#endif
11974
11975SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11976#ifndef SQLITE_OMIT_LOAD_EXTENSION
11977SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
11978#else
11979# define sqlite3CloseExtensions(X)
11980#endif
11981
11982#ifndef SQLITE_OMIT_SHARED_CACHE
11983SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
11984#else
11985  #define sqlite3TableLock(v,w,x,y,z)
11986#endif
11987
11988#ifdef SQLITE_TEST
11989SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
11990#endif
11991
11992#ifdef SQLITE_OMIT_VIRTUALTABLE
11993#  define sqlite3VtabClear(Y)
11994#  define sqlite3VtabSync(X,Y) SQLITE_OK
11995#  define sqlite3VtabRollback(X)
11996#  define sqlite3VtabCommit(X)
11997#  define sqlite3VtabInSync(db) 0
11998#  define sqlite3VtabLock(X)
11999#  define sqlite3VtabUnlock(X)
12000#  define sqlite3VtabUnlockList(X)
12001#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12002#  define sqlite3GetVTable(X,Y)  ((VTable*)0)
12003#else
12004SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
12005SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
12006SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
12007SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
12008SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
12009SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
12010SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
12011SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
12012SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
12013#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12014#endif
12015SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12016SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12017SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12018SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12019SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12020SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12021SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12022SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12023SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12024SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12025SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12026SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12027SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12028SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12029SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12030SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12031SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12032SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12033SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12034SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12035
12036/* Declarations for functions in fkey.c. All of these are replaced by
12037** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12038** key functionality is available. If OMIT_TRIGGER is defined but
12039** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12040** this case foreign keys are parsed, but no other functionality is
12041** provided (enforcement of FK constraints requires the triggers sub-system).
12042*/
12043#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12044SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
12045SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12046SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
12047SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
12048SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
12049SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
12050#else
12051  #define sqlite3FkActions(a,b,c,d)
12052  #define sqlite3FkCheck(a,b,c,d)
12053  #define sqlite3FkDropTable(a,b,c)
12054  #define sqlite3FkOldmask(a,b)      0
12055  #define sqlite3FkRequired(a,b,c,d) 0
12056#endif
12057#ifndef SQLITE_OMIT_FOREIGN_KEY
12058SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
12059#else
12060  #define sqlite3FkDelete(a,b)
12061#endif
12062
12063
12064/*
12065** Available fault injectors.  Should be numbered beginning with 0.
12066*/
12067#define SQLITE_FAULTINJECTOR_MALLOC     0
12068#define SQLITE_FAULTINJECTOR_COUNT      1
12069
12070/*
12071** The interface to the code in fault.c used for identifying "benign"
12072** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12073** is not defined.
12074*/
12075#ifndef SQLITE_OMIT_BUILTIN_TEST
12076SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
12077SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
12078#else
12079  #define sqlite3BeginBenignMalloc()
12080  #define sqlite3EndBenignMalloc()
12081#endif
12082
12083#define IN_INDEX_ROWID           1
12084#define IN_INDEX_EPH             2
12085#define IN_INDEX_INDEX           3
12086SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12087
12088#ifdef SQLITE_ENABLE_ATOMIC_WRITE
12089SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12090SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
12091SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
12092#else
12093  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12094#endif
12095
12096SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12097SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12098SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12099
12100#if SQLITE_MAX_EXPR_DEPTH>0
12101SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12102SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
12103SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
12104#else
12105  #define sqlite3ExprSetHeight(x,y)
12106  #define sqlite3SelectExprHeight(x) 0
12107  #define sqlite3ExprCheckHeight(x,y)
12108#endif
12109
12110SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12111SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12112
12113#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12114SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12115SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
12116SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
12117#else
12118  #define sqlite3ConnectionBlocked(x,y)
12119  #define sqlite3ConnectionUnlocked(x)
12120  #define sqlite3ConnectionClosed(x)
12121#endif
12122
12123#ifdef SQLITE_DEBUG
12124SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
12125#endif
12126
12127/*
12128** If the SQLITE_ENABLE IOTRACE exists then the global variable
12129** sqlite3IoTrace is a pointer to a printf-like routine used to
12130** print I/O tracing messages.
12131*/
12132#ifdef SQLITE_ENABLE_IOTRACE
12133# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12134SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
12135SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12136#else
12137# define IOTRACE(A)
12138# define sqlite3VdbeIOTraceSql(X)
12139#endif
12140
12141/*
12142** These routines are available for the mem2.c debugging memory allocator
12143** only.  They are used to verify that different "types" of memory
12144** allocations are properly tracked by the system.
12145**
12146** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12147** the MEMTYPE_* macros defined below.  The type must be a bitmask with
12148** a single bit set.
12149**
12150** sqlite3MemdebugHasType() returns true if any of the bits in its second
12151** argument match the type set by the previous sqlite3MemdebugSetType().
12152** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12153**
12154** sqlite3MemdebugNoType() returns true if none of the bits in its second
12155** argument match the type set by the previous sqlite3MemdebugSetType().
12156**
12157** Perhaps the most important point is the difference between MEMTYPE_HEAP
12158** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
12159** it might have been allocated by lookaside, except the allocation was
12160** too large or lookaside was already full.  It is important to verify
12161** that allocations that might have been satisfied by lookaside are not
12162** passed back to non-lookaside free() routines.  Asserts such as the
12163** example above are placed on the non-lookaside free() routines to verify
12164** this constraint.
12165**
12166** All of this is no-op for a production build.  It only comes into
12167** play when the SQLITE_MEMDEBUG compile-time option is used.
12168*/
12169#ifdef SQLITE_MEMDEBUG
12170SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
12171SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
12172SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
12173#else
12174# define sqlite3MemdebugSetType(X,Y)  /* no-op */
12175# define sqlite3MemdebugHasType(X,Y)  1
12176# define sqlite3MemdebugNoType(X,Y)   1
12177#endif
12178#define MEMTYPE_HEAP       0x01  /* General heap allocations */
12179#define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
12180#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
12181#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
12182#define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
12183
12184#endif /* _SQLITEINT_H_ */
12185
12186/************** End of sqliteInt.h *******************************************/
12187/************** Begin file global.c ******************************************/
12188/*
12189** 2008 June 13
12190**
12191** The author disclaims copyright to this source code.  In place of
12192** a legal notice, here is a blessing:
12193**
12194**    May you do good and not evil.
12195**    May you find forgiveness for yourself and forgive others.
12196**    May you share freely, never taking more than you give.
12197**
12198*************************************************************************
12199**
12200** This file contains definitions of global variables and contants.
12201*/
12202
12203/* An array to map all upper-case characters into their corresponding
12204** lower-case character.
12205**
12206** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
12207** handle case conversions for the UTF character set since the tables
12208** involved are nearly as big or bigger than SQLite itself.
12209*/
12210SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12211#ifdef SQLITE_ASCII
12212      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
12213     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12214     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12215     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12216    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12217    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12218    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12219    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12220    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12221    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12222    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12223    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12224    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12225    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12226    252,253,254,255
12227#endif
12228#ifdef SQLITE_EBCDIC
12229      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
12230     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12231     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12232     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12233     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12234     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12235     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12236    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12237    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12238    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12239    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12240    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12241    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12242    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12243    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12244    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12245#endif
12246};
12247
12248/*
12249** The following 256 byte lookup table is used to support SQLites built-in
12250** equivalents to the following standard library functions:
12251**
12252**   isspace()                        0x01
12253**   isalpha()                        0x02
12254**   isdigit()                        0x04
12255**   isalnum()                        0x06
12256**   isxdigit()                       0x08
12257**   toupper()                        0x20
12258**   SQLite identifier character      0x40
12259**
12260** Bit 0x20 is set if the mapped character requires translation to upper
12261** case. i.e. if the character is a lower-case ASCII character.
12262** If x is a lower-case ASCII character, then its upper-case equivalent
12263** is (x - 0x20). Therefore toupper() can be implemented as:
12264**
12265**   (x & ~(map[x]&0x20))
12266**
12267** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12268** array. tolower() is used more often than toupper() by SQLite.
12269**
12270** Bit 0x40 is set if the character non-alphanumeric and can be used in an
12271** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
12272** non-ASCII UTF character. Hence the test for whether or not a character is
12273** part of an identifier is 0x46.
12274**
12275** SQLite's versions are identical to the standard versions assuming a
12276** locale of "C". They are implemented as macros in sqliteInt.h.
12277*/
12278#ifdef SQLITE_ASCII
12279SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12280  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
12281  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
12282  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
12283  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
12284  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
12285  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
12286  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
12287  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
12288
12289  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
12290  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
12291  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
12292  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
12293  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
12294  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
12295  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
12296  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
12297
12298  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
12299  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
12300  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
12301  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
12302  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
12303  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
12304  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
12305  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
12306
12307  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
12308  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
12309  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
12310  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
12311  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
12312  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
12313  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
12314  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
12315};
12316#endif
12317
12318#ifndef SQLITE_USE_URI
12319# define  SQLITE_USE_URI 0
12320#endif
12321
12322/*
12323** The following singleton contains the global configuration for
12324** the SQLite library.
12325*/
12326SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12327   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
12328   1,                         /* bCoreMutex */
12329   SQLITE_THREADSAFE==1,      /* bFullMutex */
12330   SQLITE_USE_URI,            /* bOpenUri */
12331   0x7ffffffe,                /* mxStrlen */
12332   128,                       /* szLookaside */
12333   500,                       /* nLookaside */
12334   {0,0,0,0,0,0,0,0},         /* m */
12335   {0,0,0,0,0,0,0,0,0},       /* mutex */
12336   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
12337   (void*)0,                  /* pHeap */
12338   0,                         /* nHeap */
12339   0, 0,                      /* mnHeap, mxHeap */
12340   (void*)0,                  /* pScratch */
12341   0,                         /* szScratch */
12342   0,                         /* nScratch */
12343   (void*)0,                  /* pPage */
12344   0,                         /* szPage */
12345   0,                         /* nPage */
12346   0,                         /* mxParserStack */
12347   0,                         /* sharedCacheEnabled */
12348   /* All the rest should always be initialized to zero */
12349   0,                         /* isInit */
12350   0,                         /* inProgress */
12351   0,                         /* isMutexInit */
12352   0,                         /* isMallocInit */
12353   0,                         /* isPCacheInit */
12354   0,                         /* pInitMutex */
12355   0,                         /* nRefInitMutex */
12356   0,                         /* xLog */
12357   0,                         /* pLogArg */
12358   0,                         /* bLocaltimeFault */
12359};
12360
12361
12362/*
12363** Hash table for global functions - functions common to all
12364** database connections.  After initialization, this table is
12365** read-only.
12366*/
12367SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12368
12369/*
12370** Constant tokens for values 0 and 1.
12371*/
12372SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12373   { "0", 1 },
12374   { "1", 1 }
12375};
12376
12377
12378/*
12379** The value of the "pending" byte must be 0x40000000 (1 byte past the
12380** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12381** the database page that contains the pending byte.  It never attempts
12382** to read or write that page.  The pending byte page is set assign
12383** for use by the VFS layers as space for managing file locks.
12384**
12385** During testing, it is often desirable to move the pending byte to
12386** a different position in the file.  This allows code that has to
12387** deal with the pending byte to run on files that are much smaller
12388** than 1 GiB.  The sqlite3_test_control() interface can be used to
12389** move the pending byte.
12390**
12391** IMPORTANT:  Changing the pending byte to any value other than
12392** 0x40000000 results in an incompatible database file format!
12393** Changing the pending byte during operating results in undefined
12394** and dileterious behavior.
12395*/
12396#ifndef SQLITE_OMIT_WSD
12397SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12398#endif
12399
12400/*
12401** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12402** created by mkopcodeh.awk during compilation.  Data is obtained
12403** from the comments following the "case OP_xxxx:" statements in
12404** the vdbe.c file.
12405*/
12406SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12407
12408/************** End of global.c **********************************************/
12409/************** Begin file ctime.c *******************************************/
12410/*
12411** 2010 February 23
12412**
12413** The author disclaims copyright to this source code.  In place of
12414** a legal notice, here is a blessing:
12415**
12416**    May you do good and not evil.
12417**    May you find forgiveness for yourself and forgive others.
12418**    May you share freely, never taking more than you give.
12419**
12420*************************************************************************
12421**
12422** This file implements routines used to report what compile-time options
12423** SQLite was built with.
12424*/
12425
12426#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12427
12428
12429/*
12430** An array of names of all compile-time options.  This array should
12431** be sorted A-Z.
12432**
12433** This array looks large, but in a typical installation actually uses
12434** only a handful of compile-time options, so most times this array is usually
12435** rather short and uses little memory space.
12436*/
12437static const char * const azCompileOpt[] = {
12438
12439/* These macros are provided to "stringify" the value of the define
12440** for those options in which the value is meaningful. */
12441#define CTIMEOPT_VAL_(opt) #opt
12442#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12443
12444#ifdef SQLITE_32BIT_ROWID
12445  "32BIT_ROWID",
12446#endif
12447#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12448  "4_BYTE_ALIGNED_MALLOC",
12449#endif
12450#ifdef SQLITE_CASE_SENSITIVE_LIKE
12451  "CASE_SENSITIVE_LIKE",
12452#endif
12453#ifdef SQLITE_CHECK_PAGES
12454  "CHECK_PAGES",
12455#endif
12456#ifdef SQLITE_COVERAGE_TEST
12457  "COVERAGE_TEST",
12458#endif
12459#ifdef SQLITE_DEBUG
12460  "DEBUG",
12461#endif
12462#ifdef SQLITE_DEFAULT_LOCKING_MODE
12463  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12464#endif
12465#ifdef SQLITE_DISABLE_DIRSYNC
12466  "DISABLE_DIRSYNC",
12467#endif
12468#ifdef SQLITE_DISABLE_LFS
12469  "DISABLE_LFS",
12470#endif
12471#ifdef SQLITE_ENABLE_ATOMIC_WRITE
12472  "ENABLE_ATOMIC_WRITE",
12473#endif
12474#ifdef SQLITE_ENABLE_CEROD
12475  "ENABLE_CEROD",
12476#endif
12477#ifdef SQLITE_ENABLE_COLUMN_METADATA
12478  "ENABLE_COLUMN_METADATA",
12479#endif
12480#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12481  "ENABLE_EXPENSIVE_ASSERT",
12482#endif
12483#ifdef SQLITE_ENABLE_FTS1
12484  "ENABLE_FTS1",
12485#endif
12486#ifdef SQLITE_ENABLE_FTS2
12487  "ENABLE_FTS2",
12488#endif
12489#ifdef SQLITE_ENABLE_FTS3
12490  "ENABLE_FTS3",
12491#endif
12492#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12493  "ENABLE_FTS3_PARENTHESIS",
12494#endif
12495#ifdef SQLITE_ENABLE_FTS4
12496  "ENABLE_FTS4",
12497#endif
12498#ifdef SQLITE_ENABLE_ICU
12499  "ENABLE_ICU",
12500#endif
12501#ifdef SQLITE_ENABLE_IOTRACE
12502  "ENABLE_IOTRACE",
12503#endif
12504#ifdef SQLITE_ENABLE_LOAD_EXTENSION
12505  "ENABLE_LOAD_EXTENSION",
12506#endif
12507#ifdef SQLITE_ENABLE_LOCKING_STYLE
12508  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12509#endif
12510#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12511  "ENABLE_MEMORY_MANAGEMENT",
12512#endif
12513#ifdef SQLITE_ENABLE_MEMSYS3
12514  "ENABLE_MEMSYS3",
12515#endif
12516#ifdef SQLITE_ENABLE_MEMSYS5
12517  "ENABLE_MEMSYS5",
12518#endif
12519#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12520  "ENABLE_OVERSIZE_CELL_CHECK",
12521#endif
12522#ifdef SQLITE_ENABLE_RTREE
12523  "ENABLE_RTREE",
12524#endif
12525#ifdef SQLITE_ENABLE_STAT3
12526  "ENABLE_STAT3",
12527#endif
12528#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12529  "ENABLE_UNLOCK_NOTIFY",
12530#endif
12531#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12532  "ENABLE_UPDATE_DELETE_LIMIT",
12533#endif
12534#ifdef SQLITE_HAS_CODEC
12535  "HAS_CODEC",
12536#endif
12537#ifdef SQLITE_HAVE_ISNAN
12538  "HAVE_ISNAN",
12539#endif
12540#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12541  "HOMEGROWN_RECURSIVE_MUTEX",
12542#endif
12543#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12544  "IGNORE_AFP_LOCK_ERRORS",
12545#endif
12546#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12547  "IGNORE_FLOCK_LOCK_ERRORS",
12548#endif
12549#ifdef SQLITE_INT64_TYPE
12550  "INT64_TYPE",
12551#endif
12552#ifdef SQLITE_LOCK_TRACE
12553  "LOCK_TRACE",
12554#endif
12555#ifdef SQLITE_MAX_SCHEMA_RETRY
12556  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12557#endif
12558#ifdef SQLITE_MEMDEBUG
12559  "MEMDEBUG",
12560#endif
12561#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12562  "MIXED_ENDIAN_64BIT_FLOAT",
12563#endif
12564#ifdef SQLITE_NO_SYNC
12565  "NO_SYNC",
12566#endif
12567#ifdef SQLITE_OMIT_ALTERTABLE
12568  "OMIT_ALTERTABLE",
12569#endif
12570#ifdef SQLITE_OMIT_ANALYZE
12571  "OMIT_ANALYZE",
12572#endif
12573#ifdef SQLITE_OMIT_ATTACH
12574  "OMIT_ATTACH",
12575#endif
12576#ifdef SQLITE_OMIT_AUTHORIZATION
12577  "OMIT_AUTHORIZATION",
12578#endif
12579#ifdef SQLITE_OMIT_AUTOINCREMENT
12580  "OMIT_AUTOINCREMENT",
12581#endif
12582#ifdef SQLITE_OMIT_AUTOINIT
12583  "OMIT_AUTOINIT",
12584#endif
12585#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
12586  "OMIT_AUTOMATIC_INDEX",
12587#endif
12588#ifdef SQLITE_OMIT_AUTORESET
12589  "OMIT_AUTORESET",
12590#endif
12591#ifdef SQLITE_OMIT_AUTOVACUUM
12592  "OMIT_AUTOVACUUM",
12593#endif
12594#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12595  "OMIT_BETWEEN_OPTIMIZATION",
12596#endif
12597#ifdef SQLITE_OMIT_BLOB_LITERAL
12598  "OMIT_BLOB_LITERAL",
12599#endif
12600#ifdef SQLITE_OMIT_BTREECOUNT
12601  "OMIT_BTREECOUNT",
12602#endif
12603#ifdef SQLITE_OMIT_BUILTIN_TEST
12604  "OMIT_BUILTIN_TEST",
12605#endif
12606#ifdef SQLITE_OMIT_CAST
12607  "OMIT_CAST",
12608#endif
12609#ifdef SQLITE_OMIT_CHECK
12610  "OMIT_CHECK",
12611#endif
12612/* // redundant
12613** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12614**   "OMIT_COMPILEOPTION_DIAGS",
12615** #endif
12616*/
12617#ifdef SQLITE_OMIT_COMPLETE
12618  "OMIT_COMPLETE",
12619#endif
12620#ifdef SQLITE_OMIT_COMPOUND_SELECT
12621  "OMIT_COMPOUND_SELECT",
12622#endif
12623#ifdef SQLITE_OMIT_DATETIME_FUNCS
12624  "OMIT_DATETIME_FUNCS",
12625#endif
12626#ifdef SQLITE_OMIT_DECLTYPE
12627  "OMIT_DECLTYPE",
12628#endif
12629#ifdef SQLITE_OMIT_DEPRECATED
12630  "OMIT_DEPRECATED",
12631#endif
12632#ifdef SQLITE_OMIT_DISKIO
12633  "OMIT_DISKIO",
12634#endif
12635#ifdef SQLITE_OMIT_EXPLAIN
12636  "OMIT_EXPLAIN",
12637#endif
12638#ifdef SQLITE_OMIT_FLAG_PRAGMAS
12639  "OMIT_FLAG_PRAGMAS",
12640#endif
12641#ifdef SQLITE_OMIT_FLOATING_POINT
12642  "OMIT_FLOATING_POINT",
12643#endif
12644#ifdef SQLITE_OMIT_FOREIGN_KEY
12645  "OMIT_FOREIGN_KEY",
12646#endif
12647#ifdef SQLITE_OMIT_GET_TABLE
12648  "OMIT_GET_TABLE",
12649#endif
12650#ifdef SQLITE_OMIT_INCRBLOB
12651  "OMIT_INCRBLOB",
12652#endif
12653#ifdef SQLITE_OMIT_INTEGRITY_CHECK
12654  "OMIT_INTEGRITY_CHECK",
12655#endif
12656#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12657  "OMIT_LIKE_OPTIMIZATION",
12658#endif
12659#ifdef SQLITE_OMIT_LOAD_EXTENSION
12660  "OMIT_LOAD_EXTENSION",
12661#endif
12662#ifdef SQLITE_OMIT_LOCALTIME
12663  "OMIT_LOCALTIME",
12664#endif
12665#ifdef SQLITE_OMIT_LOOKASIDE
12666  "OMIT_LOOKASIDE",
12667#endif
12668#ifdef SQLITE_OMIT_MEMORYDB
12669  "OMIT_MEMORYDB",
12670#endif
12671#ifdef SQLITE_OMIT_MERGE_SORT
12672  "OMIT_MERGE_SORT",
12673#endif
12674#ifdef SQLITE_OMIT_OR_OPTIMIZATION
12675  "OMIT_OR_OPTIMIZATION",
12676#endif
12677#ifdef SQLITE_OMIT_PAGER_PRAGMAS
12678  "OMIT_PAGER_PRAGMAS",
12679#endif
12680#ifdef SQLITE_OMIT_PRAGMA
12681  "OMIT_PRAGMA",
12682#endif
12683#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12684  "OMIT_PROGRESS_CALLBACK",
12685#endif
12686#ifdef SQLITE_OMIT_QUICKBALANCE
12687  "OMIT_QUICKBALANCE",
12688#endif
12689#ifdef SQLITE_OMIT_REINDEX
12690  "OMIT_REINDEX",
12691#endif
12692#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12693  "OMIT_SCHEMA_PRAGMAS",
12694#endif
12695#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12696  "OMIT_SCHEMA_VERSION_PRAGMAS",
12697#endif
12698#ifdef SQLITE_OMIT_SHARED_CACHE
12699  "OMIT_SHARED_CACHE",
12700#endif
12701#ifdef SQLITE_OMIT_SUBQUERY
12702  "OMIT_SUBQUERY",
12703#endif
12704#ifdef SQLITE_OMIT_TCL_VARIABLE
12705  "OMIT_TCL_VARIABLE",
12706#endif
12707#ifdef SQLITE_OMIT_TEMPDB
12708  "OMIT_TEMPDB",
12709#endif
12710#ifdef SQLITE_OMIT_TRACE
12711  "OMIT_TRACE",
12712#endif
12713#ifdef SQLITE_OMIT_TRIGGER
12714  "OMIT_TRIGGER",
12715#endif
12716#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12717  "OMIT_TRUNCATE_OPTIMIZATION",
12718#endif
12719#ifdef SQLITE_OMIT_UTF16
12720  "OMIT_UTF16",
12721#endif
12722#ifdef SQLITE_OMIT_VACUUM
12723  "OMIT_VACUUM",
12724#endif
12725#ifdef SQLITE_OMIT_VIEW
12726  "OMIT_VIEW",
12727#endif
12728#ifdef SQLITE_OMIT_VIRTUALTABLE
12729  "OMIT_VIRTUALTABLE",
12730#endif
12731#ifdef SQLITE_OMIT_WAL
12732  "OMIT_WAL",
12733#endif
12734#ifdef SQLITE_OMIT_WSD
12735  "OMIT_WSD",
12736#endif
12737#ifdef SQLITE_OMIT_XFER_OPT
12738  "OMIT_XFER_OPT",
12739#endif
12740#ifdef SQLITE_PERFORMANCE_TRACE
12741  "PERFORMANCE_TRACE",
12742#endif
12743#ifdef SQLITE_PROXY_DEBUG
12744  "PROXY_DEBUG",
12745#endif
12746#ifdef SQLITE_SECURE_DELETE
12747  "SECURE_DELETE",
12748#endif
12749#ifdef SQLITE_SMALL_STACK
12750  "SMALL_STACK",
12751#endif
12752#ifdef SQLITE_SOUNDEX
12753  "SOUNDEX",
12754#endif
12755#ifdef SQLITE_TCL
12756  "TCL",
12757#endif
12758#ifdef SQLITE_TEMP_STORE
12759  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12760#endif
12761#ifdef SQLITE_TEST
12762  "TEST",
12763#endif
12764#ifdef SQLITE_THREADSAFE
12765  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12766#endif
12767#ifdef SQLITE_USE_ALLOCA
12768  "USE_ALLOCA",
12769#endif
12770#ifdef SQLITE_ZERO_MALLOC
12771  "ZERO_MALLOC"
12772#endif
12773};
12774
12775/*
12776** Given the name of a compile-time option, return true if that option
12777** was used and false if not.
12778**
12779** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12780** is not required for a match.
12781*/
12782SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12783  int i, n;
12784  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12785  n = sqlite3Strlen30(zOptName);
12786
12787  /* Since ArraySize(azCompileOpt) is normally in single digits, a
12788  ** linear search is adequate.  No need for a binary search. */
12789  for(i=0; i<ArraySize(azCompileOpt); i++){
12790    if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12791       && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12792  }
12793  return 0;
12794}
12795
12796/*
12797** Return the N-th compile-time option string.  If N is out of range,
12798** return a NULL pointer.
12799*/
12800SQLITE_API const char *sqlite3_compileoption_get(int N){
12801  if( N>=0 && N<ArraySize(azCompileOpt) ){
12802    return azCompileOpt[N];
12803  }
12804  return 0;
12805}
12806
12807#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12808
12809/************** End of ctime.c ***********************************************/
12810/************** Begin file status.c ******************************************/
12811/*
12812** 2008 June 18
12813**
12814** The author disclaims copyright to this source code.  In place of
12815** a legal notice, here is a blessing:
12816**
12817**    May you do good and not evil.
12818**    May you find forgiveness for yourself and forgive others.
12819**    May you share freely, never taking more than you give.
12820**
12821*************************************************************************
12822**
12823** This module implements the sqlite3_status() interface and related
12824** functionality.
12825*/
12826/************** Include vdbeInt.h in the middle of status.c ******************/
12827/************** Begin file vdbeInt.h *****************************************/
12828/*
12829** 2003 September 6
12830**
12831** The author disclaims copyright to this source code.  In place of
12832** a legal notice, here is a blessing:
12833**
12834**    May you do good and not evil.
12835**    May you find forgiveness for yourself and forgive others.
12836**    May you share freely, never taking more than you give.
12837**
12838*************************************************************************
12839** This is the header file for information that is private to the
12840** VDBE.  This information used to all be at the top of the single
12841** source code file "vdbe.c".  When that file became too big (over
12842** 6000 lines long) it was split up into several smaller files and
12843** this header information was factored out.
12844*/
12845#ifndef _VDBEINT_H_
12846#define _VDBEINT_H_
12847
12848/*
12849** SQL is translated into a sequence of instructions to be
12850** executed by a virtual machine.  Each instruction is an instance
12851** of the following structure.
12852*/
12853typedef struct VdbeOp Op;
12854
12855/*
12856** Boolean values
12857*/
12858typedef unsigned char Bool;
12859
12860/* Opaque type used by code in vdbesort.c */
12861typedef struct VdbeSorter VdbeSorter;
12862
12863/* Opaque type used by the explainer */
12864typedef struct Explain Explain;
12865
12866/*
12867** A cursor is a pointer into a single BTree within a database file.
12868** The cursor can seek to a BTree entry with a particular key, or
12869** loop over all entries of the Btree.  You can also insert new BTree
12870** entries or retrieve the key or data from the entry that the cursor
12871** is currently pointing to.
12872**
12873** Every cursor that the virtual machine has open is represented by an
12874** instance of the following structure.
12875*/
12876struct VdbeCursor {
12877  BtCursor *pCursor;    /* The cursor structure of the backend */
12878  Btree *pBt;           /* Separate file holding temporary table */
12879  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
12880  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
12881  int pseudoTableReg;   /* Register holding pseudotable content. */
12882  int nField;           /* Number of fields in the header */
12883  Bool zeroed;          /* True if zeroed out and ready for reuse */
12884  Bool rowidIsValid;    /* True if lastRowid is valid */
12885  Bool atFirst;         /* True if pointing to first entry */
12886  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
12887  Bool nullRow;         /* True if pointing to a row with no data */
12888  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
12889  Bool isTable;         /* True if a table requiring integer keys */
12890  Bool isIndex;         /* True if an index containing keys only - no data */
12891  Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
12892  Bool isSorter;        /* True if a new-style sorter */
12893  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
12894  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
12895  i64 seqCount;         /* Sequence counter */
12896  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
12897  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
12898  VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
12899
12900  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
12901  ** OP_IsUnique opcode on this cursor. */
12902  int seekResult;
12903
12904  /* Cached information about the header for the data record that the
12905  ** cursor is currently pointing to.  Only valid if cacheStatus matches
12906  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
12907  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12908  ** the cache is out of date.
12909  **
12910  ** aRow might point to (ephemeral) data for the current row, or it might
12911  ** be NULL.
12912  */
12913  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
12914  int payloadSize;      /* Total number of bytes in the record */
12915  u32 *aType;           /* Type values for all entries in the record */
12916  u32 *aOffset;         /* Cached offsets to the start of each columns data */
12917  u8 *aRow;             /* Data for the current row, if all on one page */
12918};
12919typedef struct VdbeCursor VdbeCursor;
12920
12921/*
12922** When a sub-program is executed (OP_Program), a structure of this type
12923** is allocated to store the current value of the program counter, as
12924** well as the current memory cell array and various other frame specific
12925** values stored in the Vdbe struct. When the sub-program is finished,
12926** these values are copied back to the Vdbe from the VdbeFrame structure,
12927** restoring the state of the VM to as it was before the sub-program
12928** began executing.
12929**
12930** The memory for a VdbeFrame object is allocated and managed by a memory
12931** cell in the parent (calling) frame. When the memory cell is deleted or
12932** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12933** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12934** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12935** this instead of deleting the VdbeFrame immediately is to avoid recursive
12936** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12937** child frame are released.
12938**
12939** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12940** set to NULL if the currently executing frame is the main program.
12941*/
12942typedef struct VdbeFrame VdbeFrame;
12943struct VdbeFrame {
12944  Vdbe *v;                /* VM this frame belongs to */
12945  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
12946  Op *aOp;                /* Program instructions for parent frame */
12947  Mem *aMem;              /* Array of memory cells for parent frame */
12948  u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
12949  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
12950  void *token;            /* Copy of SubProgram.token */
12951  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
12952  u16 nCursor;            /* Number of entries in apCsr */
12953  int pc;                 /* Program Counter in parent (calling) frame */
12954  int nOp;                /* Size of aOp array */
12955  int nMem;               /* Number of entries in aMem */
12956  int nOnceFlag;          /* Number of entries in aOnceFlag */
12957  int nChildMem;          /* Number of memory cells for child frame */
12958  int nChildCsr;          /* Number of cursors for child frame */
12959  int nChange;            /* Statement changes (Vdbe.nChanges)     */
12960};
12961
12962#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12963
12964/*
12965** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12966*/
12967#define CACHE_STALE 0
12968
12969/*
12970** Internally, the vdbe manipulates nearly all SQL values as Mem
12971** structures. Each Mem struct may cache multiple representations (string,
12972** integer etc.) of the same value.
12973*/
12974struct Mem {
12975  sqlite3 *db;        /* The associated database connection */
12976  char *z;            /* String or BLOB value */
12977  double r;           /* Real value */
12978  union {
12979    i64 i;              /* Integer value used when MEM_Int is set in flags */
12980    int nZero;          /* Used when bit MEM_Zero is set in flags */
12981    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
12982    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
12983    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
12984  } u;
12985  int n;              /* Number of characters in string value, excluding '\0' */
12986  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12987  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12988  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12989#ifdef SQLITE_DEBUG
12990  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
12991  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
12992#endif
12993  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
12994  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
12995};
12996
12997/* One or more of the following flags are set to indicate the validOK
12998** representations of the value stored in the Mem struct.
12999**
13000** If the MEM_Null flag is set, then the value is an SQL NULL value.
13001** No other flags may be set in this case.
13002**
13003** If the MEM_Str flag is set then Mem.z points at a string representation.
13004** Usually this is encoded in the same unicode encoding as the main
13005** database (see below for exceptions). If the MEM_Term flag is also
13006** set, then the string is nul terminated. The MEM_Int and MEM_Real
13007** flags may coexist with the MEM_Str flag.
13008*/
13009#define MEM_Null      0x0001   /* Value is NULL */
13010#define MEM_Str       0x0002   /* Value is a string */
13011#define MEM_Int       0x0004   /* Value is an integer */
13012#define MEM_Real      0x0008   /* Value is a real number */
13013#define MEM_Blob      0x0010   /* Value is a BLOB */
13014#define MEM_RowSet    0x0020   /* Value is a RowSet object */
13015#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
13016#define MEM_Invalid   0x0080   /* Value is undefined */
13017#define MEM_TypeMask  0x00ff   /* Mask of type bits */
13018
13019/* Whenever Mem contains a valid string or blob representation, one of
13020** the following flags must be set to determine the memory management
13021** policy for Mem.z.  The MEM_Term flag tells us whether or not the
13022** string is \000 or \u0000 terminated
13023*/
13024#define MEM_Term      0x0200   /* String rep is nul terminated */
13025#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
13026#define MEM_Static    0x0800   /* Mem.z points to a static string */
13027#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
13028#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
13029#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
13030#ifdef SQLITE_OMIT_INCRBLOB
13031  #undef MEM_Zero
13032  #define MEM_Zero 0x0000
13033#endif
13034
13035/*
13036** Clear any existing type flags from a Mem and replace them with f
13037*/
13038#define MemSetTypeFlag(p, f) \
13039   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13040
13041/*
13042** Return true if a memory cell is not marked as invalid.  This macro
13043** is for use inside assert() statements only.
13044*/
13045#ifdef SQLITE_DEBUG
13046#define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
13047#endif
13048
13049
13050/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
13051** additional information about auxiliary information bound to arguments
13052** of the function.  This is used to implement the sqlite3_get_auxdata()
13053** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
13054** that can be associated with a constant argument to a function.  This
13055** allows functions such as "regexp" to compile their constant regular
13056** expression argument once and reused the compiled code for multiple
13057** invocations.
13058*/
13059struct VdbeFunc {
13060  FuncDef *pFunc;               /* The definition of the function */
13061  int nAux;                     /* Number of entries allocated for apAux[] */
13062  struct AuxData {
13063    void *pAux;                   /* Aux data for the i-th argument */
13064    void (*xDelete)(void *);      /* Destructor for the aux data */
13065  } apAux[1];                   /* One slot for each function argument */
13066};
13067
13068/*
13069** The "context" argument for a installable function.  A pointer to an
13070** instance of this structure is the first argument to the routines used
13071** implement the SQL functions.
13072**
13073** There is a typedef for this structure in sqlite.h.  So all routines,
13074** even the public interface to SQLite, can use a pointer to this structure.
13075** But this file is the only place where the internal details of this
13076** structure are known.
13077**
13078** This structure is defined inside of vdbeInt.h because it uses substructures
13079** (Mem) which are only defined there.
13080*/
13081struct sqlite3_context {
13082  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
13083  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
13084  Mem s;                /* The return value is stored here */
13085  Mem *pMem;            /* Memory cell used to store aggregate context */
13086  CollSeq *pColl;       /* Collating sequence */
13087  int isError;          /* Error code returned by the function. */
13088  int skipFlag;         /* Skip skip accumulator loading if true */
13089};
13090
13091/*
13092** An Explain object accumulates indented output which is helpful
13093** in describing recursive data structures.
13094*/
13095struct Explain {
13096  Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
13097  StrAccum str;      /* The string being accumulated */
13098  int nIndent;       /* Number of elements in aIndent */
13099  u16 aIndent[100];  /* Levels of indentation */
13100  char zBase[100];   /* Initial space */
13101};
13102
13103/*
13104** An instance of the virtual machine.  This structure contains the complete
13105** state of the virtual machine.
13106**
13107** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13108** is really a pointer to an instance of this structure.
13109**
13110** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13111** any virtual table method invocations made by the vdbe program. It is
13112** set to 2 for xDestroy method calls and 1 for all other methods. This
13113** variable is used for two purposes: to allow xDestroy methods to execute
13114** "DROP TABLE" statements and to prevent some nasty side effects of
13115** malloc failure when SQLite is invoked recursively by a virtual table
13116** method function.
13117*/
13118struct Vdbe {
13119  sqlite3 *db;            /* The database connection that owns this statement */
13120  Op *aOp;                /* Space to hold the virtual machine's program */
13121  Mem *aMem;              /* The memory locations */
13122  Mem **apArg;            /* Arguments to currently executing user function */
13123  Mem *aColName;          /* Column names to return */
13124  Mem *pResultSet;        /* Pointer to an array of results */
13125  int nMem;               /* Number of memory locations currently allocated */
13126  int nOp;                /* Number of instructions in the program */
13127  int nOpAlloc;           /* Number of slots allocated for aOp[] */
13128  int nLabel;             /* Number of labels used */
13129  int *aLabel;            /* Space to hold the labels */
13130  u16 nResColumn;         /* Number of columns in one row of the result set */
13131  u16 nCursor;            /* Number of slots in apCsr[] */
13132  u32 magic;              /* Magic number for sanity checking */
13133  char *zErrMsg;          /* Error message written here */
13134  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
13135  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
13136  Mem *aVar;              /* Values for the OP_Variable opcode. */
13137  char **azVar;           /* Name of variables */
13138  ynVar nVar;             /* Number of entries in aVar[] */
13139  ynVar nzVar;            /* Number of entries in azVar[] */
13140  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
13141  int pc;                 /* The program counter */
13142  int rc;                 /* Value to return */
13143  u8 errorAction;         /* Recovery action to do in case of an error */
13144  u8 explain;             /* True if EXPLAIN present on SQL command */
13145  u8 changeCntOn;         /* True to update the change-counter */
13146  u8 expired;             /* True if the VM needs to be recompiled */
13147  u8 runOnlyOnce;         /* Automatically expire on reset */
13148  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
13149  u8 inVtabMethod;        /* See comments above */
13150  u8 usesStmtJournal;     /* True if uses a statement journal */
13151  u8 readOnly;            /* True for read-only statements */
13152  u8 isPrepareV2;         /* True if prepared with prepare_v2() */
13153  int nChange;            /* Number of db changes made since last reset */
13154  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
13155  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
13156  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
13157  int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
13158#ifndef SQLITE_OMIT_TRACE
13159  i64 startTime;          /* Time when query started - used for profiling */
13160#endif
13161  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
13162  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
13163  char *zSql;             /* Text of the SQL statement that generated this */
13164  void *pFree;            /* Free this when deleting the vdbe */
13165#ifdef SQLITE_DEBUG
13166  FILE *trace;            /* Write an execution trace here, if not NULL */
13167#endif
13168#ifdef SQLITE_ENABLE_TREE_EXPLAIN
13169  Explain *pExplain;      /* The explainer */
13170  char *zExplain;         /* Explanation of data structures */
13171#endif
13172  VdbeFrame *pFrame;      /* Parent frame */
13173  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
13174  int nFrame;             /* Number of frames in pFrame list */
13175  u32 expmask;            /* Binding to these vars invalidates VM */
13176  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
13177  int nOnceFlag;          /* Size of array aOnceFlag[] */
13178  u8 *aOnceFlag;          /* Flags for OP_Once */
13179};
13180
13181/*
13182** The following are allowed values for Vdbe.magic
13183*/
13184#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
13185#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
13186#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
13187#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
13188
13189/*
13190** Function prototypes
13191*/
13192SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13193void sqliteVdbePopStack(Vdbe*,int);
13194SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13195#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13196SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13197#endif
13198SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13199SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13200SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
13201SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13202SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
13203
13204int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13205SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13206SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13207SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13208SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13209SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13210SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13211SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13212SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13213SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13214SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
13215SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
13216SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
13217SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
13218SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
13219#ifdef SQLITE_OMIT_FLOATING_POINT
13220# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
13221#else
13222SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
13223#endif
13224SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
13225SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
13226SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
13227SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
13228SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
13229SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
13230SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
13231SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
13232SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
13233SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
13234SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
13235SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
13236SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
13237SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
13238#define VdbeMemRelease(X)  \
13239  if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
13240    sqlite3VdbeMemReleaseExternal(X);
13241SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
13242SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
13243SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
13244SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
13245SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
13246SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
13247SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
13248SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
13249
13250#ifdef SQLITE_OMIT_MERGE_SORT
13251# define sqlite3VdbeSorterInit(Y,Z)      SQLITE_OK
13252# define sqlite3VdbeSorterWrite(X,Y,Z)   SQLITE_OK
13253# define sqlite3VdbeSorterClose(Y,Z)
13254# define sqlite3VdbeSorterRowkey(Y,Z)    SQLITE_OK
13255# define sqlite3VdbeSorterRewind(X,Y,Z)  SQLITE_OK
13256# define sqlite3VdbeSorterNext(X,Y,Z)    SQLITE_OK
13257# define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK
13258#else
13259SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13260SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13261SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *, Mem *);
13262SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, VdbeCursor *, int *);
13263SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, VdbeCursor *, int *);
13264SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, VdbeCursor *, Mem *);
13265SQLITE_PRIVATE int sqlite3VdbeSorterCompare(VdbeCursor *, Mem *, int *);
13266#endif
13267
13268#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13269SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
13270SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
13271#else
13272# define sqlite3VdbeEnter(X)
13273# define sqlite3VdbeLeave(X)
13274#endif
13275
13276#ifdef SQLITE_DEBUG
13277SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
13278#endif
13279
13280#ifndef SQLITE_OMIT_FOREIGN_KEY
13281SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13282#else
13283# define sqlite3VdbeCheckFk(p,i) 0
13284#endif
13285
13286SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13287#ifdef SQLITE_DEBUG
13288SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
13289SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13290#endif
13291SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13292
13293#ifndef SQLITE_OMIT_INCRBLOB
13294SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
13295  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
13296#else
13297  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13298  #define ExpandBlob(P) SQLITE_OK
13299#endif
13300
13301#endif /* !defined(_VDBEINT_H_) */
13302
13303/************** End of vdbeInt.h *********************************************/
13304/************** Continuing where we left off in status.c *********************/
13305
13306/*
13307** Variables in which to record status information.
13308*/
13309typedef struct sqlite3StatType sqlite3StatType;
13310static SQLITE_WSD struct sqlite3StatType {
13311  int nowValue[10];         /* Current value */
13312  int mxValue[10];          /* Maximum value */
13313} sqlite3Stat = { {0,}, {0,} };
13314
13315
13316/* The "wsdStat" macro will resolve to the status information
13317** state vector.  If writable static data is unsupported on the target,
13318** we have to locate the state vector at run-time.  In the more common
13319** case where writable static data is supported, wsdStat can refer directly
13320** to the "sqlite3Stat" state vector declared above.
13321*/
13322#ifdef SQLITE_OMIT_WSD
13323# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13324# define wsdStat x[0]
13325#else
13326# define wsdStatInit
13327# define wsdStat sqlite3Stat
13328#endif
13329
13330/*
13331** Return the current value of a status parameter.
13332*/
13333SQLITE_PRIVATE int sqlite3StatusValue(int op){
13334  wsdStatInit;
13335  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13336  return wsdStat.nowValue[op];
13337}
13338
13339/*
13340** Add N to the value of a status record.  It is assumed that the
13341** caller holds appropriate locks.
13342*/
13343SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13344  wsdStatInit;
13345  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13346  wsdStat.nowValue[op] += N;
13347  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13348    wsdStat.mxValue[op] = wsdStat.nowValue[op];
13349  }
13350}
13351
13352/*
13353** Set the value of a status to X.
13354*/
13355SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13356  wsdStatInit;
13357  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13358  wsdStat.nowValue[op] = X;
13359  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13360    wsdStat.mxValue[op] = wsdStat.nowValue[op];
13361  }
13362}
13363
13364/*
13365** Query status information.
13366**
13367** This implementation assumes that reading or writing an aligned
13368** 32-bit integer is an atomic operation.  If that assumption is not true,
13369** then this routine is not threadsafe.
13370*/
13371SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13372  wsdStatInit;
13373  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13374    return SQLITE_MISUSE_BKPT;
13375  }
13376  *pCurrent = wsdStat.nowValue[op];
13377  *pHighwater = wsdStat.mxValue[op];
13378  if( resetFlag ){
13379    wsdStat.mxValue[op] = wsdStat.nowValue[op];
13380  }
13381  return SQLITE_OK;
13382}
13383
13384/*
13385** Query status information for a single database connection
13386*/
13387SQLITE_API int sqlite3_db_status(
13388  sqlite3 *db,          /* The database connection whose status is desired */
13389  int op,               /* Status verb */
13390  int *pCurrent,        /* Write current value here */
13391  int *pHighwater,      /* Write high-water mark here */
13392  int resetFlag         /* Reset high-water mark if true */
13393){
13394  int rc = SQLITE_OK;   /* Return code */
13395  sqlite3_mutex_enter(db->mutex);
13396  switch( op ){
13397    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13398      *pCurrent = db->lookaside.nOut;
13399      *pHighwater = db->lookaside.mxOut;
13400      if( resetFlag ){
13401        db->lookaside.mxOut = db->lookaside.nOut;
13402      }
13403      break;
13404    }
13405
13406    case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13407    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13408    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13409      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13410      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13411      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13412      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13413      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13414      *pCurrent = 0;
13415      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13416      if( resetFlag ){
13417        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13418      }
13419      break;
13420    }
13421
13422    /*
13423    ** Return an approximation for the amount of memory currently used
13424    ** by all pagers associated with the given database connection.  The
13425    ** highwater mark is meaningless and is returned as zero.
13426    */
13427    case SQLITE_DBSTATUS_CACHE_USED: {
13428      int totalUsed = 0;
13429      int i;
13430      sqlite3BtreeEnterAll(db);
13431      for(i=0; i<db->nDb; i++){
13432        Btree *pBt = db->aDb[i].pBt;
13433        if( pBt ){
13434          Pager *pPager = sqlite3BtreePager(pBt);
13435          totalUsed += sqlite3PagerMemUsed(pPager);
13436        }
13437      }
13438      sqlite3BtreeLeaveAll(db);
13439      *pCurrent = totalUsed;
13440      *pHighwater = 0;
13441      break;
13442    }
13443
13444    /*
13445    ** *pCurrent gets an accurate estimate of the amount of memory used
13446    ** to store the schema for all databases (main, temp, and any ATTACHed
13447    ** databases.  *pHighwater is set to zero.
13448    */
13449    case SQLITE_DBSTATUS_SCHEMA_USED: {
13450      int i;                      /* Used to iterate through schemas */
13451      int nByte = 0;              /* Used to accumulate return value */
13452
13453      sqlite3BtreeEnterAll(db);
13454      db->pnBytesFreed = &nByte;
13455      for(i=0; i<db->nDb; i++){
13456        Schema *pSchema = db->aDb[i].pSchema;
13457        if( ALWAYS(pSchema!=0) ){
13458          HashElem *p;
13459
13460          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13461              pSchema->tblHash.count
13462            + pSchema->trigHash.count
13463            + pSchema->idxHash.count
13464            + pSchema->fkeyHash.count
13465          );
13466          nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13467          nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13468          nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13469          nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13470
13471          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13472            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13473          }
13474          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13475            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13476          }
13477        }
13478      }
13479      db->pnBytesFreed = 0;
13480      sqlite3BtreeLeaveAll(db);
13481
13482      *pHighwater = 0;
13483      *pCurrent = nByte;
13484      break;
13485    }
13486
13487    /*
13488    ** *pCurrent gets an accurate estimate of the amount of memory used
13489    ** to store all prepared statements.
13490    ** *pHighwater is set to zero.
13491    */
13492    case SQLITE_DBSTATUS_STMT_USED: {
13493      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
13494      int nByte = 0;              /* Used to accumulate return value */
13495
13496      db->pnBytesFreed = &nByte;
13497      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13498        sqlite3VdbeDeleteObject(db, pVdbe);
13499      }
13500      db->pnBytesFreed = 0;
13501
13502      *pHighwater = 0;
13503      *pCurrent = nByte;
13504
13505      break;
13506    }
13507
13508    /*
13509    ** Set *pCurrent to the total cache hits or misses encountered by all
13510    ** pagers the database handle is connected to. *pHighwater is always set
13511    ** to zero.
13512    */
13513    case SQLITE_DBSTATUS_CACHE_HIT:
13514    case SQLITE_DBSTATUS_CACHE_MISS: {
13515      int i;
13516      int nRet = 0;
13517      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
13518
13519      for(i=0; i<db->nDb; i++){
13520        if( db->aDb[i].pBt ){
13521          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
13522          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
13523        }
13524      }
13525      *pHighwater = 0;
13526      *pCurrent = nRet;
13527      break;
13528    }
13529
13530    default: {
13531      rc = SQLITE_ERROR;
13532    }
13533  }
13534  sqlite3_mutex_leave(db->mutex);
13535  return rc;
13536}
13537
13538/************** End of status.c **********************************************/
13539/************** Begin file date.c ********************************************/
13540/*
13541** 2003 October 31
13542**
13543** The author disclaims copyright to this source code.  In place of
13544** a legal notice, here is a blessing:
13545**
13546**    May you do good and not evil.
13547**    May you find forgiveness for yourself and forgive others.
13548**    May you share freely, never taking more than you give.
13549**
13550*************************************************************************
13551** This file contains the C functions that implement date and time
13552** functions for SQLite.
13553**
13554** There is only one exported symbol in this file - the function
13555** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13556** All other code has file scope.
13557**
13558** SQLite processes all times and dates as Julian Day numbers.  The
13559** dates and times are stored as the number of days since noon
13560** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13561** calendar system.
13562**
13563** 1970-01-01 00:00:00 is JD 2440587.5
13564** 2000-01-01 00:00:00 is JD 2451544.5
13565**
13566** This implemention requires years to be expressed as a 4-digit number
13567** which means that only dates between 0000-01-01 and 9999-12-31 can
13568** be represented, even though julian day numbers allow a much wider
13569** range of dates.
13570**
13571** The Gregorian calendar system is used for all dates and times,
13572** even those that predate the Gregorian calendar.  Historians usually
13573** use the Julian calendar for dates prior to 1582-10-15 and for some
13574** dates afterwards, depending on locale.  Beware of this difference.
13575**
13576** The conversion algorithms are implemented based on descriptions
13577** in the following text:
13578**
13579**      Jean Meeus
13580**      Astronomical Algorithms, 2nd Edition, 1998
13581**      ISBM 0-943396-61-1
13582**      Willmann-Bell, Inc
13583**      Richmond, Virginia (USA)
13584*/
13585/* #include <stdlib.h> */
13586/* #include <assert.h> */
13587#include <time.h>
13588
13589#ifndef SQLITE_OMIT_DATETIME_FUNCS
13590
13591
13592/*
13593** A structure for holding a single date and time.
13594*/
13595typedef struct DateTime DateTime;
13596struct DateTime {
13597  sqlite3_int64 iJD; /* The julian day number times 86400000 */
13598  int Y, M, D;       /* Year, month, and day */
13599  int h, m;          /* Hour and minutes */
13600  int tz;            /* Timezone offset in minutes */
13601  double s;          /* Seconds */
13602  char validYMD;     /* True (1) if Y,M,D are valid */
13603  char validHMS;     /* True (1) if h,m,s are valid */
13604  char validJD;      /* True (1) if iJD is valid */
13605  char validTZ;      /* True (1) if tz is valid */
13606};
13607
13608
13609/*
13610** Convert zDate into one or more integers.  Additional arguments
13611** come in groups of 5 as follows:
13612**
13613**       N       number of digits in the integer
13614**       min     minimum allowed value of the integer
13615**       max     maximum allowed value of the integer
13616**       nextC   first character after the integer
13617**       pVal    where to write the integers value.
13618**
13619** Conversions continue until one with nextC==0 is encountered.
13620** The function returns the number of successful conversions.
13621*/
13622static int getDigits(const char *zDate, ...){
13623  va_list ap;
13624  int val;
13625  int N;
13626  int min;
13627  int max;
13628  int nextC;
13629  int *pVal;
13630  int cnt = 0;
13631  va_start(ap, zDate);
13632  do{
13633    N = va_arg(ap, int);
13634    min = va_arg(ap, int);
13635    max = va_arg(ap, int);
13636    nextC = va_arg(ap, int);
13637    pVal = va_arg(ap, int*);
13638    val = 0;
13639    while( N-- ){
13640      if( !sqlite3Isdigit(*zDate) ){
13641        goto end_getDigits;
13642      }
13643      val = val*10 + *zDate - '0';
13644      zDate++;
13645    }
13646    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
13647      goto end_getDigits;
13648    }
13649    *pVal = val;
13650    zDate++;
13651    cnt++;
13652  }while( nextC );
13653end_getDigits:
13654  va_end(ap);
13655  return cnt;
13656}
13657
13658/*
13659** Parse a timezone extension on the end of a date-time.
13660** The extension is of the form:
13661**
13662**        (+/-)HH:MM
13663**
13664** Or the "zulu" notation:
13665**
13666**        Z
13667**
13668** If the parse is successful, write the number of minutes
13669** of change in p->tz and return 0.  If a parser error occurs,
13670** return non-zero.
13671**
13672** A missing specifier is not considered an error.
13673*/
13674static int parseTimezone(const char *zDate, DateTime *p){
13675  int sgn = 0;
13676  int nHr, nMn;
13677  int c;
13678  while( sqlite3Isspace(*zDate) ){ zDate++; }
13679  p->tz = 0;
13680  c = *zDate;
13681  if( c=='-' ){
13682    sgn = -1;
13683  }else if( c=='+' ){
13684    sgn = +1;
13685  }else if( c=='Z' || c=='z' ){
13686    zDate++;
13687    goto zulu_time;
13688  }else{
13689    return c!=0;
13690  }
13691  zDate++;
13692  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13693    return 1;
13694  }
13695  zDate += 5;
13696  p->tz = sgn*(nMn + nHr*60);
13697zulu_time:
13698  while( sqlite3Isspace(*zDate) ){ zDate++; }
13699  return *zDate!=0;
13700}
13701
13702/*
13703** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13704** The HH, MM, and SS must each be exactly 2 digits.  The
13705** fractional seconds FFFF can be one or more digits.
13706**
13707** Return 1 if there is a parsing error and 0 on success.
13708*/
13709static int parseHhMmSs(const char *zDate, DateTime *p){
13710  int h, m, s;
13711  double ms = 0.0;
13712  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13713    return 1;
13714  }
13715  zDate += 5;
13716  if( *zDate==':' ){
13717    zDate++;
13718    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13719      return 1;
13720    }
13721    zDate += 2;
13722    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13723      double rScale = 1.0;
13724      zDate++;
13725      while( sqlite3Isdigit(*zDate) ){
13726        ms = ms*10.0 + *zDate - '0';
13727        rScale *= 10.0;
13728        zDate++;
13729      }
13730      ms /= rScale;
13731    }
13732  }else{
13733    s = 0;
13734  }
13735  p->validJD = 0;
13736  p->validHMS = 1;
13737  p->h = h;
13738  p->m = m;
13739  p->s = s + ms;
13740  if( parseTimezone(zDate, p) ) return 1;
13741  p->validTZ = (p->tz!=0)?1:0;
13742  return 0;
13743}
13744
13745/*
13746** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
13747** that the YYYY-MM-DD is according to the Gregorian calendar.
13748**
13749** Reference:  Meeus page 61
13750*/
13751static void computeJD(DateTime *p){
13752  int Y, M, D, A, B, X1, X2;
13753
13754  if( p->validJD ) return;
13755  if( p->validYMD ){
13756    Y = p->Y;
13757    M = p->M;
13758    D = p->D;
13759  }else{
13760    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
13761    M = 1;
13762    D = 1;
13763  }
13764  if( M<=2 ){
13765    Y--;
13766    M += 12;
13767  }
13768  A = Y/100;
13769  B = 2 - A + (A/4);
13770  X1 = 36525*(Y+4716)/100;
13771  X2 = 306001*(M+1)/10000;
13772  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13773  p->validJD = 1;
13774  if( p->validHMS ){
13775    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13776    if( p->validTZ ){
13777      p->iJD -= p->tz*60000;
13778      p->validYMD = 0;
13779      p->validHMS = 0;
13780      p->validTZ = 0;
13781    }
13782  }
13783}
13784
13785/*
13786** Parse dates of the form
13787**
13788**     YYYY-MM-DD HH:MM:SS.FFF
13789**     YYYY-MM-DD HH:MM:SS
13790**     YYYY-MM-DD HH:MM
13791**     YYYY-MM-DD
13792**
13793** Write the result into the DateTime structure and return 0
13794** on success and 1 if the input string is not a well-formed
13795** date.
13796*/
13797static int parseYyyyMmDd(const char *zDate, DateTime *p){
13798  int Y, M, D, neg;
13799
13800  if( zDate[0]=='-' ){
13801    zDate++;
13802    neg = 1;
13803  }else{
13804    neg = 0;
13805  }
13806  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13807    return 1;
13808  }
13809  zDate += 10;
13810  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13811  if( parseHhMmSs(zDate, p)==0 ){
13812    /* We got the time */
13813  }else if( *zDate==0 ){
13814    p->validHMS = 0;
13815  }else{
13816    return 1;
13817  }
13818  p->validJD = 0;
13819  p->validYMD = 1;
13820  p->Y = neg ? -Y : Y;
13821  p->M = M;
13822  p->D = D;
13823  if( p->validTZ ){
13824    computeJD(p);
13825  }
13826  return 0;
13827}
13828
13829/*
13830** Set the time to the current time reported by the VFS.
13831**
13832** Return the number of errors.
13833*/
13834static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13835  sqlite3 *db = sqlite3_context_db_handle(context);
13836  if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
13837    p->validJD = 1;
13838    return 0;
13839  }else{
13840    return 1;
13841  }
13842}
13843
13844/*
13845** Attempt to parse the given string into a Julian Day Number.  Return
13846** the number of errors.
13847**
13848** The following are acceptable forms for the input string:
13849**
13850**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
13851**      DDDD.DD
13852**      now
13853**
13854** In the first form, the +/-HH:MM is always optional.  The fractional
13855** seconds extension (the ".FFF") is optional.  The seconds portion
13856** (":SS.FFF") is option.  The year and date can be omitted as long
13857** as there is a time string.  The time string can be omitted as long
13858** as there is a year and date.
13859*/
13860static int parseDateOrTime(
13861  sqlite3_context *context,
13862  const char *zDate,
13863  DateTime *p
13864){
13865  double r;
13866  if( parseYyyyMmDd(zDate,p)==0 ){
13867    return 0;
13868  }else if( parseHhMmSs(zDate, p)==0 ){
13869    return 0;
13870  }else if( sqlite3StrICmp(zDate,"now")==0){
13871    return setDateTimeToCurrent(context, p);
13872  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13873    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13874    p->validJD = 1;
13875    return 0;
13876  }
13877  return 1;
13878}
13879
13880/*
13881** Compute the Year, Month, and Day from the julian day number.
13882*/
13883static void computeYMD(DateTime *p){
13884  int Z, A, B, C, D, E, X1;
13885  if( p->validYMD ) return;
13886  if( !p->validJD ){
13887    p->Y = 2000;
13888    p->M = 1;
13889    p->D = 1;
13890  }else{
13891    Z = (int)((p->iJD + 43200000)/86400000);
13892    A = (int)((Z - 1867216.25)/36524.25);
13893    A = Z + 1 + A - (A/4);
13894    B = A + 1524;
13895    C = (int)((B - 122.1)/365.25);
13896    D = (36525*C)/100;
13897    E = (int)((B-D)/30.6001);
13898    X1 = (int)(30.6001*E);
13899    p->D = B - D - X1;
13900    p->M = E<14 ? E-1 : E-13;
13901    p->Y = p->M>2 ? C - 4716 : C - 4715;
13902  }
13903  p->validYMD = 1;
13904}
13905
13906/*
13907** Compute the Hour, Minute, and Seconds from the julian day number.
13908*/
13909static void computeHMS(DateTime *p){
13910  int s;
13911  if( p->validHMS ) return;
13912  computeJD(p);
13913  s = (int)((p->iJD + 43200000) % 86400000);
13914  p->s = s/1000.0;
13915  s = (int)p->s;
13916  p->s -= s;
13917  p->h = s/3600;
13918  s -= p->h*3600;
13919  p->m = s/60;
13920  p->s += s - p->m*60;
13921  p->validHMS = 1;
13922}
13923
13924/*
13925** Compute both YMD and HMS
13926*/
13927static void computeYMD_HMS(DateTime *p){
13928  computeYMD(p);
13929  computeHMS(p);
13930}
13931
13932/*
13933** Clear the YMD and HMS and the TZ
13934*/
13935static void clearYMD_HMS_TZ(DateTime *p){
13936  p->validYMD = 0;
13937  p->validHMS = 0;
13938  p->validTZ = 0;
13939}
13940
13941/*
13942** On recent Windows platforms, the localtime_s() function is available
13943** as part of the "Secure CRT". It is essentially equivalent to
13944** localtime_r() available under most POSIX platforms, except that the
13945** order of the parameters is reversed.
13946**
13947** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
13948**
13949** If the user has not indicated to use localtime_r() or localtime_s()
13950** already, check for an MSVC build environment that provides
13951** localtime_s().
13952*/
13953#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
13954     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
13955#define HAVE_LOCALTIME_S 1
13956#endif
13957
13958#ifndef SQLITE_OMIT_LOCALTIME
13959/*
13960** The following routine implements the rough equivalent of localtime_r()
13961** using whatever operating-system specific localtime facility that
13962** is available.  This routine returns 0 on success and
13963** non-zero on any kind of error.
13964**
13965** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
13966** routine will always fail.
13967*/
13968static int osLocaltime(time_t *t, struct tm *pTm){
13969  int rc;
13970#if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
13971      && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
13972  struct tm *pX;
13973#if SQLITE_THREADSAFE>0
13974  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13975#endif
13976  sqlite3_mutex_enter(mutex);
13977  pX = localtime(t);
13978#ifndef SQLITE_OMIT_BUILTIN_TEST
13979  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
13980#endif
13981  if( pX ) *pTm = *pX;
13982  sqlite3_mutex_leave(mutex);
13983  rc = pX==0;
13984#else
13985#ifndef SQLITE_OMIT_BUILTIN_TEST
13986  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
13987#endif
13988#if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
13989  rc = localtime_r(t, pTm)==0;
13990#else
13991  rc = localtime_s(pTm, t);
13992#endif /* HAVE_LOCALTIME_R */
13993#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
13994  return rc;
13995}
13996#endif /* SQLITE_OMIT_LOCALTIME */
13997
13998
13999#ifndef SQLITE_OMIT_LOCALTIME
14000/*
14001** Compute the difference (in milliseconds) between localtime and UTC
14002** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14003** return this value and set *pRc to SQLITE_OK.
14004**
14005** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14006** is undefined in this case.
14007*/
14008static sqlite3_int64 localtimeOffset(
14009  DateTime *p,                    /* Date at which to calculate offset */
14010  sqlite3_context *pCtx,          /* Write error here if one occurs */
14011  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
14012){
14013  DateTime x, y;
14014  time_t t;
14015  struct tm sLocal;
14016
14017  /* Initialize the contents of sLocal to avoid a compiler warning. */
14018  memset(&sLocal, 0, sizeof(sLocal));
14019
14020  x = *p;
14021  computeYMD_HMS(&x);
14022  if( x.Y<1971 || x.Y>=2038 ){
14023    x.Y = 2000;
14024    x.M = 1;
14025    x.D = 1;
14026    x.h = 0;
14027    x.m = 0;
14028    x.s = 0.0;
14029  } else {
14030    int s = (int)(x.s + 0.5);
14031    x.s = s;
14032  }
14033  x.tz = 0;
14034  x.validJD = 0;
14035  computeJD(&x);
14036  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14037  if( osLocaltime(&t, &sLocal) ){
14038    sqlite3_result_error(pCtx, "local time unavailable", -1);
14039    *pRc = SQLITE_ERROR;
14040    return 0;
14041  }
14042  y.Y = sLocal.tm_year + 1900;
14043  y.M = sLocal.tm_mon + 1;
14044  y.D = sLocal.tm_mday;
14045  y.h = sLocal.tm_hour;
14046  y.m = sLocal.tm_min;
14047  y.s = sLocal.tm_sec;
14048  y.validYMD = 1;
14049  y.validHMS = 1;
14050  y.validJD = 0;
14051  y.validTZ = 0;
14052  computeJD(&y);
14053  *pRc = SQLITE_OK;
14054  return y.iJD - x.iJD;
14055}
14056#endif /* SQLITE_OMIT_LOCALTIME */
14057
14058/*
14059** Process a modifier to a date-time stamp.  The modifiers are
14060** as follows:
14061**
14062**     NNN days
14063**     NNN hours
14064**     NNN minutes
14065**     NNN.NNNN seconds
14066**     NNN months
14067**     NNN years
14068**     start of month
14069**     start of year
14070**     start of week
14071**     start of day
14072**     weekday N
14073**     unixepoch
14074**     localtime
14075**     utc
14076**
14077** Return 0 on success and 1 if there is any kind of error. If the error
14078** is in a system call (i.e. localtime()), then an error message is written
14079** to context pCtx. If the error is an unrecognized modifier, no error is
14080** written to pCtx.
14081*/
14082static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14083  int rc = 1;
14084  int n;
14085  double r;
14086  char *z, zBuf[30];
14087  z = zBuf;
14088  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14089    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14090  }
14091  z[n] = 0;
14092  switch( z[0] ){
14093#ifndef SQLITE_OMIT_LOCALTIME
14094    case 'l': {
14095      /*    localtime
14096      **
14097      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14098      ** show local time.
14099      */
14100      if( strcmp(z, "localtime")==0 ){
14101        computeJD(p);
14102        p->iJD += localtimeOffset(p, pCtx, &rc);
14103        clearYMD_HMS_TZ(p);
14104      }
14105      break;
14106    }
14107#endif
14108    case 'u': {
14109      /*
14110      **    unixepoch
14111      **
14112      ** Treat the current value of p->iJD as the number of
14113      ** seconds since 1970.  Convert to a real julian day number.
14114      */
14115      if( strcmp(z, "unixepoch")==0 && p->validJD ){
14116        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14117        clearYMD_HMS_TZ(p);
14118        rc = 0;
14119      }
14120#ifndef SQLITE_OMIT_LOCALTIME
14121      else if( strcmp(z, "utc")==0 ){
14122        sqlite3_int64 c1;
14123        computeJD(p);
14124        c1 = localtimeOffset(p, pCtx, &rc);
14125        if( rc==SQLITE_OK ){
14126          p->iJD -= c1;
14127          clearYMD_HMS_TZ(p);
14128          p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14129        }
14130      }
14131#endif
14132      break;
14133    }
14134    case 'w': {
14135      /*
14136      **    weekday N
14137      **
14138      ** Move the date to the same time on the next occurrence of
14139      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
14140      ** date is already on the appropriate weekday, this is a no-op.
14141      */
14142      if( strncmp(z, "weekday ", 8)==0
14143               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14144               && (n=(int)r)==r && n>=0 && r<7 ){
14145        sqlite3_int64 Z;
14146        computeYMD_HMS(p);
14147        p->validTZ = 0;
14148        p->validJD = 0;
14149        computeJD(p);
14150        Z = ((p->iJD + 129600000)/86400000) % 7;
14151        if( Z>n ) Z -= 7;
14152        p->iJD += (n - Z)*86400000;
14153        clearYMD_HMS_TZ(p);
14154        rc = 0;
14155      }
14156      break;
14157    }
14158    case 's': {
14159      /*
14160      **    start of TTTTT
14161      **
14162      ** Move the date backwards to the beginning of the current day,
14163      ** or month or year.
14164      */
14165      if( strncmp(z, "start of ", 9)!=0 ) break;
14166      z += 9;
14167      computeYMD(p);
14168      p->validHMS = 1;
14169      p->h = p->m = 0;
14170      p->s = 0.0;
14171      p->validTZ = 0;
14172      p->validJD = 0;
14173      if( strcmp(z,"month")==0 ){
14174        p->D = 1;
14175        rc = 0;
14176      }else if( strcmp(z,"year")==0 ){
14177        computeYMD(p);
14178        p->M = 1;
14179        p->D = 1;
14180        rc = 0;
14181      }else if( strcmp(z,"day")==0 ){
14182        rc = 0;
14183      }
14184      break;
14185    }
14186    case '+':
14187    case '-':
14188    case '0':
14189    case '1':
14190    case '2':
14191    case '3':
14192    case '4':
14193    case '5':
14194    case '6':
14195    case '7':
14196    case '8':
14197    case '9': {
14198      double rRounder;
14199      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14200      if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14201        rc = 1;
14202        break;
14203      }
14204      if( z[n]==':' ){
14205        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
14206        ** specified number of hours, minutes, seconds, and fractional seconds
14207        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
14208        ** omitted.
14209        */
14210        const char *z2 = z;
14211        DateTime tx;
14212        sqlite3_int64 day;
14213        if( !sqlite3Isdigit(*z2) ) z2++;
14214        memset(&tx, 0, sizeof(tx));
14215        if( parseHhMmSs(z2, &tx) ) break;
14216        computeJD(&tx);
14217        tx.iJD -= 43200000;
14218        day = tx.iJD/86400000;
14219        tx.iJD -= day*86400000;
14220        if( z[0]=='-' ) tx.iJD = -tx.iJD;
14221        computeJD(p);
14222        clearYMD_HMS_TZ(p);
14223        p->iJD += tx.iJD;
14224        rc = 0;
14225        break;
14226      }
14227      z += n;
14228      while( sqlite3Isspace(*z) ) z++;
14229      n = sqlite3Strlen30(z);
14230      if( n>10 || n<3 ) break;
14231      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
14232      computeJD(p);
14233      rc = 0;
14234      rRounder = r<0 ? -0.5 : +0.5;
14235      if( n==3 && strcmp(z,"day")==0 ){
14236        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
14237      }else if( n==4 && strcmp(z,"hour")==0 ){
14238        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
14239      }else if( n==6 && strcmp(z,"minute")==0 ){
14240        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
14241      }else if( n==6 && strcmp(z,"second")==0 ){
14242        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
14243      }else if( n==5 && strcmp(z,"month")==0 ){
14244        int x, y;
14245        computeYMD_HMS(p);
14246        p->M += (int)r;
14247        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
14248        p->Y += x;
14249        p->M -= x*12;
14250        p->validJD = 0;
14251        computeJD(p);
14252        y = (int)r;
14253        if( y!=r ){
14254          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
14255        }
14256      }else if( n==4 && strcmp(z,"year")==0 ){
14257        int y = (int)r;
14258        computeYMD_HMS(p);
14259        p->Y += y;
14260        p->validJD = 0;
14261        computeJD(p);
14262        if( y!=r ){
14263          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14264        }
14265      }else{
14266        rc = 1;
14267      }
14268      clearYMD_HMS_TZ(p);
14269      break;
14270    }
14271    default: {
14272      break;
14273    }
14274  }
14275  return rc;
14276}
14277
14278/*
14279** Process time function arguments.  argv[0] is a date-time stamp.
14280** argv[1] and following are modifiers.  Parse them all and write
14281** the resulting time into the DateTime structure p.  Return 0
14282** on success and 1 if there are any errors.
14283**
14284** If there are zero parameters (if even argv[0] is undefined)
14285** then assume a default value of "now" for argv[0].
14286*/
14287static int isDate(
14288  sqlite3_context *context,
14289  int argc,
14290  sqlite3_value **argv,
14291  DateTime *p
14292){
14293  int i;
14294  const unsigned char *z;
14295  int eType;
14296  memset(p, 0, sizeof(*p));
14297  if( argc==0 ){
14298    return setDateTimeToCurrent(context, p);
14299  }
14300  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14301                   || eType==SQLITE_INTEGER ){
14302    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14303    p->validJD = 1;
14304  }else{
14305    z = sqlite3_value_text(argv[0]);
14306    if( !z || parseDateOrTime(context, (char*)z, p) ){
14307      return 1;
14308    }
14309  }
14310  for(i=1; i<argc; i++){
14311    z = sqlite3_value_text(argv[i]);
14312    if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14313  }
14314  return 0;
14315}
14316
14317
14318/*
14319** The following routines implement the various date and time functions
14320** of SQLite.
14321*/
14322
14323/*
14324**    julianday( TIMESTRING, MOD, MOD, ...)
14325**
14326** Return the julian day number of the date specified in the arguments
14327*/
14328static void juliandayFunc(
14329  sqlite3_context *context,
14330  int argc,
14331  sqlite3_value **argv
14332){
14333  DateTime x;
14334  if( isDate(context, argc, argv, &x)==0 ){
14335    computeJD(&x);
14336    sqlite3_result_double(context, x.iJD/86400000.0);
14337  }
14338}
14339
14340/*
14341**    datetime( TIMESTRING, MOD, MOD, ...)
14342**
14343** Return YYYY-MM-DD HH:MM:SS
14344*/
14345static void datetimeFunc(
14346  sqlite3_context *context,
14347  int argc,
14348  sqlite3_value **argv
14349){
14350  DateTime x;
14351  if( isDate(context, argc, argv, &x)==0 ){
14352    char zBuf[100];
14353    computeYMD_HMS(&x);
14354    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14355                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14356    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14357  }
14358}
14359
14360/*
14361**    time( TIMESTRING, MOD, MOD, ...)
14362**
14363** Return HH:MM:SS
14364*/
14365static void timeFunc(
14366  sqlite3_context *context,
14367  int argc,
14368  sqlite3_value **argv
14369){
14370  DateTime x;
14371  if( isDate(context, argc, argv, &x)==0 ){
14372    char zBuf[100];
14373    computeHMS(&x);
14374    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14375    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14376  }
14377}
14378
14379/*
14380**    date( TIMESTRING, MOD, MOD, ...)
14381**
14382** Return YYYY-MM-DD
14383*/
14384static void dateFunc(
14385  sqlite3_context *context,
14386  int argc,
14387  sqlite3_value **argv
14388){
14389  DateTime x;
14390  if( isDate(context, argc, argv, &x)==0 ){
14391    char zBuf[100];
14392    computeYMD(&x);
14393    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14394    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14395  }
14396}
14397
14398/*
14399**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14400**
14401** Return a string described by FORMAT.  Conversions as follows:
14402**
14403**   %d  day of month
14404**   %f  ** fractional seconds  SS.SSS
14405**   %H  hour 00-24
14406**   %j  day of year 000-366
14407**   %J  ** Julian day number
14408**   %m  month 01-12
14409**   %M  minute 00-59
14410**   %s  seconds since 1970-01-01
14411**   %S  seconds 00-59
14412**   %w  day of week 0-6  sunday==0
14413**   %W  week of year 00-53
14414**   %Y  year 0000-9999
14415**   %%  %
14416*/
14417static void strftimeFunc(
14418  sqlite3_context *context,
14419  int argc,
14420  sqlite3_value **argv
14421){
14422  DateTime x;
14423  u64 n;
14424  size_t i,j;
14425  char *z;
14426  sqlite3 *db;
14427  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14428  char zBuf[100];
14429  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14430  db = sqlite3_context_db_handle(context);
14431  for(i=0, n=1; zFmt[i]; i++, n++){
14432    if( zFmt[i]=='%' ){
14433      switch( zFmt[i+1] ){
14434        case 'd':
14435        case 'H':
14436        case 'm':
14437        case 'M':
14438        case 'S':
14439        case 'W':
14440          n++;
14441          /* fall thru */
14442        case 'w':
14443        case '%':
14444          break;
14445        case 'f':
14446          n += 8;
14447          break;
14448        case 'j':
14449          n += 3;
14450          break;
14451        case 'Y':
14452          n += 8;
14453          break;
14454        case 's':
14455        case 'J':
14456          n += 50;
14457          break;
14458        default:
14459          return;  /* ERROR.  return a NULL */
14460      }
14461      i++;
14462    }
14463  }
14464  testcase( n==sizeof(zBuf)-1 );
14465  testcase( n==sizeof(zBuf) );
14466  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14467  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14468  if( n<sizeof(zBuf) ){
14469    z = zBuf;
14470  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14471    sqlite3_result_error_toobig(context);
14472    return;
14473  }else{
14474    z = sqlite3DbMallocRaw(db, (int)n);
14475    if( z==0 ){
14476      sqlite3_result_error_nomem(context);
14477      return;
14478    }
14479  }
14480  computeJD(&x);
14481  computeYMD_HMS(&x);
14482  for(i=j=0; zFmt[i]; i++){
14483    if( zFmt[i]!='%' ){
14484      z[j++] = zFmt[i];
14485    }else{
14486      i++;
14487      switch( zFmt[i] ){
14488        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14489        case 'f': {
14490          double s = x.s;
14491          if( s>59.999 ) s = 59.999;
14492          sqlite3_snprintf(7, &z[j],"%06.3f", s);
14493          j += sqlite3Strlen30(&z[j]);
14494          break;
14495        }
14496        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14497        case 'W': /* Fall thru */
14498        case 'j': {
14499          int nDay;             /* Number of days since 1st day of year */
14500          DateTime y = x;
14501          y.validJD = 0;
14502          y.M = 1;
14503          y.D = 1;
14504          computeJD(&y);
14505          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14506          if( zFmt[i]=='W' ){
14507            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14508            wd = (int)(((x.iJD+43200000)/86400000)%7);
14509            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14510            j += 2;
14511          }else{
14512            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14513            j += 3;
14514          }
14515          break;
14516        }
14517        case 'J': {
14518          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14519          j+=sqlite3Strlen30(&z[j]);
14520          break;
14521        }
14522        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14523        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14524        case 's': {
14525          sqlite3_snprintf(30,&z[j],"%lld",
14526                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
14527          j += sqlite3Strlen30(&z[j]);
14528          break;
14529        }
14530        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14531        case 'w': {
14532          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14533          break;
14534        }
14535        case 'Y': {
14536          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14537          break;
14538        }
14539        default:   z[j++] = '%'; break;
14540      }
14541    }
14542  }
14543  z[j] = 0;
14544  sqlite3_result_text(context, z, -1,
14545                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14546}
14547
14548/*
14549** current_time()
14550**
14551** This function returns the same value as time('now').
14552*/
14553static void ctimeFunc(
14554  sqlite3_context *context,
14555  int NotUsed,
14556  sqlite3_value **NotUsed2
14557){
14558  UNUSED_PARAMETER2(NotUsed, NotUsed2);
14559  timeFunc(context, 0, 0);
14560}
14561
14562/*
14563** current_date()
14564**
14565** This function returns the same value as date('now').
14566*/
14567static void cdateFunc(
14568  sqlite3_context *context,
14569  int NotUsed,
14570  sqlite3_value **NotUsed2
14571){
14572  UNUSED_PARAMETER2(NotUsed, NotUsed2);
14573  dateFunc(context, 0, 0);
14574}
14575
14576/*
14577** current_timestamp()
14578**
14579** This function returns the same value as datetime('now').
14580*/
14581static void ctimestampFunc(
14582  sqlite3_context *context,
14583  int NotUsed,
14584  sqlite3_value **NotUsed2
14585){
14586  UNUSED_PARAMETER2(NotUsed, NotUsed2);
14587  datetimeFunc(context, 0, 0);
14588}
14589#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
14590
14591#ifdef SQLITE_OMIT_DATETIME_FUNCS
14592/*
14593** If the library is compiled to omit the full-scale date and time
14594** handling (to get a smaller binary), the following minimal version
14595** of the functions current_time(), current_date() and current_timestamp()
14596** are included instead. This is to support column declarations that
14597** include "DEFAULT CURRENT_TIME" etc.
14598**
14599** This function uses the C-library functions time(), gmtime()
14600** and strftime(). The format string to pass to strftime() is supplied
14601** as the user-data for the function.
14602*/
14603static void currentTimeFunc(
14604  sqlite3_context *context,
14605  int argc,
14606  sqlite3_value **argv
14607){
14608  time_t t;
14609  char *zFormat = (char *)sqlite3_user_data(context);
14610  sqlite3 *db;
14611  sqlite3_int64 iT;
14612  struct tm *pTm;
14613  struct tm sNow;
14614  char zBuf[20];
14615
14616  UNUSED_PARAMETER(argc);
14617  UNUSED_PARAMETER(argv);
14618
14619  db = sqlite3_context_db_handle(context);
14620  if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
14621  t = iT/1000 - 10000*(sqlite3_int64)21086676;
14622#ifdef HAVE_GMTIME_R
14623  pTm = gmtime_r(&t, &sNow);
14624#else
14625  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14626  pTm = gmtime(&t);
14627  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
14628  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14629#endif
14630  if( pTm ){
14631    strftime(zBuf, 20, zFormat, &sNow);
14632    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14633  }
14634}
14635#endif
14636
14637/*
14638** This function registered all of the above C functions as SQL
14639** functions.  This should be the only routine in this file with
14640** external linkage.
14641*/
14642SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
14643  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
14644#ifndef SQLITE_OMIT_DATETIME_FUNCS
14645    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
14646    FUNCTION(date,             -1, 0, 0, dateFunc      ),
14647    FUNCTION(time,             -1, 0, 0, timeFunc      ),
14648    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
14649    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
14650    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
14651    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
14652    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
14653#else
14654    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
14655    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
14656    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
14657#endif
14658  };
14659  int i;
14660  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
14661  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
14662
14663  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
14664    sqlite3FuncDefInsert(pHash, &aFunc[i]);
14665  }
14666}
14667
14668/************** End of date.c ************************************************/
14669/************** Begin file os.c **********************************************/
14670/*
14671** 2005 November 29
14672**
14673** The author disclaims copyright to this source code.  In place of
14674** a legal notice, here is a blessing:
14675**
14676**    May you do good and not evil.
14677**    May you find forgiveness for yourself and forgive others.
14678**    May you share freely, never taking more than you give.
14679**
14680******************************************************************************
14681**
14682** This file contains OS interface code that is common to all
14683** architectures.
14684*/
14685#define _SQLITE_OS_C_ 1
14686#undef _SQLITE_OS_C_
14687
14688/*
14689** The default SQLite sqlite3_vfs implementations do not allocate
14690** memory (actually, os_unix.c allocates a small amount of memory
14691** from within OsOpen()), but some third-party implementations may.
14692** So we test the effects of a malloc() failing and the sqlite3OsXXX()
14693** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
14694**
14695** The following functions are instrumented for malloc() failure
14696** testing:
14697**
14698**     sqlite3OsRead()
14699**     sqlite3OsWrite()
14700**     sqlite3OsSync()
14701**     sqlite3OsFileSize()
14702**     sqlite3OsLock()
14703**     sqlite3OsCheckReservedLock()
14704**     sqlite3OsFileControl()
14705**     sqlite3OsShmMap()
14706**     sqlite3OsOpen()
14707**     sqlite3OsDelete()
14708**     sqlite3OsAccess()
14709**     sqlite3OsFullPathname()
14710**
14711*/
14712#if defined(SQLITE_TEST)
14713SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
14714  #define DO_OS_MALLOC_TEST(x)                                       \
14715  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
14716    void *pTstAlloc = sqlite3Malloc(10);                             \
14717    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
14718    sqlite3_free(pTstAlloc);                                         \
14719  }
14720#else
14721  #define DO_OS_MALLOC_TEST(x)
14722#endif
14723
14724/*
14725** The following routines are convenience wrappers around methods
14726** of the sqlite3_file object.  This is mostly just syntactic sugar. All
14727** of this would be completely automatic if SQLite were coded using
14728** C++ instead of plain old C.
14729*/
14730SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
14731  int rc = SQLITE_OK;
14732  if( pId->pMethods ){
14733    rc = pId->pMethods->xClose(pId);
14734    pId->pMethods = 0;
14735  }
14736  return rc;
14737}
14738SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
14739  DO_OS_MALLOC_TEST(id);
14740  return id->pMethods->xRead(id, pBuf, amt, offset);
14741}
14742SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
14743  DO_OS_MALLOC_TEST(id);
14744  return id->pMethods->xWrite(id, pBuf, amt, offset);
14745}
14746SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
14747  return id->pMethods->xTruncate(id, size);
14748}
14749SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
14750  DO_OS_MALLOC_TEST(id);
14751  return id->pMethods->xSync(id, flags);
14752}
14753SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14754  DO_OS_MALLOC_TEST(id);
14755  return id->pMethods->xFileSize(id, pSize);
14756}
14757SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14758  DO_OS_MALLOC_TEST(id);
14759  return id->pMethods->xLock(id, lockType);
14760}
14761SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14762  return id->pMethods->xUnlock(id, lockType);
14763}
14764SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14765  DO_OS_MALLOC_TEST(id);
14766  return id->pMethods->xCheckReservedLock(id, pResOut);
14767}
14768
14769/*
14770** Use sqlite3OsFileControl() when we are doing something that might fail
14771** and we need to know about the failures.  Use sqlite3OsFileControlHint()
14772** when simply tossing information over the wall to the VFS and we do not
14773** really care if the VFS receives and understands the information since it
14774** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
14775** routine has no return value since the return value would be meaningless.
14776*/
14777SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14778  DO_OS_MALLOC_TEST(id);
14779  return id->pMethods->xFileControl(id, op, pArg);
14780}
14781SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
14782  (void)id->pMethods->xFileControl(id, op, pArg);
14783}
14784
14785SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14786  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14787  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14788}
14789SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14790  return id->pMethods->xDeviceCharacteristics(id);
14791}
14792SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14793  return id->pMethods->xShmLock(id, offset, n, flags);
14794}
14795SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14796  id->pMethods->xShmBarrier(id);
14797}
14798SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14799  return id->pMethods->xShmUnmap(id, deleteFlag);
14800}
14801SQLITE_PRIVATE int sqlite3OsShmMap(
14802  sqlite3_file *id,               /* Database file handle */
14803  int iPage,
14804  int pgsz,
14805  int bExtend,                    /* True to extend file if necessary */
14806  void volatile **pp              /* OUT: Pointer to mapping */
14807){
14808  DO_OS_MALLOC_TEST(id);
14809  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14810}
14811
14812/*
14813** The next group of routines are convenience wrappers around the
14814** VFS methods.
14815*/
14816SQLITE_PRIVATE int sqlite3OsOpen(
14817  sqlite3_vfs *pVfs,
14818  const char *zPath,
14819  sqlite3_file *pFile,
14820  int flags,
14821  int *pFlagsOut
14822){
14823  int rc;
14824  DO_OS_MALLOC_TEST(0);
14825  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14826  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
14827  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14828  ** reaching the VFS. */
14829  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
14830  assert( rc==SQLITE_OK || pFile->pMethods==0 );
14831  return rc;
14832}
14833SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14834  DO_OS_MALLOC_TEST(0);
14835  assert( dirSync==0 || dirSync==1 );
14836  return pVfs->xDelete(pVfs, zPath, dirSync);
14837}
14838SQLITE_PRIVATE int sqlite3OsAccess(
14839  sqlite3_vfs *pVfs,
14840  const char *zPath,
14841  int flags,
14842  int *pResOut
14843){
14844  DO_OS_MALLOC_TEST(0);
14845  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14846}
14847SQLITE_PRIVATE int sqlite3OsFullPathname(
14848  sqlite3_vfs *pVfs,
14849  const char *zPath,
14850  int nPathOut,
14851  char *zPathOut
14852){
14853  DO_OS_MALLOC_TEST(0);
14854  zPathOut[0] = 0;
14855  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14856}
14857#ifndef SQLITE_OMIT_LOAD_EXTENSION
14858SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14859  return pVfs->xDlOpen(pVfs, zPath);
14860}
14861SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14862  pVfs->xDlError(pVfs, nByte, zBufOut);
14863}
14864SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
14865  return pVfs->xDlSym(pVfs, pHdle, zSym);
14866}
14867SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
14868  pVfs->xDlClose(pVfs, pHandle);
14869}
14870#endif /* SQLITE_OMIT_LOAD_EXTENSION */
14871SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14872  return pVfs->xRandomness(pVfs, nByte, zBufOut);
14873}
14874SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
14875  return pVfs->xSleep(pVfs, nMicro);
14876}
14877SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
14878  int rc;
14879  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
14880  ** method to get the current date and time if that method is available
14881  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
14882  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
14883  ** unavailable.
14884  */
14885  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
14886    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
14887  }else{
14888    double r;
14889    rc = pVfs->xCurrentTime(pVfs, &r);
14890    *pTimeOut = (sqlite3_int64)(r*86400000.0);
14891  }
14892  return rc;
14893}
14894
14895SQLITE_PRIVATE int sqlite3OsOpenMalloc(
14896  sqlite3_vfs *pVfs,
14897  const char *zFile,
14898  sqlite3_file **ppFile,
14899  int flags,
14900  int *pOutFlags
14901){
14902  int rc = SQLITE_NOMEM;
14903  sqlite3_file *pFile;
14904  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
14905  if( pFile ){
14906    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
14907    if( rc!=SQLITE_OK ){
14908      sqlite3_free(pFile);
14909    }else{
14910      *ppFile = pFile;
14911    }
14912  }
14913  return rc;
14914}
14915SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
14916  int rc = SQLITE_OK;
14917  assert( pFile );
14918  rc = sqlite3OsClose(pFile);
14919  sqlite3_free(pFile);
14920  return rc;
14921}
14922
14923/*
14924** This function is a wrapper around the OS specific implementation of
14925** sqlite3_os_init(). The purpose of the wrapper is to provide the
14926** ability to simulate a malloc failure, so that the handling of an
14927** error in sqlite3_os_init() by the upper layers can be tested.
14928*/
14929SQLITE_PRIVATE int sqlite3OsInit(void){
14930  void *p = sqlite3_malloc(10);
14931  if( p==0 ) return SQLITE_NOMEM;
14932  sqlite3_free(p);
14933  return sqlite3_os_init();
14934}
14935
14936/*
14937** The list of all registered VFS implementations.
14938*/
14939static sqlite3_vfs * SQLITE_WSD vfsList = 0;
14940#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
14941
14942/*
14943** Locate a VFS by name.  If no name is given, simply return the
14944** first VFS on the list.
14945*/
14946SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
14947  sqlite3_vfs *pVfs = 0;
14948#if SQLITE_THREADSAFE
14949  sqlite3_mutex *mutex;
14950#endif
14951#ifndef SQLITE_OMIT_AUTOINIT
14952  int rc = sqlite3_initialize();
14953  if( rc ) return 0;
14954#endif
14955#if SQLITE_THREADSAFE
14956  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14957#endif
14958  sqlite3_mutex_enter(mutex);
14959  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
14960    if( zVfs==0 ) break;
14961    if( strcmp(zVfs, pVfs->zName)==0 ) break;
14962  }
14963  sqlite3_mutex_leave(mutex);
14964  return pVfs;
14965}
14966
14967/*
14968** Unlink a VFS from the linked list
14969*/
14970static void vfsUnlink(sqlite3_vfs *pVfs){
14971  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
14972  if( pVfs==0 ){
14973    /* No-op */
14974  }else if( vfsList==pVfs ){
14975    vfsList = pVfs->pNext;
14976  }else if( vfsList ){
14977    sqlite3_vfs *p = vfsList;
14978    while( p->pNext && p->pNext!=pVfs ){
14979      p = p->pNext;
14980    }
14981    if( p->pNext==pVfs ){
14982      p->pNext = pVfs->pNext;
14983    }
14984  }
14985}
14986
14987/*
14988** Register a VFS with the system.  It is harmless to register the same
14989** VFS multiple times.  The new VFS becomes the default if makeDflt is
14990** true.
14991*/
14992SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
14993  MUTEX_LOGIC(sqlite3_mutex *mutex;)
14994#ifndef SQLITE_OMIT_AUTOINIT
14995  int rc = sqlite3_initialize();
14996  if( rc ) return rc;
14997#endif
14998  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
14999  sqlite3_mutex_enter(mutex);
15000  vfsUnlink(pVfs);
15001  if( makeDflt || vfsList==0 ){
15002    pVfs->pNext = vfsList;
15003    vfsList = pVfs;
15004  }else{
15005    pVfs->pNext = vfsList->pNext;
15006    vfsList->pNext = pVfs;
15007  }
15008  assert(vfsList);
15009  sqlite3_mutex_leave(mutex);
15010  return SQLITE_OK;
15011}
15012
15013/*
15014** Unregister a VFS so that it is no longer accessible.
15015*/
15016SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15017#if SQLITE_THREADSAFE
15018  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15019#endif
15020  sqlite3_mutex_enter(mutex);
15021  vfsUnlink(pVfs);
15022  sqlite3_mutex_leave(mutex);
15023  return SQLITE_OK;
15024}
15025
15026/************** End of os.c **************************************************/
15027/************** Begin file fault.c *******************************************/
15028/*
15029** 2008 Jan 22
15030**
15031** The author disclaims copyright to this source code.  In place of
15032** a legal notice, here is a blessing:
15033**
15034**    May you do good and not evil.
15035**    May you find forgiveness for yourself and forgive others.
15036**    May you share freely, never taking more than you give.
15037**
15038*************************************************************************
15039**
15040** This file contains code to support the concept of "benign"
15041** malloc failures (when the xMalloc() or xRealloc() method of the
15042** sqlite3_mem_methods structure fails to allocate a block of memory
15043** and returns 0).
15044**
15045** Most malloc failures are non-benign. After they occur, SQLite
15046** abandons the current operation and returns an error code (usually
15047** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15048** fatal. For example, if a malloc fails while resizing a hash table, this
15049** is completely recoverable simply by not carrying out the resize. The
15050** hash table will continue to function normally.  So a malloc failure
15051** during a hash table resize is a benign fault.
15052*/
15053
15054
15055#ifndef SQLITE_OMIT_BUILTIN_TEST
15056
15057/*
15058** Global variables.
15059*/
15060typedef struct BenignMallocHooks BenignMallocHooks;
15061static SQLITE_WSD struct BenignMallocHooks {
15062  void (*xBenignBegin)(void);
15063  void (*xBenignEnd)(void);
15064} sqlite3Hooks = { 0, 0 };
15065
15066/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15067** structure.  If writable static data is unsupported on the target,
15068** we have to locate the state vector at run-time.  In the more common
15069** case where writable static data is supported, wsdHooks can refer directly
15070** to the "sqlite3Hooks" state vector declared above.
15071*/
15072#ifdef SQLITE_OMIT_WSD
15073# define wsdHooksInit \
15074  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15075# define wsdHooks x[0]
15076#else
15077# define wsdHooksInit
15078# define wsdHooks sqlite3Hooks
15079#endif
15080
15081
15082/*
15083** Register hooks to call when sqlite3BeginBenignMalloc() and
15084** sqlite3EndBenignMalloc() are called, respectively.
15085*/
15086SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15087  void (*xBenignBegin)(void),
15088  void (*xBenignEnd)(void)
15089){
15090  wsdHooksInit;
15091  wsdHooks.xBenignBegin = xBenignBegin;
15092  wsdHooks.xBenignEnd = xBenignEnd;
15093}
15094
15095/*
15096** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15097** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15098** indicates that subsequent malloc failures are non-benign.
15099*/
15100SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15101  wsdHooksInit;
15102  if( wsdHooks.xBenignBegin ){
15103    wsdHooks.xBenignBegin();
15104  }
15105}
15106SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15107  wsdHooksInit;
15108  if( wsdHooks.xBenignEnd ){
15109    wsdHooks.xBenignEnd();
15110  }
15111}
15112
15113#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15114
15115/************** End of fault.c ***********************************************/
15116/************** Begin file mem0.c ********************************************/
15117/*
15118** 2008 October 28
15119**
15120** The author disclaims copyright to this source code.  In place of
15121** a legal notice, here is a blessing:
15122**
15123**    May you do good and not evil.
15124**    May you find forgiveness for yourself and forgive others.
15125**    May you share freely, never taking more than you give.
15126**
15127*************************************************************************
15128**
15129** This file contains a no-op memory allocation drivers for use when
15130** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
15131** here always fail.  SQLite will not operate with these drivers.  These
15132** are merely placeholders.  Real drivers must be substituted using
15133** sqlite3_config() before SQLite will operate.
15134*/
15135
15136/*
15137** This version of the memory allocator is the default.  It is
15138** used when no other memory allocator is specified using compile-time
15139** macros.
15140*/
15141#ifdef SQLITE_ZERO_MALLOC
15142
15143/*
15144** No-op versions of all memory allocation routines
15145*/
15146static void *sqlite3MemMalloc(int nByte){ return 0; }
15147static void sqlite3MemFree(void *pPrior){ return; }
15148static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15149static int sqlite3MemSize(void *pPrior){ return 0; }
15150static int sqlite3MemRoundup(int n){ return n; }
15151static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15152static void sqlite3MemShutdown(void *NotUsed){ return; }
15153
15154/*
15155** This routine is the only routine in this file with external linkage.
15156**
15157** Populate the low-level memory allocation function pointers in
15158** sqlite3GlobalConfig.m with pointers to the routines in this file.
15159*/
15160SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15161  static const sqlite3_mem_methods defaultMethods = {
15162     sqlite3MemMalloc,
15163     sqlite3MemFree,
15164     sqlite3MemRealloc,
15165     sqlite3MemSize,
15166     sqlite3MemRoundup,
15167     sqlite3MemInit,
15168     sqlite3MemShutdown,
15169     0
15170  };
15171  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15172}
15173
15174#endif /* SQLITE_ZERO_MALLOC */
15175
15176/************** End of mem0.c ************************************************/
15177/************** Begin file mem1.c ********************************************/
15178/*
15179** 2007 August 14
15180**
15181** The author disclaims copyright to this source code.  In place of
15182** a legal notice, here is a blessing:
15183**
15184**    May you do good and not evil.
15185**    May you find forgiveness for yourself and forgive others.
15186**    May you share freely, never taking more than you give.
15187**
15188*************************************************************************
15189**
15190** This file contains low-level memory allocation drivers for when
15191** SQLite will use the standard C-library malloc/realloc/free interface
15192** to obtain the memory it needs.
15193**
15194** This file contains implementations of the low-level memory allocation
15195** routines specified in the sqlite3_mem_methods object.  The content of
15196** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
15197** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
15198** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
15199** default configuration is to use memory allocation routines in this
15200** file.
15201**
15202** C-preprocessor macro summary:
15203**
15204**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
15205**                                the malloc_usable_size() interface exists
15206**                                on the target platform.  Or, this symbol
15207**                                can be set manually, if desired.
15208**                                If an equivalent interface exists by
15209**                                a different name, using a separate -D
15210**                                option to rename it.
15211**
15212**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
15213**                                memory allocator.  Set this symbol to enable
15214**                                building on older macs.
15215**
15216**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
15217**                                _msize() on windows systems.  This might
15218**                                be necessary when compiling for Delphi,
15219**                                for example.
15220*/
15221
15222/*
15223** This version of the memory allocator is the default.  It is
15224** used when no other memory allocator is specified using compile-time
15225** macros.
15226*/
15227#ifdef SQLITE_SYSTEM_MALLOC
15228
15229/*
15230** The MSVCRT has malloc_usable_size() but it is called _msize().
15231** The use of _msize() is automatic, but can be disabled by compiling
15232** with -DSQLITE_WITHOUT_MSIZE
15233*/
15234#if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
15235# define SQLITE_MALLOCSIZE _msize
15236#endif
15237
15238#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15239
15240/*
15241** Use the zone allocator available on apple products unless the
15242** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
15243*/
15244#include <sys/sysctl.h>
15245#include <malloc/malloc.h>
15246#include <libkern/OSAtomic.h>
15247static malloc_zone_t* _sqliteZone_;
15248#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
15249#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
15250#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
15251#define SQLITE_MALLOCSIZE(x) \
15252        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
15253
15254#else /* if not __APPLE__ */
15255
15256/*
15257** Use standard C library malloc and free on non-Apple systems.
15258** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
15259*/
15260#define SQLITE_MALLOC(x)    malloc(x)
15261#define SQLITE_FREE(x)      free(x)
15262#define SQLITE_REALLOC(x,y) realloc((x),(y))
15263
15264#if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
15265      || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
15266# include <malloc.h>    /* Needed for malloc_usable_size on linux */
15267#endif
15268#ifdef HAVE_MALLOC_USABLE_SIZE
15269# ifndef SQLITE_MALLOCSIZE
15270#  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
15271# endif
15272#else
15273# undef SQLITE_MALLOCSIZE
15274#endif
15275
15276#endif /* __APPLE__ or not __APPLE__ */
15277
15278/*
15279** Like malloc(), but remember the size of the allocation
15280** so that we can find it later using sqlite3MemSize().
15281**
15282** For this low-level routine, we are guaranteed that nByte>0 because
15283** cases of nByte<=0 will be intercepted and dealt with by higher level
15284** routines.
15285*/
15286static void *sqlite3MemMalloc(int nByte){
15287#ifdef SQLITE_MALLOCSIZE
15288  void *p = SQLITE_MALLOC( nByte );
15289  if( p==0 ){
15290    testcase( sqlite3GlobalConfig.xLog!=0 );
15291    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15292  }
15293  return p;
15294#else
15295  sqlite3_int64 *p;
15296  assert( nByte>0 );
15297  nByte = ROUND8(nByte);
15298  p = SQLITE_MALLOC( nByte+8 );
15299  if( p ){
15300    p[0] = nByte;
15301    p++;
15302  }else{
15303    testcase( sqlite3GlobalConfig.xLog!=0 );
15304    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15305  }
15306  return (void *)p;
15307#endif
15308}
15309
15310/*
15311** Like free() but works for allocations obtained from sqlite3MemMalloc()
15312** or sqlite3MemRealloc().
15313**
15314** For this low-level routine, we already know that pPrior!=0 since
15315** cases where pPrior==0 will have been intecepted and dealt with
15316** by higher-level routines.
15317*/
15318static void sqlite3MemFree(void *pPrior){
15319#ifdef SQLITE_MALLOCSIZE
15320  SQLITE_FREE(pPrior);
15321#else
15322  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15323  assert( pPrior!=0 );
15324  p--;
15325  SQLITE_FREE(p);
15326#endif
15327}
15328
15329/*
15330** Report the allocated size of a prior return from xMalloc()
15331** or xRealloc().
15332*/
15333static int sqlite3MemSize(void *pPrior){
15334#ifdef SQLITE_MALLOCSIZE
15335  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
15336#else
15337  sqlite3_int64 *p;
15338  if( pPrior==0 ) return 0;
15339  p = (sqlite3_int64*)pPrior;
15340  p--;
15341  return (int)p[0];
15342#endif
15343}
15344
15345/*
15346** Like realloc().  Resize an allocation previously obtained from
15347** sqlite3MemMalloc().
15348**
15349** For this low-level interface, we know that pPrior!=0.  Cases where
15350** pPrior==0 while have been intercepted by higher-level routine and
15351** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
15352** cases where nByte<=0 will have been intercepted by higher-level
15353** routines and redirected to xFree.
15354*/
15355static void *sqlite3MemRealloc(void *pPrior, int nByte){
15356#ifdef SQLITE_MALLOCSIZE
15357  void *p = SQLITE_REALLOC(pPrior, nByte);
15358  if( p==0 ){
15359    testcase( sqlite3GlobalConfig.xLog!=0 );
15360    sqlite3_log(SQLITE_NOMEM,
15361      "failed memory resize %u to %u bytes",
15362      SQLITE_MALLOCSIZE(pPrior), nByte);
15363  }
15364  return p;
15365#else
15366  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15367  assert( pPrior!=0 && nByte>0 );
15368  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
15369  p--;
15370  p = SQLITE_REALLOC(p, nByte+8 );
15371  if( p ){
15372    p[0] = nByte;
15373    p++;
15374  }else{
15375    testcase( sqlite3GlobalConfig.xLog!=0 );
15376    sqlite3_log(SQLITE_NOMEM,
15377      "failed memory resize %u to %u bytes",
15378      sqlite3MemSize(pPrior), nByte);
15379  }
15380  return (void*)p;
15381#endif
15382}
15383
15384/*
15385** Round up a request size to the next valid allocation size.
15386*/
15387static int sqlite3MemRoundup(int n){
15388  return ROUND8(n);
15389}
15390
15391/*
15392** Initialize this module.
15393*/
15394static int sqlite3MemInit(void *NotUsed){
15395#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15396  int cpuCount;
15397  size_t len;
15398  if( _sqliteZone_ ){
15399    return SQLITE_OK;
15400  }
15401  len = sizeof(cpuCount);
15402  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
15403  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
15404  if( cpuCount>1 ){
15405    /* defer MT decisions to system malloc */
15406    _sqliteZone_ = malloc_default_zone();
15407  }else{
15408    /* only 1 core, use our own zone to contention over global locks,
15409    ** e.g. we have our own dedicated locks */
15410    bool success;
15411    malloc_zone_t* newzone = malloc_create_zone(4096, 0);
15412    malloc_set_zone_name(newzone, "Sqlite_Heap");
15413    do{
15414      success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
15415                                 (void * volatile *)&_sqliteZone_);
15416    }while(!_sqliteZone_);
15417    if( !success ){
15418      /* somebody registered a zone first */
15419      malloc_destroy_zone(newzone);
15420    }
15421  }
15422#endif
15423  UNUSED_PARAMETER(NotUsed);
15424  return SQLITE_OK;
15425}
15426
15427/*
15428** Deinitialize this module.
15429*/
15430static void sqlite3MemShutdown(void *NotUsed){
15431  UNUSED_PARAMETER(NotUsed);
15432  return;
15433}
15434
15435/*
15436** This routine is the only routine in this file with external linkage.
15437**
15438** Populate the low-level memory allocation function pointers in
15439** sqlite3GlobalConfig.m with pointers to the routines in this file.
15440*/
15441SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15442  static const sqlite3_mem_methods defaultMethods = {
15443     sqlite3MemMalloc,
15444     sqlite3MemFree,
15445     sqlite3MemRealloc,
15446     sqlite3MemSize,
15447     sqlite3MemRoundup,
15448     sqlite3MemInit,
15449     sqlite3MemShutdown,
15450     0
15451  };
15452  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15453}
15454
15455#endif /* SQLITE_SYSTEM_MALLOC */
15456
15457/************** End of mem1.c ************************************************/
15458/************** Begin file mem2.c ********************************************/
15459/*
15460** 2007 August 15
15461**
15462** The author disclaims copyright to this source code.  In place of
15463** a legal notice, here is a blessing:
15464**
15465**    May you do good and not evil.
15466**    May you find forgiveness for yourself and forgive others.
15467**    May you share freely, never taking more than you give.
15468**
15469*************************************************************************
15470**
15471** This file contains low-level memory allocation drivers for when
15472** SQLite will use the standard C-library malloc/realloc/free interface
15473** to obtain the memory it needs while adding lots of additional debugging
15474** information to each allocation in order to help detect and fix memory
15475** leaks and memory usage errors.
15476**
15477** This file contains implementations of the low-level memory allocation
15478** routines specified in the sqlite3_mem_methods object.
15479*/
15480
15481/*
15482** This version of the memory allocator is used only if the
15483** SQLITE_MEMDEBUG macro is defined
15484*/
15485#ifdef SQLITE_MEMDEBUG
15486
15487/*
15488** The backtrace functionality is only available with GLIBC
15489*/
15490#ifdef __GLIBC__
15491  extern int backtrace(void**,int);
15492  extern void backtrace_symbols_fd(void*const*,int,int);
15493#else
15494# define backtrace(A,B) 1
15495# define backtrace_symbols_fd(A,B,C)
15496#endif
15497/* #include <stdio.h> */
15498
15499/*
15500** Each memory allocation looks like this:
15501**
15502**  ------------------------------------------------------------------------
15503**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
15504**  ------------------------------------------------------------------------
15505**
15506** The application code sees only a pointer to the allocation.  We have
15507** to back up from the allocation pointer to find the MemBlockHdr.  The
15508** MemBlockHdr tells us the size of the allocation and the number of
15509** backtrace pointers.  There is also a guard word at the end of the
15510** MemBlockHdr.
15511*/
15512struct MemBlockHdr {
15513  i64 iSize;                          /* Size of this allocation */
15514  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
15515  char nBacktrace;                    /* Number of backtraces on this alloc */
15516  char nBacktraceSlots;               /* Available backtrace slots */
15517  u8 nTitle;                          /* Bytes of title; includes '\0' */
15518  u8 eType;                           /* Allocation type code */
15519  int iForeGuard;                     /* Guard word for sanity */
15520};
15521
15522/*
15523** Guard words
15524*/
15525#define FOREGUARD 0x80F5E153
15526#define REARGUARD 0xE4676B53
15527
15528/*
15529** Number of malloc size increments to track.
15530*/
15531#define NCSIZE  1000
15532
15533/*
15534** All of the static variables used by this module are collected
15535** into a single structure named "mem".  This is to keep the
15536** static variables organized and to reduce namespace pollution
15537** when this module is combined with other in the amalgamation.
15538*/
15539static struct {
15540
15541  /*
15542  ** Mutex to control access to the memory allocation subsystem.
15543  */
15544  sqlite3_mutex *mutex;
15545
15546  /*
15547  ** Head and tail of a linked list of all outstanding allocations
15548  */
15549  struct MemBlockHdr *pFirst;
15550  struct MemBlockHdr *pLast;
15551
15552  /*
15553  ** The number of levels of backtrace to save in new allocations.
15554  */
15555  int nBacktrace;
15556  void (*xBacktrace)(int, int, void **);
15557
15558  /*
15559  ** Title text to insert in front of each block
15560  */
15561  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
15562  char zTitle[100];  /* The title text */
15563
15564  /*
15565  ** sqlite3MallocDisallow() increments the following counter.
15566  ** sqlite3MallocAllow() decrements it.
15567  */
15568  int disallow; /* Do not allow memory allocation */
15569
15570  /*
15571  ** Gather statistics on the sizes of memory allocations.
15572  ** nAlloc[i] is the number of allocation attempts of i*8
15573  ** bytes.  i==NCSIZE is the number of allocation attempts for
15574  ** sizes more than NCSIZE*8 bytes.
15575  */
15576  int nAlloc[NCSIZE];      /* Total number of allocations */
15577  int nCurrent[NCSIZE];    /* Current number of allocations */
15578  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
15579
15580} mem;
15581
15582
15583/*
15584** Adjust memory usage statistics
15585*/
15586static void adjustStats(int iSize, int increment){
15587  int i = ROUND8(iSize)/8;
15588  if( i>NCSIZE-1 ){
15589    i = NCSIZE - 1;
15590  }
15591  if( increment>0 ){
15592    mem.nAlloc[i]++;
15593    mem.nCurrent[i]++;
15594    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
15595      mem.mxCurrent[i] = mem.nCurrent[i];
15596    }
15597  }else{
15598    mem.nCurrent[i]--;
15599    assert( mem.nCurrent[i]>=0 );
15600  }
15601}
15602
15603/*
15604** Given an allocation, find the MemBlockHdr for that allocation.
15605**
15606** This routine checks the guards at either end of the allocation and
15607** if they are incorrect it asserts.
15608*/
15609static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
15610  struct MemBlockHdr *p;
15611  int *pInt;
15612  u8 *pU8;
15613  int nReserve;
15614
15615  p = (struct MemBlockHdr*)pAllocation;
15616  p--;
15617  assert( p->iForeGuard==(int)FOREGUARD );
15618  nReserve = ROUND8(p->iSize);
15619  pInt = (int*)pAllocation;
15620  pU8 = (u8*)pAllocation;
15621  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
15622  /* This checks any of the "extra" bytes allocated due
15623  ** to rounding up to an 8 byte boundary to ensure
15624  ** they haven't been overwritten.
15625  */
15626  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
15627  return p;
15628}
15629
15630/*
15631** Return the number of bytes currently allocated at address p.
15632*/
15633static int sqlite3MemSize(void *p){
15634  struct MemBlockHdr *pHdr;
15635  if( !p ){
15636    return 0;
15637  }
15638  pHdr = sqlite3MemsysGetHeader(p);
15639  return pHdr->iSize;
15640}
15641
15642/*
15643** Initialize the memory allocation subsystem.
15644*/
15645static int sqlite3MemInit(void *NotUsed){
15646  UNUSED_PARAMETER(NotUsed);
15647  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
15648  if( !sqlite3GlobalConfig.bMemstat ){
15649    /* If memory status is enabled, then the malloc.c wrapper will already
15650    ** hold the STATIC_MEM mutex when the routines here are invoked. */
15651    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15652  }
15653  return SQLITE_OK;
15654}
15655
15656/*
15657** Deinitialize the memory allocation subsystem.
15658*/
15659static void sqlite3MemShutdown(void *NotUsed){
15660  UNUSED_PARAMETER(NotUsed);
15661  mem.mutex = 0;
15662}
15663
15664/*
15665** Round up a request size to the next valid allocation size.
15666*/
15667static int sqlite3MemRoundup(int n){
15668  return ROUND8(n);
15669}
15670
15671/*
15672** Fill a buffer with pseudo-random bytes.  This is used to preset
15673** the content of a new memory allocation to unpredictable values and
15674** to clear the content of a freed allocation to unpredictable values.
15675*/
15676static void randomFill(char *pBuf, int nByte){
15677  unsigned int x, y, r;
15678  x = SQLITE_PTR_TO_INT(pBuf);
15679  y = nByte | 1;
15680  while( nByte >= 4 ){
15681    x = (x>>1) ^ (-(x&1) & 0xd0000001);
15682    y = y*1103515245 + 12345;
15683    r = x ^ y;
15684    *(int*)pBuf = r;
15685    pBuf += 4;
15686    nByte -= 4;
15687  }
15688  while( nByte-- > 0 ){
15689    x = (x>>1) ^ (-(x&1) & 0xd0000001);
15690    y = y*1103515245 + 12345;
15691    r = x ^ y;
15692    *(pBuf++) = r & 0xff;
15693  }
15694}
15695
15696/*
15697** Allocate nByte bytes of memory.
15698*/
15699static void *sqlite3MemMalloc(int nByte){
15700  struct MemBlockHdr *pHdr;
15701  void **pBt;
15702  char *z;
15703  int *pInt;
15704  void *p = 0;
15705  int totalSize;
15706  int nReserve;
15707  sqlite3_mutex_enter(mem.mutex);
15708  assert( mem.disallow==0 );
15709  nReserve = ROUND8(nByte);
15710  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
15711               mem.nBacktrace*sizeof(void*) + mem.nTitle;
15712  p = malloc(totalSize);
15713  if( p ){
15714    z = p;
15715    pBt = (void**)&z[mem.nTitle];
15716    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
15717    pHdr->pNext = 0;
15718    pHdr->pPrev = mem.pLast;
15719    if( mem.pLast ){
15720      mem.pLast->pNext = pHdr;
15721    }else{
15722      mem.pFirst = pHdr;
15723    }
15724    mem.pLast = pHdr;
15725    pHdr->iForeGuard = FOREGUARD;
15726    pHdr->eType = MEMTYPE_HEAP;
15727    pHdr->nBacktraceSlots = mem.nBacktrace;
15728    pHdr->nTitle = mem.nTitle;
15729    if( mem.nBacktrace ){
15730      void *aAddr[40];
15731      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
15732      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
15733      assert(pBt[0]);
15734      if( mem.xBacktrace ){
15735        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
15736      }
15737    }else{
15738      pHdr->nBacktrace = 0;
15739    }
15740    if( mem.nTitle ){
15741      memcpy(z, mem.zTitle, mem.nTitle);
15742    }
15743    pHdr->iSize = nByte;
15744    adjustStats(nByte, +1);
15745    pInt = (int*)&pHdr[1];
15746    pInt[nReserve/sizeof(int)] = REARGUARD;
15747    randomFill((char*)pInt, nByte);
15748    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
15749    p = (void*)pInt;
15750  }
15751  sqlite3_mutex_leave(mem.mutex);
15752  return p;
15753}
15754
15755/*
15756** Free memory.
15757*/
15758static void sqlite3MemFree(void *pPrior){
15759  struct MemBlockHdr *pHdr;
15760  void **pBt;
15761  char *z;
15762  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
15763       || mem.mutex!=0 );
15764  pHdr = sqlite3MemsysGetHeader(pPrior);
15765  pBt = (void**)pHdr;
15766  pBt -= pHdr->nBacktraceSlots;
15767  sqlite3_mutex_enter(mem.mutex);
15768  if( pHdr->pPrev ){
15769    assert( pHdr->pPrev->pNext==pHdr );
15770    pHdr->pPrev->pNext = pHdr->pNext;
15771  }else{
15772    assert( mem.pFirst==pHdr );
15773    mem.pFirst = pHdr->pNext;
15774  }
15775  if( pHdr->pNext ){
15776    assert( pHdr->pNext->pPrev==pHdr );
15777    pHdr->pNext->pPrev = pHdr->pPrev;
15778  }else{
15779    assert( mem.pLast==pHdr );
15780    mem.pLast = pHdr->pPrev;
15781  }
15782  z = (char*)pBt;
15783  z -= pHdr->nTitle;
15784  adjustStats(pHdr->iSize, -1);
15785  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
15786                pHdr->iSize + sizeof(int) + pHdr->nTitle);
15787  free(z);
15788  sqlite3_mutex_leave(mem.mutex);
15789}
15790
15791/*
15792** Change the size of an existing memory allocation.
15793**
15794** For this debugging implementation, we *always* make a copy of the
15795** allocation into a new place in memory.  In this way, if the
15796** higher level code is using pointer to the old allocation, it is
15797** much more likely to break and we are much more liking to find
15798** the error.
15799*/
15800static void *sqlite3MemRealloc(void *pPrior, int nByte){
15801  struct MemBlockHdr *pOldHdr;
15802  void *pNew;
15803  assert( mem.disallow==0 );
15804  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
15805  pOldHdr = sqlite3MemsysGetHeader(pPrior);
15806  pNew = sqlite3MemMalloc(nByte);
15807  if( pNew ){
15808    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
15809    if( nByte>pOldHdr->iSize ){
15810      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
15811    }
15812    sqlite3MemFree(pPrior);
15813  }
15814  return pNew;
15815}
15816
15817/*
15818** Populate the low-level memory allocation function pointers in
15819** sqlite3GlobalConfig.m with pointers to the routines in this file.
15820*/
15821SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15822  static const sqlite3_mem_methods defaultMethods = {
15823     sqlite3MemMalloc,
15824     sqlite3MemFree,
15825     sqlite3MemRealloc,
15826     sqlite3MemSize,
15827     sqlite3MemRoundup,
15828     sqlite3MemInit,
15829     sqlite3MemShutdown,
15830     0
15831  };
15832  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15833}
15834
15835/*
15836** Set the "type" of an allocation.
15837*/
15838SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
15839  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15840    struct MemBlockHdr *pHdr;
15841    pHdr = sqlite3MemsysGetHeader(p);
15842    assert( pHdr->iForeGuard==FOREGUARD );
15843    pHdr->eType = eType;
15844  }
15845}
15846
15847/*
15848** Return TRUE if the mask of type in eType matches the type of the
15849** allocation p.  Also return true if p==NULL.
15850**
15851** This routine is designed for use within an assert() statement, to
15852** verify the type of an allocation.  For example:
15853**
15854**     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
15855*/
15856SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
15857  int rc = 1;
15858  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15859    struct MemBlockHdr *pHdr;
15860    pHdr = sqlite3MemsysGetHeader(p);
15861    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
15862    if( (pHdr->eType&eType)==0 ){
15863      rc = 0;
15864    }
15865  }
15866  return rc;
15867}
15868
15869/*
15870** Return TRUE if the mask of type in eType matches no bits of the type of the
15871** allocation p.  Also return true if p==NULL.
15872**
15873** This routine is designed for use within an assert() statement, to
15874** verify the type of an allocation.  For example:
15875**
15876**     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
15877*/
15878SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
15879  int rc = 1;
15880  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15881    struct MemBlockHdr *pHdr;
15882    pHdr = sqlite3MemsysGetHeader(p);
15883    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
15884    if( (pHdr->eType&eType)!=0 ){
15885      rc = 0;
15886    }
15887  }
15888  return rc;
15889}
15890
15891/*
15892** Set the number of backtrace levels kept for each allocation.
15893** A value of zero turns off backtracing.  The number is always rounded
15894** up to a multiple of 2.
15895*/
15896SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
15897  if( depth<0 ){ depth = 0; }
15898  if( depth>20 ){ depth = 20; }
15899  depth = (depth+1)&0xfe;
15900  mem.nBacktrace = depth;
15901}
15902
15903SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
15904  mem.xBacktrace = xBacktrace;
15905}
15906
15907/*
15908** Set the title string for subsequent allocations.
15909*/
15910SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
15911  unsigned int n = sqlite3Strlen30(zTitle) + 1;
15912  sqlite3_mutex_enter(mem.mutex);
15913  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
15914  memcpy(mem.zTitle, zTitle, n);
15915  mem.zTitle[n] = 0;
15916  mem.nTitle = ROUND8(n);
15917  sqlite3_mutex_leave(mem.mutex);
15918}
15919
15920SQLITE_PRIVATE void sqlite3MemdebugSync(){
15921  struct MemBlockHdr *pHdr;
15922  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15923    void **pBt = (void**)pHdr;
15924    pBt -= pHdr->nBacktraceSlots;
15925    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
15926  }
15927}
15928
15929/*
15930** Open the file indicated and write a log of all unfreed memory
15931** allocations into that log.
15932*/
15933SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
15934  FILE *out;
15935  struct MemBlockHdr *pHdr;
15936  void **pBt;
15937  int i;
15938  out = fopen(zFilename, "w");
15939  if( out==0 ){
15940    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15941                    zFilename);
15942    return;
15943  }
15944  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15945    char *z = (char*)pHdr;
15946    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
15947    fprintf(out, "**** %lld bytes at %p from %s ****\n",
15948            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
15949    if( pHdr->nBacktrace ){
15950      fflush(out);
15951      pBt = (void**)pHdr;
15952      pBt -= pHdr->nBacktraceSlots;
15953      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
15954      fprintf(out, "\n");
15955    }
15956  }
15957  fprintf(out, "COUNTS:\n");
15958  for(i=0; i<NCSIZE-1; i++){
15959    if( mem.nAlloc[i] ){
15960      fprintf(out, "   %5d: %10d %10d %10d\n",
15961            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
15962    }
15963  }
15964  if( mem.nAlloc[NCSIZE-1] ){
15965    fprintf(out, "   %5d: %10d %10d %10d\n",
15966             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
15967             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
15968  }
15969  fclose(out);
15970}
15971
15972/*
15973** Return the number of times sqlite3MemMalloc() has been called.
15974*/
15975SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
15976  int i;
15977  int nTotal = 0;
15978  for(i=0; i<NCSIZE; i++){
15979    nTotal += mem.nAlloc[i];
15980  }
15981  return nTotal;
15982}
15983
15984
15985#endif /* SQLITE_MEMDEBUG */
15986
15987/************** End of mem2.c ************************************************/
15988/************** Begin file mem3.c ********************************************/
15989/*
15990** 2007 October 14
15991**
15992** The author disclaims copyright to this source code.  In place of
15993** a legal notice, here is a blessing:
15994**
15995**    May you do good and not evil.
15996**    May you find forgiveness for yourself and forgive others.
15997**    May you share freely, never taking more than you give.
15998**
15999*************************************************************************
16000** This file contains the C functions that implement a memory
16001** allocation subsystem for use by SQLite.
16002**
16003** This version of the memory allocation subsystem omits all
16004** use of malloc(). The SQLite user supplies a block of memory
16005** before calling sqlite3_initialize() from which allocations
16006** are made and returned by the xMalloc() and xRealloc()
16007** implementations. Once sqlite3_initialize() has been called,
16008** the amount of memory available to SQLite is fixed and cannot
16009** be changed.
16010**
16011** This version of the memory allocation subsystem is included
16012** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16013*/
16014
16015/*
16016** This version of the memory allocator is only built into the library
16017** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16018** mean that the library will use a memory-pool by default, just that
16019** it is available. The mempool allocator is activated by calling
16020** sqlite3_config().
16021*/
16022#ifdef SQLITE_ENABLE_MEMSYS3
16023
16024/*
16025** Maximum size (in Mem3Blocks) of a "small" chunk.
16026*/
16027#define MX_SMALL 10
16028
16029
16030/*
16031** Number of freelist hash slots
16032*/
16033#define N_HASH  61
16034
16035/*
16036** A memory allocation (also called a "chunk") consists of two or
16037** more blocks where each block is 8 bytes.  The first 8 bytes are
16038** a header that is not returned to the user.
16039**
16040** A chunk is two or more blocks that is either checked out or
16041** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
16042** size of the allocation in blocks if the allocation is free.
16043** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16044** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
16045** is true if the previous chunk is checked out and false if the
16046** previous chunk is free.  The u.hdr.prevSize field is the size of
16047** the previous chunk in blocks if the previous chunk is on the
16048** freelist. If the previous chunk is checked out, then
16049** u.hdr.prevSize can be part of the data for that chunk and should
16050** not be read or written.
16051**
16052** We often identify a chunk by its index in mem3.aPool[].  When
16053** this is done, the chunk index refers to the second block of
16054** the chunk.  In this way, the first chunk has an index of 1.
16055** A chunk index of 0 means "no such chunk" and is the equivalent
16056** of a NULL pointer.
16057**
16058** The second block of free chunks is of the form u.list.  The
16059** two fields form a double-linked list of chunks of related sizes.
16060** Pointers to the head of the list are stored in mem3.aiSmall[]
16061** for smaller chunks and mem3.aiHash[] for larger chunks.
16062**
16063** The second block of a chunk is user data if the chunk is checked
16064** out.  If a chunk is checked out, the user data may extend into
16065** the u.hdr.prevSize value of the following chunk.
16066*/
16067typedef struct Mem3Block Mem3Block;
16068struct Mem3Block {
16069  union {
16070    struct {
16071      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
16072      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
16073    } hdr;
16074    struct {
16075      u32 next;       /* Index in mem3.aPool[] of next free chunk */
16076      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
16077    } list;
16078  } u;
16079};
16080
16081/*
16082** All of the static variables used by this module are collected
16083** into a single structure named "mem3".  This is to keep the
16084** static variables organized and to reduce namespace pollution
16085** when this module is combined with other in the amalgamation.
16086*/
16087static SQLITE_WSD struct Mem3Global {
16088  /*
16089  ** Memory available for allocation. nPool is the size of the array
16090  ** (in Mem3Blocks) pointed to by aPool less 2.
16091  */
16092  u32 nPool;
16093  Mem3Block *aPool;
16094
16095  /*
16096  ** True if we are evaluating an out-of-memory callback.
16097  */
16098  int alarmBusy;
16099
16100  /*
16101  ** Mutex to control access to the memory allocation subsystem.
16102  */
16103  sqlite3_mutex *mutex;
16104
16105  /*
16106  ** The minimum amount of free space that we have seen.
16107  */
16108  u32 mnMaster;
16109
16110  /*
16111  ** iMaster is the index of the master chunk.  Most new allocations
16112  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
16113  ** of the current master.  iMaster is 0 if there is not master chunk.
16114  ** The master chunk is not in either the aiHash[] or aiSmall[].
16115  */
16116  u32 iMaster;
16117  u32 szMaster;
16118
16119  /*
16120  ** Array of lists of free blocks according to the block size
16121  ** for smaller chunks, or a hash on the block size for larger
16122  ** chunks.
16123  */
16124  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
16125  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
16126} mem3 = { 97535575 };
16127
16128#define mem3 GLOBAL(struct Mem3Global, mem3)
16129
16130/*
16131** Unlink the chunk at mem3.aPool[i] from list it is currently
16132** on.  *pRoot is the list that i is a member of.
16133*/
16134static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16135  u32 next = mem3.aPool[i].u.list.next;
16136  u32 prev = mem3.aPool[i].u.list.prev;
16137  assert( sqlite3_mutex_held(mem3.mutex) );
16138  if( prev==0 ){
16139    *pRoot = next;
16140  }else{
16141    mem3.aPool[prev].u.list.next = next;
16142  }
16143  if( next ){
16144    mem3.aPool[next].u.list.prev = prev;
16145  }
16146  mem3.aPool[i].u.list.next = 0;
16147  mem3.aPool[i].u.list.prev = 0;
16148}
16149
16150/*
16151** Unlink the chunk at index i from
16152** whatever list is currently a member of.
16153*/
16154static void memsys3Unlink(u32 i){
16155  u32 size, hash;
16156  assert( sqlite3_mutex_held(mem3.mutex) );
16157  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16158  assert( i>=1 );
16159  size = mem3.aPool[i-1].u.hdr.size4x/4;
16160  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16161  assert( size>=2 );
16162  if( size <= MX_SMALL ){
16163    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
16164  }else{
16165    hash = size % N_HASH;
16166    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16167  }
16168}
16169
16170/*
16171** Link the chunk at mem3.aPool[i] so that is on the list rooted
16172** at *pRoot.
16173*/
16174static void memsys3LinkIntoList(u32 i, u32 *pRoot){
16175  assert( sqlite3_mutex_held(mem3.mutex) );
16176  mem3.aPool[i].u.list.next = *pRoot;
16177  mem3.aPool[i].u.list.prev = 0;
16178  if( *pRoot ){
16179    mem3.aPool[*pRoot].u.list.prev = i;
16180  }
16181  *pRoot = i;
16182}
16183
16184/*
16185** Link the chunk at index i into either the appropriate
16186** small chunk list, or into the large chunk hash table.
16187*/
16188static void memsys3Link(u32 i){
16189  u32 size, hash;
16190  assert( sqlite3_mutex_held(mem3.mutex) );
16191  assert( i>=1 );
16192  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16193  size = mem3.aPool[i-1].u.hdr.size4x/4;
16194  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16195  assert( size>=2 );
16196  if( size <= MX_SMALL ){
16197    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
16198  }else{
16199    hash = size % N_HASH;
16200    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
16201  }
16202}
16203
16204/*
16205** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16206** will already be held (obtained by code in malloc.c) if
16207** sqlite3GlobalConfig.bMemStat is true.
16208*/
16209static void memsys3Enter(void){
16210  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
16211    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16212  }
16213  sqlite3_mutex_enter(mem3.mutex);
16214}
16215static void memsys3Leave(void){
16216  sqlite3_mutex_leave(mem3.mutex);
16217}
16218
16219/*
16220** Called when we are unable to satisfy an allocation of nBytes.
16221*/
16222static void memsys3OutOfMemory(int nByte){
16223  if( !mem3.alarmBusy ){
16224    mem3.alarmBusy = 1;
16225    assert( sqlite3_mutex_held(mem3.mutex) );
16226    sqlite3_mutex_leave(mem3.mutex);
16227    sqlite3_release_memory(nByte);
16228    sqlite3_mutex_enter(mem3.mutex);
16229    mem3.alarmBusy = 0;
16230  }
16231}
16232
16233
16234/*
16235** Chunk i is a free chunk that has been unlinked.  Adjust its
16236** size parameters for check-out and return a pointer to the
16237** user portion of the chunk.
16238*/
16239static void *memsys3Checkout(u32 i, u32 nBlock){
16240  u32 x;
16241  assert( sqlite3_mutex_held(mem3.mutex) );
16242  assert( i>=1 );
16243  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
16244  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
16245  x = mem3.aPool[i-1].u.hdr.size4x;
16246  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
16247  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
16248  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
16249  return &mem3.aPool[i];
16250}
16251
16252/*
16253** Carve a piece off of the end of the mem3.iMaster free chunk.
16254** Return a pointer to the new allocation.  Or, if the master chunk
16255** is not large enough, return 0.
16256*/
16257static void *memsys3FromMaster(u32 nBlock){
16258  assert( sqlite3_mutex_held(mem3.mutex) );
16259  assert( mem3.szMaster>=nBlock );
16260  if( nBlock>=mem3.szMaster-1 ){
16261    /* Use the entire master */
16262    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
16263    mem3.iMaster = 0;
16264    mem3.szMaster = 0;
16265    mem3.mnMaster = 0;
16266    return p;
16267  }else{
16268    /* Split the master block.  Return the tail. */
16269    u32 newi, x;
16270    newi = mem3.iMaster + mem3.szMaster - nBlock;
16271    assert( newi > mem3.iMaster+1 );
16272    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
16273    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
16274    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
16275    mem3.szMaster -= nBlock;
16276    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
16277    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16278    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16279    if( mem3.szMaster < mem3.mnMaster ){
16280      mem3.mnMaster = mem3.szMaster;
16281    }
16282    return (void*)&mem3.aPool[newi];
16283  }
16284}
16285
16286/*
16287** *pRoot is the head of a list of free chunks of the same size
16288** or same size hash.  In other words, *pRoot is an entry in either
16289** mem3.aiSmall[] or mem3.aiHash[].
16290**
16291** This routine examines all entries on the given list and tries
16292** to coalesce each entries with adjacent free chunks.
16293**
16294** If it sees a chunk that is larger than mem3.iMaster, it replaces
16295** the current mem3.iMaster with the new larger chunk.  In order for
16296** this mem3.iMaster replacement to work, the master chunk must be
16297** linked into the hash tables.  That is not the normal state of
16298** affairs, of course.  The calling routine must link the master
16299** chunk before invoking this routine, then must unlink the (possibly
16300** changed) master chunk once this routine has finished.
16301*/
16302static void memsys3Merge(u32 *pRoot){
16303  u32 iNext, prev, size, i, x;
16304
16305  assert( sqlite3_mutex_held(mem3.mutex) );
16306  for(i=*pRoot; i>0; i=iNext){
16307    iNext = mem3.aPool[i].u.list.next;
16308    size = mem3.aPool[i-1].u.hdr.size4x;
16309    assert( (size&1)==0 );
16310    if( (size&2)==0 ){
16311      memsys3UnlinkFromList(i, pRoot);
16312      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
16313      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
16314      if( prev==iNext ){
16315        iNext = mem3.aPool[prev].u.list.next;
16316      }
16317      memsys3Unlink(prev);
16318      size = i + size/4 - prev;
16319      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
16320      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
16321      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
16322      memsys3Link(prev);
16323      i = prev;
16324    }else{
16325      size /= 4;
16326    }
16327    if( size>mem3.szMaster ){
16328      mem3.iMaster = i;
16329      mem3.szMaster = size;
16330    }
16331  }
16332}
16333
16334/*
16335** Return a block of memory of at least nBytes in size.
16336** Return NULL if unable.
16337**
16338** This function assumes that the necessary mutexes, if any, are
16339** already held by the caller. Hence "Unsafe".
16340*/
16341static void *memsys3MallocUnsafe(int nByte){
16342  u32 i;
16343  u32 nBlock;
16344  u32 toFree;
16345
16346  assert( sqlite3_mutex_held(mem3.mutex) );
16347  assert( sizeof(Mem3Block)==8 );
16348  if( nByte<=12 ){
16349    nBlock = 2;
16350  }else{
16351    nBlock = (nByte + 11)/8;
16352  }
16353  assert( nBlock>=2 );
16354
16355  /* STEP 1:
16356  ** Look for an entry of the correct size in either the small
16357  ** chunk table or in the large chunk hash table.  This is
16358  ** successful most of the time (about 9 times out of 10).
16359  */
16360  if( nBlock <= MX_SMALL ){
16361    i = mem3.aiSmall[nBlock-2];
16362    if( i>0 ){
16363      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
16364      return memsys3Checkout(i, nBlock);
16365    }
16366  }else{
16367    int hash = nBlock % N_HASH;
16368    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
16369      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
16370        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16371        return memsys3Checkout(i, nBlock);
16372      }
16373    }
16374  }
16375
16376  /* STEP 2:
16377  ** Try to satisfy the allocation by carving a piece off of the end
16378  ** of the master chunk.  This step usually works if step 1 fails.
16379  */
16380  if( mem3.szMaster>=nBlock ){
16381    return memsys3FromMaster(nBlock);
16382  }
16383
16384
16385  /* STEP 3:
16386  ** Loop through the entire memory pool.  Coalesce adjacent free
16387  ** chunks.  Recompute the master chunk as the largest free chunk.
16388  ** Then try again to satisfy the allocation by carving a piece off
16389  ** of the end of the master chunk.  This step happens very
16390  ** rarely (we hope!)
16391  */
16392  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
16393    memsys3OutOfMemory(toFree);
16394    if( mem3.iMaster ){
16395      memsys3Link(mem3.iMaster);
16396      mem3.iMaster = 0;
16397      mem3.szMaster = 0;
16398    }
16399    for(i=0; i<N_HASH; i++){
16400      memsys3Merge(&mem3.aiHash[i]);
16401    }
16402    for(i=0; i<MX_SMALL-1; i++){
16403      memsys3Merge(&mem3.aiSmall[i]);
16404    }
16405    if( mem3.szMaster ){
16406      memsys3Unlink(mem3.iMaster);
16407      if( mem3.szMaster>=nBlock ){
16408        return memsys3FromMaster(nBlock);
16409      }
16410    }
16411  }
16412
16413  /* If none of the above worked, then we fail. */
16414  return 0;
16415}
16416
16417/*
16418** Free an outstanding memory allocation.
16419**
16420** This function assumes that the necessary mutexes, if any, are
16421** already held by the caller. Hence "Unsafe".
16422*/
16423static void memsys3FreeUnsafe(void *pOld){
16424  Mem3Block *p = (Mem3Block*)pOld;
16425  int i;
16426  u32 size, x;
16427  assert( sqlite3_mutex_held(mem3.mutex) );
16428  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
16429  i = p - mem3.aPool;
16430  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
16431  size = mem3.aPool[i-1].u.hdr.size4x/4;
16432  assert( i+size<=mem3.nPool+1 );
16433  mem3.aPool[i-1].u.hdr.size4x &= ~1;
16434  mem3.aPool[i+size-1].u.hdr.prevSize = size;
16435  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
16436  memsys3Link(i);
16437
16438  /* Try to expand the master using the newly freed chunk */
16439  if( mem3.iMaster ){
16440    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
16441      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
16442      mem3.iMaster -= size;
16443      mem3.szMaster += size;
16444      memsys3Unlink(mem3.iMaster);
16445      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16446      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16447      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16448    }
16449    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16450    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
16451      memsys3Unlink(mem3.iMaster+mem3.szMaster);
16452      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
16453      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16454      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16455    }
16456  }
16457}
16458
16459/*
16460** Return the size of an outstanding allocation, in bytes.  The
16461** size returned omits the 8-byte header overhead.  This only
16462** works for chunks that are currently checked out.
16463*/
16464static int memsys3Size(void *p){
16465  Mem3Block *pBlock;
16466  if( p==0 ) return 0;
16467  pBlock = (Mem3Block*)p;
16468  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
16469  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
16470}
16471
16472/*
16473** Round up a request size to the next valid allocation size.
16474*/
16475static int memsys3Roundup(int n){
16476  if( n<=12 ){
16477    return 12;
16478  }else{
16479    return ((n+11)&~7) - 4;
16480  }
16481}
16482
16483/*
16484** Allocate nBytes of memory.
16485*/
16486static void *memsys3Malloc(int nBytes){
16487  sqlite3_int64 *p;
16488  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
16489  memsys3Enter();
16490  p = memsys3MallocUnsafe(nBytes);
16491  memsys3Leave();
16492  return (void*)p;
16493}
16494
16495/*
16496** Free memory.
16497*/
16498static void memsys3Free(void *pPrior){
16499  assert( pPrior );
16500  memsys3Enter();
16501  memsys3FreeUnsafe(pPrior);
16502  memsys3Leave();
16503}
16504
16505/*
16506** Change the size of an existing memory allocation
16507*/
16508static void *memsys3Realloc(void *pPrior, int nBytes){
16509  int nOld;
16510  void *p;
16511  if( pPrior==0 ){
16512    return sqlite3_malloc(nBytes);
16513  }
16514  if( nBytes<=0 ){
16515    sqlite3_free(pPrior);
16516    return 0;
16517  }
16518  nOld = memsys3Size(pPrior);
16519  if( nBytes<=nOld && nBytes>=nOld-128 ){
16520    return pPrior;
16521  }
16522  memsys3Enter();
16523  p = memsys3MallocUnsafe(nBytes);
16524  if( p ){
16525    if( nOld<nBytes ){
16526      memcpy(p, pPrior, nOld);
16527    }else{
16528      memcpy(p, pPrior, nBytes);
16529    }
16530    memsys3FreeUnsafe(pPrior);
16531  }
16532  memsys3Leave();
16533  return p;
16534}
16535
16536/*
16537** Initialize this module.
16538*/
16539static int memsys3Init(void *NotUsed){
16540  UNUSED_PARAMETER(NotUsed);
16541  if( !sqlite3GlobalConfig.pHeap ){
16542    return SQLITE_ERROR;
16543  }
16544
16545  /* Store a pointer to the memory block in global structure mem3. */
16546  assert( sizeof(Mem3Block)==8 );
16547  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16548  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16549
16550  /* Initialize the master block. */
16551  mem3.szMaster = mem3.nPool;
16552  mem3.mnMaster = mem3.szMaster;
16553  mem3.iMaster = 1;
16554  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
16555  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
16556  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
16557
16558  return SQLITE_OK;
16559}
16560
16561/*
16562** Deinitialize this module.
16563*/
16564static void memsys3Shutdown(void *NotUsed){
16565  UNUSED_PARAMETER(NotUsed);
16566  mem3.mutex = 0;
16567  return;
16568}
16569
16570
16571
16572/*
16573** Open the file indicated and write a log of all unfreed memory
16574** allocations into that log.
16575*/
16576SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
16577#ifdef SQLITE_DEBUG
16578  FILE *out;
16579  u32 i, j;
16580  u32 size;
16581  if( zFilename==0 || zFilename[0]==0 ){
16582    out = stdout;
16583  }else{
16584    out = fopen(zFilename, "w");
16585    if( out==0 ){
16586      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16587                      zFilename);
16588      return;
16589    }
16590  }
16591  memsys3Enter();
16592  fprintf(out, "CHUNKS:\n");
16593  for(i=1; i<=mem3.nPool; i+=size/4){
16594    size = mem3.aPool[i-1].u.hdr.size4x;
16595    if( size/4<=1 ){
16596      fprintf(out, "%p size error\n", &mem3.aPool[i]);
16597      assert( 0 );
16598      break;
16599    }
16600    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
16601      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
16602      assert( 0 );
16603      break;
16604    }
16605    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
16606      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
16607      assert( 0 );
16608      break;
16609    }
16610    if( size&1 ){
16611      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
16612    }else{
16613      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
16614                  i==mem3.iMaster ? " **master**" : "");
16615    }
16616  }
16617  for(i=0; i<MX_SMALL-1; i++){
16618    if( mem3.aiSmall[i]==0 ) continue;
16619    fprintf(out, "small(%2d):", i);
16620    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
16621      fprintf(out, " %p(%d)", &mem3.aPool[j],
16622              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16623    }
16624    fprintf(out, "\n");
16625  }
16626  for(i=0; i<N_HASH; i++){
16627    if( mem3.aiHash[i]==0 ) continue;
16628    fprintf(out, "hash(%2d):", i);
16629    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
16630      fprintf(out, " %p(%d)", &mem3.aPool[j],
16631              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16632    }
16633    fprintf(out, "\n");
16634  }
16635  fprintf(out, "master=%d\n", mem3.iMaster);
16636  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
16637  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
16638  sqlite3_mutex_leave(mem3.mutex);
16639  if( out==stdout ){
16640    fflush(stdout);
16641  }else{
16642    fclose(out);
16643  }
16644#else
16645  UNUSED_PARAMETER(zFilename);
16646#endif
16647}
16648
16649/*
16650** This routine is the only routine in this file with external
16651** linkage.
16652**
16653** Populate the low-level memory allocation function pointers in
16654** sqlite3GlobalConfig.m with pointers to the routines in this file. The
16655** arguments specify the block of memory to manage.
16656**
16657** This routine is only called by sqlite3_config(), and therefore
16658** is not required to be threadsafe (it is not).
16659*/
16660SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
16661  static const sqlite3_mem_methods mempoolMethods = {
16662     memsys3Malloc,
16663     memsys3Free,
16664     memsys3Realloc,
16665     memsys3Size,
16666     memsys3Roundup,
16667     memsys3Init,
16668     memsys3Shutdown,
16669     0
16670  };
16671  return &mempoolMethods;
16672}
16673
16674#endif /* SQLITE_ENABLE_MEMSYS3 */
16675
16676/************** End of mem3.c ************************************************/
16677/************** Begin file mem5.c ********************************************/
16678/*
16679** 2007 October 14
16680**
16681** The author disclaims copyright to this source code.  In place of
16682** a legal notice, here is a blessing:
16683**
16684**    May you do good and not evil.
16685**    May you find forgiveness for yourself and forgive others.
16686**    May you share freely, never taking more than you give.
16687**
16688*************************************************************************
16689** This file contains the C functions that implement a memory
16690** allocation subsystem for use by SQLite.
16691**
16692** This version of the memory allocation subsystem omits all
16693** use of malloc(). The application gives SQLite a block of memory
16694** before calling sqlite3_initialize() from which allocations
16695** are made and returned by the xMalloc() and xRealloc()
16696** implementations. Once sqlite3_initialize() has been called,
16697** the amount of memory available to SQLite is fixed and cannot
16698** be changed.
16699**
16700** This version of the memory allocation subsystem is included
16701** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
16702**
16703** This memory allocator uses the following algorithm:
16704**
16705**   1.  All memory allocations sizes are rounded up to a power of 2.
16706**
16707**   2.  If two adjacent free blocks are the halves of a larger block,
16708**       then the two blocks are coalesed into the single larger block.
16709**
16710**   3.  New memory is allocated from the first available free block.
16711**
16712** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
16713** Concerning Dynamic Storage Allocation". Journal of the Association for
16714** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
16715**
16716** Let n be the size of the largest allocation divided by the minimum
16717** allocation size (after rounding all sizes up to a power of 2.)  Let M
16718** be the maximum amount of memory ever outstanding at one time.  Let
16719** N be the total amount of memory available for allocation.  Robson
16720** proved that this memory allocator will never breakdown due to
16721** fragmentation as long as the following constraint holds:
16722**
16723**      N >=  M*(1 + log2(n)/2) - n + 1
16724**
16725** The sqlite3_status() logic tracks the maximum values of n and M so
16726** that an application can, at any time, verify this constraint.
16727*/
16728
16729/*
16730** This version of the memory allocator is used only when
16731** SQLITE_ENABLE_MEMSYS5 is defined.
16732*/
16733#ifdef SQLITE_ENABLE_MEMSYS5
16734
16735/*
16736** A minimum allocation is an instance of the following structure.
16737** Larger allocations are an array of these structures where the
16738** size of the array is a power of 2.
16739**
16740** The size of this object must be a power of two.  That fact is
16741** verified in memsys5Init().
16742*/
16743typedef struct Mem5Link Mem5Link;
16744struct Mem5Link {
16745  int next;       /* Index of next free chunk */
16746  int prev;       /* Index of previous free chunk */
16747};
16748
16749/*
16750** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
16751** mem5.szAtom is always at least 8 and 32-bit integers are used,
16752** it is not actually possible to reach this limit.
16753*/
16754#define LOGMAX 30
16755
16756/*
16757** Masks used for mem5.aCtrl[] elements.
16758*/
16759#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
16760#define CTRL_FREE     0x20    /* True if not checked out */
16761
16762/*
16763** All of the static variables used by this module are collected
16764** into a single structure named "mem5".  This is to keep the
16765** static variables organized and to reduce namespace pollution
16766** when this module is combined with other in the amalgamation.
16767*/
16768static SQLITE_WSD struct Mem5Global {
16769  /*
16770  ** Memory available for allocation
16771  */
16772  int szAtom;      /* Smallest possible allocation in bytes */
16773  int nBlock;      /* Number of szAtom sized blocks in zPool */
16774  u8 *zPool;       /* Memory available to be allocated */
16775
16776  /*
16777  ** Mutex to control access to the memory allocation subsystem.
16778  */
16779  sqlite3_mutex *mutex;
16780
16781  /*
16782  ** Performance statistics
16783  */
16784  u64 nAlloc;         /* Total number of calls to malloc */
16785  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
16786  u64 totalExcess;    /* Total internal fragmentation */
16787  u32 currentOut;     /* Current checkout, including internal fragmentation */
16788  u32 currentCount;   /* Current number of distinct checkouts */
16789  u32 maxOut;         /* Maximum instantaneous currentOut */
16790  u32 maxCount;       /* Maximum instantaneous currentCount */
16791  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
16792
16793  /*
16794  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
16795  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
16796  ** and so forth.
16797  */
16798  int aiFreelist[LOGMAX+1];
16799
16800  /*
16801  ** Space for tracking which blocks are checked out and the size
16802  ** of each block.  One byte per block.
16803  */
16804  u8 *aCtrl;
16805
16806} mem5;
16807
16808/*
16809** Access the static variable through a macro for SQLITE_OMIT_WSD
16810*/
16811#define mem5 GLOBAL(struct Mem5Global, mem5)
16812
16813/*
16814** Assuming mem5.zPool is divided up into an array of Mem5Link
16815** structures, return a pointer to the idx-th such lik.
16816*/
16817#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
16818
16819/*
16820** Unlink the chunk at mem5.aPool[i] from list it is currently
16821** on.  It should be found on mem5.aiFreelist[iLogsize].
16822*/
16823static void memsys5Unlink(int i, int iLogsize){
16824  int next, prev;
16825  assert( i>=0 && i<mem5.nBlock );
16826  assert( iLogsize>=0 && iLogsize<=LOGMAX );
16827  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16828
16829  next = MEM5LINK(i)->next;
16830  prev = MEM5LINK(i)->prev;
16831  if( prev<0 ){
16832    mem5.aiFreelist[iLogsize] = next;
16833  }else{
16834    MEM5LINK(prev)->next = next;
16835  }
16836  if( next>=0 ){
16837    MEM5LINK(next)->prev = prev;
16838  }
16839}
16840
16841/*
16842** Link the chunk at mem5.aPool[i] so that is on the iLogsize
16843** free list.
16844*/
16845static void memsys5Link(int i, int iLogsize){
16846  int x;
16847  assert( sqlite3_mutex_held(mem5.mutex) );
16848  assert( i>=0 && i<mem5.nBlock );
16849  assert( iLogsize>=0 && iLogsize<=LOGMAX );
16850  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16851
16852  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
16853  MEM5LINK(i)->prev = -1;
16854  if( x>=0 ){
16855    assert( x<mem5.nBlock );
16856    MEM5LINK(x)->prev = i;
16857  }
16858  mem5.aiFreelist[iLogsize] = i;
16859}
16860
16861/*
16862** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16863** will already be held (obtained by code in malloc.c) if
16864** sqlite3GlobalConfig.bMemStat is true.
16865*/
16866static void memsys5Enter(void){
16867  sqlite3_mutex_enter(mem5.mutex);
16868}
16869static void memsys5Leave(void){
16870  sqlite3_mutex_leave(mem5.mutex);
16871}
16872
16873/*
16874** Return the size of an outstanding allocation, in bytes.  The
16875** size returned omits the 8-byte header overhead.  This only
16876** works for chunks that are currently checked out.
16877*/
16878static int memsys5Size(void *p){
16879  int iSize = 0;
16880  if( p ){
16881    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
16882    assert( i>=0 && i<mem5.nBlock );
16883    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
16884  }
16885  return iSize;
16886}
16887
16888/*
16889** Find the first entry on the freelist iLogsize.  Unlink that
16890** entry and return its index.
16891*/
16892static int memsys5UnlinkFirst(int iLogsize){
16893  int i;
16894  int iFirst;
16895
16896  assert( iLogsize>=0 && iLogsize<=LOGMAX );
16897  i = iFirst = mem5.aiFreelist[iLogsize];
16898  assert( iFirst>=0 );
16899  while( i>0 ){
16900    if( i<iFirst ) iFirst = i;
16901    i = MEM5LINK(i)->next;
16902  }
16903  memsys5Unlink(iFirst, iLogsize);
16904  return iFirst;
16905}
16906
16907/*
16908** Return a block of memory of at least nBytes in size.
16909** Return NULL if unable.  Return NULL if nBytes==0.
16910**
16911** The caller guarantees that nByte positive.
16912**
16913** The caller has obtained a mutex prior to invoking this
16914** routine so there is never any chance that two or more
16915** threads can be in this routine at the same time.
16916*/
16917static void *memsys5MallocUnsafe(int nByte){
16918  int i;           /* Index of a mem5.aPool[] slot */
16919  int iBin;        /* Index into mem5.aiFreelist[] */
16920  int iFullSz;     /* Size of allocation rounded up to power of 2 */
16921  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
16922
16923  /* nByte must be a positive */
16924  assert( nByte>0 );
16925
16926  /* Keep track of the maximum allocation request.  Even unfulfilled
16927  ** requests are counted */
16928  if( (u32)nByte>mem5.maxRequest ){
16929    mem5.maxRequest = nByte;
16930  }
16931
16932  /* Abort if the requested allocation size is larger than the largest
16933  ** power of two that we can represent using 32-bit signed integers.
16934  */
16935  if( nByte > 0x40000000 ){
16936    return 0;
16937  }
16938
16939  /* Round nByte up to the next valid power of two */
16940  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
16941
16942  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
16943  ** block.  If not, then split a block of the next larger power of
16944  ** two in order to create a new free block of size iLogsize.
16945  */
16946  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
16947  if( iBin>LOGMAX ){
16948    testcase( sqlite3GlobalConfig.xLog!=0 );
16949    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
16950    return 0;
16951  }
16952  i = memsys5UnlinkFirst(iBin);
16953  while( iBin>iLogsize ){
16954    int newSize;
16955
16956    iBin--;
16957    newSize = 1 << iBin;
16958    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
16959    memsys5Link(i+newSize, iBin);
16960  }
16961  mem5.aCtrl[i] = iLogsize;
16962
16963  /* Update allocator performance statistics. */
16964  mem5.nAlloc++;
16965  mem5.totalAlloc += iFullSz;
16966  mem5.totalExcess += iFullSz - nByte;
16967  mem5.currentCount++;
16968  mem5.currentOut += iFullSz;
16969  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
16970  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
16971
16972  /* Return a pointer to the allocated memory. */
16973  return (void*)&mem5.zPool[i*mem5.szAtom];
16974}
16975
16976/*
16977** Free an outstanding memory allocation.
16978*/
16979static void memsys5FreeUnsafe(void *pOld){
16980  u32 size, iLogsize;
16981  int iBlock;
16982
16983  /* Set iBlock to the index of the block pointed to by pOld in
16984  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
16985  */
16986  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
16987
16988  /* Check that the pointer pOld points to a valid, non-free block. */
16989  assert( iBlock>=0 && iBlock<mem5.nBlock );
16990  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
16991  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
16992
16993  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
16994  size = 1<<iLogsize;
16995  assert( iBlock+size-1<(u32)mem5.nBlock );
16996
16997  mem5.aCtrl[iBlock] |= CTRL_FREE;
16998  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
16999  assert( mem5.currentCount>0 );
17000  assert( mem5.currentOut>=(size*mem5.szAtom) );
17001  mem5.currentCount--;
17002  mem5.currentOut -= size*mem5.szAtom;
17003  assert( mem5.currentOut>0 || mem5.currentCount==0 );
17004  assert( mem5.currentCount>0 || mem5.currentOut==0 );
17005
17006  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17007  while( ALWAYS(iLogsize<LOGMAX) ){
17008    int iBuddy;
17009    if( (iBlock>>iLogsize) & 1 ){
17010      iBuddy = iBlock - size;
17011    }else{
17012      iBuddy = iBlock + size;
17013    }
17014    assert( iBuddy>=0 );
17015    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17016    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17017    memsys5Unlink(iBuddy, iLogsize);
17018    iLogsize++;
17019    if( iBuddy<iBlock ){
17020      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17021      mem5.aCtrl[iBlock] = 0;
17022      iBlock = iBuddy;
17023    }else{
17024      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17025      mem5.aCtrl[iBuddy] = 0;
17026    }
17027    size *= 2;
17028  }
17029  memsys5Link(iBlock, iLogsize);
17030}
17031
17032/*
17033** Allocate nBytes of memory
17034*/
17035static void *memsys5Malloc(int nBytes){
17036  sqlite3_int64 *p = 0;
17037  if( nBytes>0 ){
17038    memsys5Enter();
17039    p = memsys5MallocUnsafe(nBytes);
17040    memsys5Leave();
17041  }
17042  return (void*)p;
17043}
17044
17045/*
17046** Free memory.
17047**
17048** The outer layer memory allocator prevents this routine from
17049** being called with pPrior==0.
17050*/
17051static void memsys5Free(void *pPrior){
17052  assert( pPrior!=0 );
17053  memsys5Enter();
17054  memsys5FreeUnsafe(pPrior);
17055  memsys5Leave();
17056}
17057
17058/*
17059** Change the size of an existing memory allocation.
17060**
17061** The outer layer memory allocator prevents this routine from
17062** being called with pPrior==0.
17063**
17064** nBytes is always a value obtained from a prior call to
17065** memsys5Round().  Hence nBytes is always a non-negative power
17066** of two.  If nBytes==0 that means that an oversize allocation
17067** (an allocation larger than 0x40000000) was requested and this
17068** routine should return 0 without freeing pPrior.
17069*/
17070static void *memsys5Realloc(void *pPrior, int nBytes){
17071  int nOld;
17072  void *p;
17073  assert( pPrior!=0 );
17074  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
17075  assert( nBytes>=0 );
17076  if( nBytes==0 ){
17077    return 0;
17078  }
17079  nOld = memsys5Size(pPrior);
17080  if( nBytes<=nOld ){
17081    return pPrior;
17082  }
17083  memsys5Enter();
17084  p = memsys5MallocUnsafe(nBytes);
17085  if( p ){
17086    memcpy(p, pPrior, nOld);
17087    memsys5FreeUnsafe(pPrior);
17088  }
17089  memsys5Leave();
17090  return p;
17091}
17092
17093/*
17094** Round up a request size to the next valid allocation size.  If
17095** the allocation is too large to be handled by this allocation system,
17096** return 0.
17097**
17098** All allocations must be a power of two and must be expressed by a
17099** 32-bit signed integer.  Hence the largest allocation is 0x40000000
17100** or 1073741824 bytes.
17101*/
17102static int memsys5Roundup(int n){
17103  int iFullSz;
17104  if( n > 0x40000000 ) return 0;
17105  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17106  return iFullSz;
17107}
17108
17109/*
17110** Return the ceiling of the logarithm base 2 of iValue.
17111**
17112** Examples:   memsys5Log(1) -> 0
17113**             memsys5Log(2) -> 1
17114**             memsys5Log(4) -> 2
17115**             memsys5Log(5) -> 3
17116**             memsys5Log(8) -> 3
17117**             memsys5Log(9) -> 4
17118*/
17119static int memsys5Log(int iValue){
17120  int iLog;
17121  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17122  return iLog;
17123}
17124
17125/*
17126** Initialize the memory allocator.
17127**
17128** This routine is not threadsafe.  The caller must be holding a mutex
17129** to prevent multiple threads from entering at the same time.
17130*/
17131static int memsys5Init(void *NotUsed){
17132  int ii;            /* Loop counter */
17133  int nByte;         /* Number of bytes of memory available to this allocator */
17134  u8 *zByte;         /* Memory usable by this allocator */
17135  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
17136  int iOffset;       /* An offset into mem5.aCtrl[] */
17137
17138  UNUSED_PARAMETER(NotUsed);
17139
17140  /* For the purposes of this routine, disable the mutex */
17141  mem5.mutex = 0;
17142
17143  /* The size of a Mem5Link object must be a power of two.  Verify that
17144  ** this is case.
17145  */
17146  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17147
17148  nByte = sqlite3GlobalConfig.nHeap;
17149  zByte = (u8*)sqlite3GlobalConfig.pHeap;
17150  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
17151
17152  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17153  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17154  mem5.szAtom = (1<<nMinLog);
17155  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17156    mem5.szAtom = mem5.szAtom << 1;
17157  }
17158
17159  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17160  mem5.zPool = zByte;
17161  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17162
17163  for(ii=0; ii<=LOGMAX; ii++){
17164    mem5.aiFreelist[ii] = -1;
17165  }
17166
17167  iOffset = 0;
17168  for(ii=LOGMAX; ii>=0; ii--){
17169    int nAlloc = (1<<ii);
17170    if( (iOffset+nAlloc)<=mem5.nBlock ){
17171      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
17172      memsys5Link(iOffset, ii);
17173      iOffset += nAlloc;
17174    }
17175    assert((iOffset+nAlloc)>mem5.nBlock);
17176  }
17177
17178  /* If a mutex is required for normal operation, allocate one */
17179  if( sqlite3GlobalConfig.bMemstat==0 ){
17180    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17181  }
17182
17183  return SQLITE_OK;
17184}
17185
17186/*
17187** Deinitialize this module.
17188*/
17189static void memsys5Shutdown(void *NotUsed){
17190  UNUSED_PARAMETER(NotUsed);
17191  mem5.mutex = 0;
17192  return;
17193}
17194
17195#ifdef SQLITE_TEST
17196/*
17197** Open the file indicated and write a log of all unfreed memory
17198** allocations into that log.
17199*/
17200SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
17201  FILE *out;
17202  int i, j, n;
17203  int nMinLog;
17204
17205  if( zFilename==0 || zFilename[0]==0 ){
17206    out = stdout;
17207  }else{
17208    out = fopen(zFilename, "w");
17209    if( out==0 ){
17210      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17211                      zFilename);
17212      return;
17213    }
17214  }
17215  memsys5Enter();
17216  nMinLog = memsys5Log(mem5.szAtom);
17217  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
17218    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
17219    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
17220  }
17221  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
17222  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
17223  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
17224  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
17225  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
17226  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
17227  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
17228  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
17229  memsys5Leave();
17230  if( out==stdout ){
17231    fflush(stdout);
17232  }else{
17233    fclose(out);
17234  }
17235}
17236#endif
17237
17238/*
17239** This routine is the only routine in this file with external
17240** linkage. It returns a pointer to a static sqlite3_mem_methods
17241** struct populated with the memsys5 methods.
17242*/
17243SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
17244  static const sqlite3_mem_methods memsys5Methods = {
17245     memsys5Malloc,
17246     memsys5Free,
17247     memsys5Realloc,
17248     memsys5Size,
17249     memsys5Roundup,
17250     memsys5Init,
17251     memsys5Shutdown,
17252     0
17253  };
17254  return &memsys5Methods;
17255}
17256
17257#endif /* SQLITE_ENABLE_MEMSYS5 */
17258
17259/************** End of mem5.c ************************************************/
17260/************** Begin file mutex.c *******************************************/
17261/*
17262** 2007 August 14
17263**
17264** The author disclaims copyright to this source code.  In place of
17265** a legal notice, here is a blessing:
17266**
17267**    May you do good and not evil.
17268**    May you find forgiveness for yourself and forgive others.
17269**    May you share freely, never taking more than you give.
17270**
17271*************************************************************************
17272** This file contains the C functions that implement mutexes.
17273**
17274** This file contains code that is common across all mutex implementations.
17275*/
17276
17277#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
17278/*
17279** For debugging purposes, record when the mutex subsystem is initialized
17280** and uninitialized so that we can assert() if there is an attempt to
17281** allocate a mutex while the system is uninitialized.
17282*/
17283static SQLITE_WSD int mutexIsInit = 0;
17284#endif /* SQLITE_DEBUG */
17285
17286
17287#ifndef SQLITE_MUTEX_OMIT
17288/*
17289** Initialize the mutex system.
17290*/
17291SQLITE_PRIVATE int sqlite3MutexInit(void){
17292  int rc = SQLITE_OK;
17293  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
17294    /* If the xMutexAlloc method has not been set, then the user did not
17295    ** install a mutex implementation via sqlite3_config() prior to
17296    ** sqlite3_initialize() being called. This block copies pointers to
17297    ** the default implementation into the sqlite3GlobalConfig structure.
17298    */
17299    sqlite3_mutex_methods const *pFrom;
17300    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
17301
17302    if( sqlite3GlobalConfig.bCoreMutex ){
17303      pFrom = sqlite3DefaultMutex();
17304    }else{
17305      pFrom = sqlite3NoopMutex();
17306    }
17307    memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
17308    memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
17309           sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
17310    pTo->xMutexAlloc = pFrom->xMutexAlloc;
17311  }
17312  rc = sqlite3GlobalConfig.mutex.xMutexInit();
17313
17314#ifdef SQLITE_DEBUG
17315  GLOBAL(int, mutexIsInit) = 1;
17316#endif
17317
17318  return rc;
17319}
17320
17321/*
17322** Shutdown the mutex system. This call frees resources allocated by
17323** sqlite3MutexInit().
17324*/
17325SQLITE_PRIVATE int sqlite3MutexEnd(void){
17326  int rc = SQLITE_OK;
17327  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
17328    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
17329  }
17330
17331#ifdef SQLITE_DEBUG
17332  GLOBAL(int, mutexIsInit) = 0;
17333#endif
17334
17335  return rc;
17336}
17337
17338/*
17339** Retrieve a pointer to a static mutex or allocate a new dynamic one.
17340*/
17341SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
17342#ifndef SQLITE_OMIT_AUTOINIT
17343  if( sqlite3_initialize() ) return 0;
17344#endif
17345  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17346}
17347
17348SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
17349  if( !sqlite3GlobalConfig.bCoreMutex ){
17350    return 0;
17351  }
17352  assert( GLOBAL(int, mutexIsInit) );
17353  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17354}
17355
17356/*
17357** Free a dynamic mutex.
17358*/
17359SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
17360  if( p ){
17361    sqlite3GlobalConfig.mutex.xMutexFree(p);
17362  }
17363}
17364
17365/*
17366** Obtain the mutex p. If some other thread already has the mutex, block
17367** until it can be obtained.
17368*/
17369SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
17370  if( p ){
17371    sqlite3GlobalConfig.mutex.xMutexEnter(p);
17372  }
17373}
17374
17375/*
17376** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
17377** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
17378*/
17379SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
17380  int rc = SQLITE_OK;
17381  if( p ){
17382    return sqlite3GlobalConfig.mutex.xMutexTry(p);
17383  }
17384  return rc;
17385}
17386
17387/*
17388** The sqlite3_mutex_leave() routine exits a mutex that was previously
17389** entered by the same thread.  The behavior is undefined if the mutex
17390** is not currently entered. If a NULL pointer is passed as an argument
17391** this function is a no-op.
17392*/
17393SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
17394  if( p ){
17395    sqlite3GlobalConfig.mutex.xMutexLeave(p);
17396  }
17397}
17398
17399#ifndef NDEBUG
17400/*
17401** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17402** intended for use inside assert() statements.
17403*/
17404SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
17405  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
17406}
17407SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
17408  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
17409}
17410#endif
17411
17412#endif /* !defined(SQLITE_MUTEX_OMIT) */
17413
17414/************** End of mutex.c ***********************************************/
17415/************** Begin file mutex_noop.c **************************************/
17416/*
17417** 2008 October 07
17418**
17419** The author disclaims copyright to this source code.  In place of
17420** a legal notice, here is a blessing:
17421**
17422**    May you do good and not evil.
17423**    May you find forgiveness for yourself and forgive others.
17424**    May you share freely, never taking more than you give.
17425**
17426*************************************************************************
17427** This file contains the C functions that implement mutexes.
17428**
17429** This implementation in this file does not provide any mutual
17430** exclusion and is thus suitable for use only in applications
17431** that use SQLite in a single thread.  The routines defined
17432** here are place-holders.  Applications can substitute working
17433** mutex routines at start-time using the
17434**
17435**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
17436**
17437** interface.
17438**
17439** If compiled with SQLITE_DEBUG, then additional logic is inserted
17440** that does error checking on mutexes to make sure they are being
17441** called correctly.
17442*/
17443
17444#ifndef SQLITE_MUTEX_OMIT
17445
17446#ifndef SQLITE_DEBUG
17447/*
17448** Stub routines for all mutex methods.
17449**
17450** This routines provide no mutual exclusion or error checking.
17451*/
17452static int noopMutexInit(void){ return SQLITE_OK; }
17453static int noopMutexEnd(void){ return SQLITE_OK; }
17454static sqlite3_mutex *noopMutexAlloc(int id){
17455  UNUSED_PARAMETER(id);
17456  return (sqlite3_mutex*)8;
17457}
17458static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17459static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17460static int noopMutexTry(sqlite3_mutex *p){
17461  UNUSED_PARAMETER(p);
17462  return SQLITE_OK;
17463}
17464static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17465
17466SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17467  static const sqlite3_mutex_methods sMutex = {
17468    noopMutexInit,
17469    noopMutexEnd,
17470    noopMutexAlloc,
17471    noopMutexFree,
17472    noopMutexEnter,
17473    noopMutexTry,
17474    noopMutexLeave,
17475
17476    0,
17477    0,
17478  };
17479
17480  return &sMutex;
17481}
17482#endif /* !SQLITE_DEBUG */
17483
17484#ifdef SQLITE_DEBUG
17485/*
17486** In this implementation, error checking is provided for testing
17487** and debugging purposes.  The mutexes still do not provide any
17488** mutual exclusion.
17489*/
17490
17491/*
17492** The mutex object
17493*/
17494typedef struct sqlite3_debug_mutex {
17495  int id;     /* The mutex type */
17496  int cnt;    /* Number of entries without a matching leave */
17497} sqlite3_debug_mutex;
17498
17499/*
17500** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17501** intended for use inside assert() statements.
17502*/
17503static int debugMutexHeld(sqlite3_mutex *pX){
17504  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17505  return p==0 || p->cnt>0;
17506}
17507static int debugMutexNotheld(sqlite3_mutex *pX){
17508  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17509  return p==0 || p->cnt==0;
17510}
17511
17512/*
17513** Initialize and deinitialize the mutex subsystem.
17514*/
17515static int debugMutexInit(void){ return SQLITE_OK; }
17516static int debugMutexEnd(void){ return SQLITE_OK; }
17517
17518/*
17519** The sqlite3_mutex_alloc() routine allocates a new
17520** mutex and returns a pointer to it.  If it returns NULL
17521** that means that a mutex could not be allocated.
17522*/
17523static sqlite3_mutex *debugMutexAlloc(int id){
17524  static sqlite3_debug_mutex aStatic[6];
17525  sqlite3_debug_mutex *pNew = 0;
17526  switch( id ){
17527    case SQLITE_MUTEX_FAST:
17528    case SQLITE_MUTEX_RECURSIVE: {
17529      pNew = sqlite3Malloc(sizeof(*pNew));
17530      if( pNew ){
17531        pNew->id = id;
17532        pNew->cnt = 0;
17533      }
17534      break;
17535    }
17536    default: {
17537      assert( id-2 >= 0 );
17538      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17539      pNew = &aStatic[id-2];
17540      pNew->id = id;
17541      break;
17542    }
17543  }
17544  return (sqlite3_mutex*)pNew;
17545}
17546
17547/*
17548** This routine deallocates a previously allocated mutex.
17549*/
17550static void debugMutexFree(sqlite3_mutex *pX){
17551  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17552  assert( p->cnt==0 );
17553  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17554  sqlite3_free(p);
17555}
17556
17557/*
17558** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17559** to enter a mutex.  If another thread is already within the mutex,
17560** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17561** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17562** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17563** be entered multiple times by the same thread.  In such cases the,
17564** mutex must be exited an equal number of times before another thread
17565** can enter.  If the same thread tries to enter any other kind of mutex
17566** more than once, the behavior is undefined.
17567*/
17568static void debugMutexEnter(sqlite3_mutex *pX){
17569  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17570  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17571  p->cnt++;
17572}
17573static int debugMutexTry(sqlite3_mutex *pX){
17574  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17575  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17576  p->cnt++;
17577  return SQLITE_OK;
17578}
17579
17580/*
17581** The sqlite3_mutex_leave() routine exits a mutex that was
17582** previously entered by the same thread.  The behavior
17583** is undefined if the mutex is not currently entered or
17584** is not currently allocated.  SQLite will never do either.
17585*/
17586static void debugMutexLeave(sqlite3_mutex *pX){
17587  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17588  assert( debugMutexHeld(pX) );
17589  p->cnt--;
17590  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17591}
17592
17593SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17594  static const sqlite3_mutex_methods sMutex = {
17595    debugMutexInit,
17596    debugMutexEnd,
17597    debugMutexAlloc,
17598    debugMutexFree,
17599    debugMutexEnter,
17600    debugMutexTry,
17601    debugMutexLeave,
17602
17603    debugMutexHeld,
17604    debugMutexNotheld
17605  };
17606
17607  return &sMutex;
17608}
17609#endif /* SQLITE_DEBUG */
17610
17611/*
17612** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
17613** is used regardless of the run-time threadsafety setting.
17614*/
17615#ifdef SQLITE_MUTEX_NOOP
17616SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17617  return sqlite3NoopMutex();
17618}
17619#endif /* defined(SQLITE_MUTEX_NOOP) */
17620#endif /* !defined(SQLITE_MUTEX_OMIT) */
17621
17622/************** End of mutex_noop.c ******************************************/
17623/************** Begin file mutex_os2.c ***************************************/
17624/*
17625** 2007 August 28
17626**
17627** The author disclaims copyright to this source code.  In place of
17628** a legal notice, here is a blessing:
17629**
17630**    May you do good and not evil.
17631**    May you find forgiveness for yourself and forgive others.
17632**    May you share freely, never taking more than you give.
17633**
17634*************************************************************************
17635** This file contains the C functions that implement mutexes for OS/2
17636*/
17637
17638/*
17639** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
17640** See the mutex.h file for details.
17641*/
17642#ifdef SQLITE_MUTEX_OS2
17643
17644/********************** OS/2 Mutex Implementation **********************
17645**
17646** This implementation of mutexes is built using the OS/2 API.
17647*/
17648
17649/*
17650** The mutex object
17651** Each recursive mutex is an instance of the following structure.
17652*/
17653struct sqlite3_mutex {
17654  HMTX mutex;       /* Mutex controlling the lock */
17655  int  id;          /* Mutex type */
17656#ifdef SQLITE_DEBUG
17657 int   trace;       /* True to trace changes */
17658#endif
17659};
17660
17661#ifdef SQLITE_DEBUG
17662#define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
17663#else
17664#define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
17665#endif
17666
17667/*
17668** Initialize and deinitialize the mutex subsystem.
17669*/
17670static int os2MutexInit(void){ return SQLITE_OK; }
17671static int os2MutexEnd(void){ return SQLITE_OK; }
17672
17673/*
17674** The sqlite3_mutex_alloc() routine allocates a new
17675** mutex and returns a pointer to it.  If it returns NULL
17676** that means that a mutex could not be allocated.
17677** SQLite will unwind its stack and return an error.  The argument
17678** to sqlite3_mutex_alloc() is one of these integer constants:
17679**
17680** <ul>
17681** <li>  SQLITE_MUTEX_FAST
17682** <li>  SQLITE_MUTEX_RECURSIVE
17683** <li>  SQLITE_MUTEX_STATIC_MASTER
17684** <li>  SQLITE_MUTEX_STATIC_MEM
17685** <li>  SQLITE_MUTEX_STATIC_MEM2
17686** <li>  SQLITE_MUTEX_STATIC_PRNG
17687** <li>  SQLITE_MUTEX_STATIC_LRU
17688** <li>  SQLITE_MUTEX_STATIC_LRU2
17689** </ul>
17690**
17691** The first two constants cause sqlite3_mutex_alloc() to create
17692** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17693** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17694** The mutex implementation does not need to make a distinction
17695** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17696** not want to.  But SQLite will only request a recursive mutex in
17697** cases where it really needs one.  If a faster non-recursive mutex
17698** implementation is available on the host platform, the mutex subsystem
17699** might return such a mutex in response to SQLITE_MUTEX_FAST.
17700**
17701** The other allowed parameters to sqlite3_mutex_alloc() each return
17702** a pointer to a static preexisting mutex.  Six static mutexes are
17703** used by the current version of SQLite.  Future versions of SQLite
17704** may add additional static mutexes.  Static mutexes are for internal
17705** use by SQLite only.  Applications that use SQLite mutexes should
17706** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17707** SQLITE_MUTEX_RECURSIVE.
17708**
17709** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17710** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17711** returns a different mutex on every call.  But for the static
17712** mutex types, the same mutex is returned on every call that has
17713** the same type number.
17714*/
17715static sqlite3_mutex *os2MutexAlloc(int iType){
17716  sqlite3_mutex *p = NULL;
17717  switch( iType ){
17718    case SQLITE_MUTEX_FAST:
17719    case SQLITE_MUTEX_RECURSIVE: {
17720      p = sqlite3MallocZero( sizeof(*p) );
17721      if( p ){
17722        p->id = iType;
17723        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
17724          sqlite3_free( p );
17725          p = NULL;
17726        }
17727      }
17728      break;
17729    }
17730    default: {
17731      static volatile int isInit = 0;
17732      static sqlite3_mutex staticMutexes[6] = {
17733        SQLITE3_MUTEX_INITIALIZER,
17734        SQLITE3_MUTEX_INITIALIZER,
17735        SQLITE3_MUTEX_INITIALIZER,
17736        SQLITE3_MUTEX_INITIALIZER,
17737        SQLITE3_MUTEX_INITIALIZER,
17738        SQLITE3_MUTEX_INITIALIZER,
17739      };
17740      if ( !isInit ){
17741        APIRET rc;
17742        PTIB ptib;
17743        PPIB ppib;
17744        HMTX mutex;
17745        char name[32];
17746        DosGetInfoBlocks( &ptib, &ppib );
17747        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
17748                          ppib->pib_ulpid );
17749        while( !isInit ){
17750          mutex = 0;
17751          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
17752          if( rc == NO_ERROR ){
17753            unsigned int i;
17754            if( !isInit ){
17755              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
17756                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
17757              }
17758              isInit = 1;
17759            }
17760            DosCloseMutexSem( mutex );
17761          }else if( rc == ERROR_DUPLICATE_NAME ){
17762            DosSleep( 1 );
17763          }else{
17764            return p;
17765          }
17766        }
17767      }
17768      assert( iType-2 >= 0 );
17769      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
17770      p = &staticMutexes[iType-2];
17771      p->id = iType;
17772      break;
17773    }
17774  }
17775  return p;
17776}
17777
17778
17779/*
17780** This routine deallocates a previously allocated mutex.
17781** SQLite is careful to deallocate every mutex that it allocates.
17782*/
17783static void os2MutexFree(sqlite3_mutex *p){
17784#ifdef SQLITE_DEBUG
17785  TID tid;
17786  PID pid;
17787  ULONG ulCount;
17788  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17789  assert( ulCount==0 );
17790  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17791#endif
17792  DosCloseMutexSem( p->mutex );
17793  sqlite3_free( p );
17794}
17795
17796#ifdef SQLITE_DEBUG
17797/*
17798** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17799** intended for use inside assert() statements.
17800*/
17801static int os2MutexHeld(sqlite3_mutex *p){
17802  TID tid;
17803  PID pid;
17804  ULONG ulCount;
17805  PTIB ptib;
17806  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17807  if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
17808    return 0;
17809  DosGetInfoBlocks(&ptib, NULL);
17810  return tid==ptib->tib_ptib2->tib2_ultid;
17811}
17812static int os2MutexNotheld(sqlite3_mutex *p){
17813  TID tid;
17814  PID pid;
17815  ULONG ulCount;
17816  PTIB ptib;
17817  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17818  if( ulCount==0 )
17819    return 1;
17820  DosGetInfoBlocks(&ptib, NULL);
17821  return tid!=ptib->tib_ptib2->tib2_ultid;
17822}
17823static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
17824  TID   tid;
17825  PID   pid;
17826  ULONG ulCount;
17827  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17828  printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
17829}
17830#endif
17831
17832/*
17833** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17834** to enter a mutex.  If another thread is already within the mutex,
17835** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17836** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17837** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17838** be entered multiple times by the same thread.  In such cases the,
17839** mutex must be exited an equal number of times before another thread
17840** can enter.  If the same thread tries to enter any other kind of mutex
17841** more than once, the behavior is undefined.
17842*/
17843static void os2MutexEnter(sqlite3_mutex *p){
17844  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17845  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
17846#ifdef SQLITE_DEBUG
17847  if( p->trace ) os2MutexTrace(p, "enter");
17848#endif
17849}
17850static int os2MutexTry(sqlite3_mutex *p){
17851  int rc = SQLITE_BUSY;
17852  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17853  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
17854    rc = SQLITE_OK;
17855#ifdef SQLITE_DEBUG
17856    if( p->trace ) os2MutexTrace(p, "try");
17857#endif
17858  }
17859  return rc;
17860}
17861
17862/*
17863** The sqlite3_mutex_leave() routine exits a mutex that was
17864** previously entered by the same thread.  The behavior
17865** is undefined if the mutex is not currently entered or
17866** is not currently allocated.  SQLite will never do either.
17867*/
17868static void os2MutexLeave(sqlite3_mutex *p){
17869  assert( os2MutexHeld(p) );
17870  DosReleaseMutexSem(p->mutex);
17871#ifdef SQLITE_DEBUG
17872  if( p->trace ) os2MutexTrace(p, "leave");
17873#endif
17874}
17875
17876SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17877  static const sqlite3_mutex_methods sMutex = {
17878    os2MutexInit,
17879    os2MutexEnd,
17880    os2MutexAlloc,
17881    os2MutexFree,
17882    os2MutexEnter,
17883    os2MutexTry,
17884    os2MutexLeave,
17885#ifdef SQLITE_DEBUG
17886    os2MutexHeld,
17887    os2MutexNotheld
17888#else
17889    0,
17890    0
17891#endif
17892  };
17893
17894  return &sMutex;
17895}
17896#endif /* SQLITE_MUTEX_OS2 */
17897
17898/************** End of mutex_os2.c *******************************************/
17899/************** Begin file mutex_unix.c **************************************/
17900/*
17901** 2007 August 28
17902**
17903** The author disclaims copyright to this source code.  In place of
17904** a legal notice, here is a blessing:
17905**
17906**    May you do good and not evil.
17907**    May you find forgiveness for yourself and forgive others.
17908**    May you share freely, never taking more than you give.
17909**
17910*************************************************************************
17911** This file contains the C functions that implement mutexes for pthreads
17912*/
17913
17914/*
17915** The code in this file is only used if we are compiling threadsafe
17916** under unix with pthreads.
17917**
17918** Note that this implementation requires a version of pthreads that
17919** supports recursive mutexes.
17920*/
17921#ifdef SQLITE_MUTEX_PTHREADS
17922
17923#include <pthread.h>
17924
17925/*
17926** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17927** are necessary under two condidtions:  (1) Debug builds and (2) using
17928** home-grown mutexes.  Encapsulate these conditions into a single #define.
17929*/
17930#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17931# define SQLITE_MUTEX_NREF 1
17932#else
17933# define SQLITE_MUTEX_NREF 0
17934#endif
17935
17936/*
17937** Each recursive mutex is an instance of the following structure.
17938*/
17939struct sqlite3_mutex {
17940  pthread_mutex_t mutex;     /* Mutex controlling the lock */
17941#if SQLITE_MUTEX_NREF
17942  int id;                    /* Mutex type */
17943  volatile int nRef;         /* Number of entrances */
17944  volatile pthread_t owner;  /* Thread that is within this mutex */
17945  int trace;                 /* True to trace changes */
17946#endif
17947};
17948#if SQLITE_MUTEX_NREF
17949#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17950#else
17951#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17952#endif
17953
17954/*
17955** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17956** intended for use only inside assert() statements.  On some platforms,
17957** there might be race conditions that can cause these routines to
17958** deliver incorrect results.  In particular, if pthread_equal() is
17959** not an atomic operation, then these routines might delivery
17960** incorrect results.  On most platforms, pthread_equal() is a
17961** comparison of two integers and is therefore atomic.  But we are
17962** told that HPUX is not such a platform.  If so, then these routines
17963** will not always work correctly on HPUX.
17964**
17965** On those platforms where pthread_equal() is not atomic, SQLite
17966** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17967** make sure no assert() statements are evaluated and hence these
17968** routines are never called.
17969*/
17970#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17971static int pthreadMutexHeld(sqlite3_mutex *p){
17972  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17973}
17974static int pthreadMutexNotheld(sqlite3_mutex *p){
17975  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17976}
17977#endif
17978
17979/*
17980** Initialize and deinitialize the mutex subsystem.
17981*/
17982static int pthreadMutexInit(void){ return SQLITE_OK; }
17983static int pthreadMutexEnd(void){ return SQLITE_OK; }
17984
17985/*
17986** The sqlite3_mutex_alloc() routine allocates a new
17987** mutex and returns a pointer to it.  If it returns NULL
17988** that means that a mutex could not be allocated.  SQLite
17989** will unwind its stack and return an error.  The argument
17990** to sqlite3_mutex_alloc() is one of these integer constants:
17991**
17992** <ul>
17993** <li>  SQLITE_MUTEX_FAST
17994** <li>  SQLITE_MUTEX_RECURSIVE
17995** <li>  SQLITE_MUTEX_STATIC_MASTER
17996** <li>  SQLITE_MUTEX_STATIC_MEM
17997** <li>  SQLITE_MUTEX_STATIC_MEM2
17998** <li>  SQLITE_MUTEX_STATIC_PRNG
17999** <li>  SQLITE_MUTEX_STATIC_LRU
18000** <li>  SQLITE_MUTEX_STATIC_PMEM
18001** </ul>
18002**
18003** The first two constants cause sqlite3_mutex_alloc() to create
18004** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18005** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18006** The mutex implementation does not need to make a distinction
18007** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18008** not want to.  But SQLite will only request a recursive mutex in
18009** cases where it really needs one.  If a faster non-recursive mutex
18010** implementation is available on the host platform, the mutex subsystem
18011** might return such a mutex in response to SQLITE_MUTEX_FAST.
18012**
18013** The other allowed parameters to sqlite3_mutex_alloc() each return
18014** a pointer to a static preexisting mutex.  Six static mutexes are
18015** used by the current version of SQLite.  Future versions of SQLite
18016** may add additional static mutexes.  Static mutexes are for internal
18017** use by SQLite only.  Applications that use SQLite mutexes should
18018** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18019** SQLITE_MUTEX_RECURSIVE.
18020**
18021** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18022** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18023** returns a different mutex on every call.  But for the static
18024** mutex types, the same mutex is returned on every call that has
18025** the same type number.
18026*/
18027static sqlite3_mutex *pthreadMutexAlloc(int iType){
18028  static sqlite3_mutex staticMutexes[] = {
18029    SQLITE3_MUTEX_INITIALIZER,
18030    SQLITE3_MUTEX_INITIALIZER,
18031    SQLITE3_MUTEX_INITIALIZER,
18032    SQLITE3_MUTEX_INITIALIZER,
18033    SQLITE3_MUTEX_INITIALIZER,
18034    SQLITE3_MUTEX_INITIALIZER
18035  };
18036  sqlite3_mutex *p;
18037  switch( iType ){
18038    case SQLITE_MUTEX_RECURSIVE: {
18039      p = sqlite3MallocZero( sizeof(*p) );
18040      if( p ){
18041#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18042        /* If recursive mutexes are not available, we will have to
18043        ** build our own.  See below. */
18044        pthread_mutex_init(&p->mutex, 0);
18045#else
18046        /* Use a recursive mutex if it is available */
18047        pthread_mutexattr_t recursiveAttr;
18048        pthread_mutexattr_init(&recursiveAttr);
18049        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18050        pthread_mutex_init(&p->mutex, &recursiveAttr);
18051        pthread_mutexattr_destroy(&recursiveAttr);
18052#endif
18053#if SQLITE_MUTEX_NREF
18054        p->id = iType;
18055#endif
18056      }
18057      break;
18058    }
18059    case SQLITE_MUTEX_FAST: {
18060      p = sqlite3MallocZero( sizeof(*p) );
18061      if( p ){
18062#if SQLITE_MUTEX_NREF
18063        p->id = iType;
18064#endif
18065        pthread_mutex_init(&p->mutex, 0);
18066      }
18067      break;
18068    }
18069    default: {
18070      assert( iType-2 >= 0 );
18071      assert( iType-2 < ArraySize(staticMutexes) );
18072      p = &staticMutexes[iType-2];
18073#if SQLITE_MUTEX_NREF
18074      p->id = iType;
18075#endif
18076      break;
18077    }
18078  }
18079  return p;
18080}
18081
18082
18083/*
18084** This routine deallocates a previously
18085** allocated mutex.  SQLite is careful to deallocate every
18086** mutex that it allocates.
18087*/
18088static void pthreadMutexFree(sqlite3_mutex *p){
18089  assert( p->nRef==0 );
18090  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18091  pthread_mutex_destroy(&p->mutex);
18092  sqlite3_free(p);
18093}
18094
18095/*
18096** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18097** to enter a mutex.  If another thread is already within the mutex,
18098** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18099** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18100** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18101** be entered multiple times by the same thread.  In such cases the,
18102** mutex must be exited an equal number of times before another thread
18103** can enter.  If the same thread tries to enter any other kind of mutex
18104** more than once, the behavior is undefined.
18105*/
18106static void pthreadMutexEnter(sqlite3_mutex *p){
18107  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18108
18109#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18110  /* If recursive mutexes are not available, then we have to grow
18111  ** our own.  This implementation assumes that pthread_equal()
18112  ** is atomic - that it cannot be deceived into thinking self
18113  ** and p->owner are equal if p->owner changes between two values
18114  ** that are not equal to self while the comparison is taking place.
18115  ** This implementation also assumes a coherent cache - that
18116  ** separate processes cannot read different values from the same
18117  ** address at the same time.  If either of these two conditions
18118  ** are not met, then the mutexes will fail and problems will result.
18119  */
18120  {
18121    pthread_t self = pthread_self();
18122    if( p->nRef>0 && pthread_equal(p->owner, self) ){
18123      p->nRef++;
18124    }else{
18125      pthread_mutex_lock(&p->mutex);
18126      assert( p->nRef==0 );
18127      p->owner = self;
18128      p->nRef = 1;
18129    }
18130  }
18131#else
18132  /* Use the built-in recursive mutexes if they are available.
18133  */
18134  pthread_mutex_lock(&p->mutex);
18135#if SQLITE_MUTEX_NREF
18136  assert( p->nRef>0 || p->owner==0 );
18137  p->owner = pthread_self();
18138  p->nRef++;
18139#endif
18140#endif
18141
18142#ifdef SQLITE_DEBUG
18143  if( p->trace ){
18144    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18145  }
18146#endif
18147}
18148static int pthreadMutexTry(sqlite3_mutex *p){
18149  int rc;
18150  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18151
18152#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18153  /* If recursive mutexes are not available, then we have to grow
18154  ** our own.  This implementation assumes that pthread_equal()
18155  ** is atomic - that it cannot be deceived into thinking self
18156  ** and p->owner are equal if p->owner changes between two values
18157  ** that are not equal to self while the comparison is taking place.
18158  ** This implementation also assumes a coherent cache - that
18159  ** separate processes cannot read different values from the same
18160  ** address at the same time.  If either of these two conditions
18161  ** are not met, then the mutexes will fail and problems will result.
18162  */
18163  {
18164    pthread_t self = pthread_self();
18165    if( p->nRef>0 && pthread_equal(p->owner, self) ){
18166      p->nRef++;
18167      rc = SQLITE_OK;
18168    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18169      assert( p->nRef==0 );
18170      p->owner = self;
18171      p->nRef = 1;
18172      rc = SQLITE_OK;
18173    }else{
18174      rc = SQLITE_BUSY;
18175    }
18176  }
18177#else
18178  /* Use the built-in recursive mutexes if they are available.
18179  */
18180  if( pthread_mutex_trylock(&p->mutex)==0 ){
18181#if SQLITE_MUTEX_NREF
18182    p->owner = pthread_self();
18183    p->nRef++;
18184#endif
18185    rc = SQLITE_OK;
18186  }else{
18187    rc = SQLITE_BUSY;
18188  }
18189#endif
18190
18191#ifdef SQLITE_DEBUG
18192  if( rc==SQLITE_OK && p->trace ){
18193    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18194  }
18195#endif
18196  return rc;
18197}
18198
18199/*
18200** The sqlite3_mutex_leave() routine exits a mutex that was
18201** previously entered by the same thread.  The behavior
18202** is undefined if the mutex is not currently entered or
18203** is not currently allocated.  SQLite will never do either.
18204*/
18205static void pthreadMutexLeave(sqlite3_mutex *p){
18206  assert( pthreadMutexHeld(p) );
18207#if SQLITE_MUTEX_NREF
18208  p->nRef--;
18209  if( p->nRef==0 ) p->owner = 0;
18210#endif
18211  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18212
18213#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18214  if( p->nRef==0 ){
18215    pthread_mutex_unlock(&p->mutex);
18216  }
18217#else
18218  pthread_mutex_unlock(&p->mutex);
18219#endif
18220
18221#ifdef SQLITE_DEBUG
18222  if( p->trace ){
18223    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18224  }
18225#endif
18226}
18227
18228SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18229  static const sqlite3_mutex_methods sMutex = {
18230    pthreadMutexInit,
18231    pthreadMutexEnd,
18232    pthreadMutexAlloc,
18233    pthreadMutexFree,
18234    pthreadMutexEnter,
18235    pthreadMutexTry,
18236    pthreadMutexLeave,
18237#ifdef SQLITE_DEBUG
18238    pthreadMutexHeld,
18239    pthreadMutexNotheld
18240#else
18241    0,
18242    0
18243#endif
18244  };
18245
18246  return &sMutex;
18247}
18248
18249#endif /* SQLITE_MUTEX_PTHREADS */
18250
18251/************** End of mutex_unix.c ******************************************/
18252/************** Begin file mutex_w32.c ***************************************/
18253/*
18254** 2007 August 14
18255**
18256** The author disclaims copyright to this source code.  In place of
18257** a legal notice, here is a blessing:
18258**
18259**    May you do good and not evil.
18260**    May you find forgiveness for yourself and forgive others.
18261**    May you share freely, never taking more than you give.
18262**
18263*************************************************************************
18264** This file contains the C functions that implement mutexes for win32
18265*/
18266
18267/*
18268** The code in this file is only used if we are compiling multithreaded
18269** on a win32 system.
18270*/
18271#ifdef SQLITE_MUTEX_W32
18272
18273/*
18274** Each recursive mutex is an instance of the following structure.
18275*/
18276struct sqlite3_mutex {
18277  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
18278  int id;                    /* Mutex type */
18279#ifdef SQLITE_DEBUG
18280  volatile int nRef;         /* Number of enterances */
18281  volatile DWORD owner;      /* Thread holding this mutex */
18282  int trace;                 /* True to trace changes */
18283#endif
18284};
18285#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18286#ifdef SQLITE_DEBUG
18287#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18288#else
18289#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18290#endif
18291
18292/*
18293** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18294** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
18295**
18296** Here is an interesting observation:  Win95, Win98, and WinME lack
18297** the LockFileEx() API.  But we can still statically link against that
18298** API as long as we don't call it win running Win95/98/ME.  A call to
18299** this routine is used to determine if the host is Win95/98/ME or
18300** WinNT/2K/XP so that we will know whether or not we can safely call
18301** the LockFileEx() API.
18302**
18303** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18304** which is only available if your application was compiled with
18305** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
18306** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
18307** this out as well.
18308*/
18309#if 0
18310#if SQLITE_OS_WINCE
18311# define mutexIsNT()  (1)
18312#else
18313  static int mutexIsNT(void){
18314    static int osType = 0;
18315    if( osType==0 ){
18316      OSVERSIONINFO sInfo;
18317      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18318      GetVersionEx(&sInfo);
18319      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18320    }
18321    return osType==2;
18322  }
18323#endif /* SQLITE_OS_WINCE */
18324#endif
18325
18326#ifdef SQLITE_DEBUG
18327/*
18328** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18329** intended for use only inside assert() statements.
18330*/
18331static int winMutexHeld(sqlite3_mutex *p){
18332  return p->nRef!=0 && p->owner==GetCurrentThreadId();
18333}
18334static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18335  return p->nRef==0 || p->owner!=tid;
18336}
18337static int winMutexNotheld(sqlite3_mutex *p){
18338  DWORD tid = GetCurrentThreadId();
18339  return winMutexNotheld2(p, tid);
18340}
18341#endif
18342
18343
18344/*
18345** Initialize and deinitialize the mutex subsystem.
18346*/
18347static sqlite3_mutex winMutex_staticMutexes[6] = {
18348  SQLITE3_MUTEX_INITIALIZER,
18349  SQLITE3_MUTEX_INITIALIZER,
18350  SQLITE3_MUTEX_INITIALIZER,
18351  SQLITE3_MUTEX_INITIALIZER,
18352  SQLITE3_MUTEX_INITIALIZER,
18353  SQLITE3_MUTEX_INITIALIZER
18354};
18355static int winMutex_isInit = 0;
18356/* As winMutexInit() and winMutexEnd() are called as part
18357** of the sqlite3_initialize and sqlite3_shutdown()
18358** processing, the "interlocked" magic is probably not
18359** strictly necessary.
18360*/
18361static long winMutex_lock = 0;
18362
18363static int winMutexInit(void){
18364  /* The first to increment to 1 does actual initialization */
18365  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18366    int i;
18367    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18368      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18369    }
18370    winMutex_isInit = 1;
18371  }else{
18372    /* Someone else is in the process of initing the static mutexes */
18373    while( !winMutex_isInit ){
18374      Sleep(1);
18375    }
18376  }
18377  return SQLITE_OK;
18378}
18379
18380static int winMutexEnd(void){
18381  /* The first to decrement to 0 does actual shutdown
18382  ** (which should be the last to shutdown.) */
18383  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18384    if( winMutex_isInit==1 ){
18385      int i;
18386      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18387        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18388      }
18389      winMutex_isInit = 0;
18390    }
18391  }
18392  return SQLITE_OK;
18393}
18394
18395/*
18396** The sqlite3_mutex_alloc() routine allocates a new
18397** mutex and returns a pointer to it.  If it returns NULL
18398** that means that a mutex could not be allocated.  SQLite
18399** will unwind its stack and return an error.  The argument
18400** to sqlite3_mutex_alloc() is one of these integer constants:
18401**
18402** <ul>
18403** <li>  SQLITE_MUTEX_FAST
18404** <li>  SQLITE_MUTEX_RECURSIVE
18405** <li>  SQLITE_MUTEX_STATIC_MASTER
18406** <li>  SQLITE_MUTEX_STATIC_MEM
18407** <li>  SQLITE_MUTEX_STATIC_MEM2
18408** <li>  SQLITE_MUTEX_STATIC_PRNG
18409** <li>  SQLITE_MUTEX_STATIC_LRU
18410** <li>  SQLITE_MUTEX_STATIC_PMEM
18411** </ul>
18412**
18413** The first two constants cause sqlite3_mutex_alloc() to create
18414** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18415** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18416** The mutex implementation does not need to make a distinction
18417** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18418** not want to.  But SQLite will only request a recursive mutex in
18419** cases where it really needs one.  If a faster non-recursive mutex
18420** implementation is available on the host platform, the mutex subsystem
18421** might return such a mutex in response to SQLITE_MUTEX_FAST.
18422**
18423** The other allowed parameters to sqlite3_mutex_alloc() each return
18424** a pointer to a static preexisting mutex.  Six static mutexes are
18425** used by the current version of SQLite.  Future versions of SQLite
18426** may add additional static mutexes.  Static mutexes are for internal
18427** use by SQLite only.  Applications that use SQLite mutexes should
18428** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18429** SQLITE_MUTEX_RECURSIVE.
18430**
18431** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18432** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18433** returns a different mutex on every call.  But for the static
18434** mutex types, the same mutex is returned on every call that has
18435** the same type number.
18436*/
18437static sqlite3_mutex *winMutexAlloc(int iType){
18438  sqlite3_mutex *p;
18439
18440  switch( iType ){
18441    case SQLITE_MUTEX_FAST:
18442    case SQLITE_MUTEX_RECURSIVE: {
18443      p = sqlite3MallocZero( sizeof(*p) );
18444      if( p ){
18445#ifdef SQLITE_DEBUG
18446        p->id = iType;
18447#endif
18448        InitializeCriticalSection(&p->mutex);
18449      }
18450      break;
18451    }
18452    default: {
18453      assert( winMutex_isInit==1 );
18454      assert( iType-2 >= 0 );
18455      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18456      p = &winMutex_staticMutexes[iType-2];
18457#ifdef SQLITE_DEBUG
18458      p->id = iType;
18459#endif
18460      break;
18461    }
18462  }
18463  return p;
18464}
18465
18466
18467/*
18468** This routine deallocates a previously
18469** allocated mutex.  SQLite is careful to deallocate every
18470** mutex that it allocates.
18471*/
18472static void winMutexFree(sqlite3_mutex *p){
18473  assert( p );
18474  assert( p->nRef==0 && p->owner==0 );
18475  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18476  DeleteCriticalSection(&p->mutex);
18477  sqlite3_free(p);
18478}
18479
18480/*
18481** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18482** to enter a mutex.  If another thread is already within the mutex,
18483** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18484** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18485** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18486** be entered multiple times by the same thread.  In such cases the,
18487** mutex must be exited an equal number of times before another thread
18488** can enter.  If the same thread tries to enter any other kind of mutex
18489** more than once, the behavior is undefined.
18490*/
18491static void winMutexEnter(sqlite3_mutex *p){
18492#ifdef SQLITE_DEBUG
18493  DWORD tid = GetCurrentThreadId();
18494  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18495#endif
18496  EnterCriticalSection(&p->mutex);
18497#ifdef SQLITE_DEBUG
18498  assert( p->nRef>0 || p->owner==0 );
18499  p->owner = tid;
18500  p->nRef++;
18501  if( p->trace ){
18502    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18503  }
18504#endif
18505}
18506static int winMutexTry(sqlite3_mutex *p){
18507#ifndef NDEBUG
18508  DWORD tid = GetCurrentThreadId();
18509#endif
18510  int rc = SQLITE_BUSY;
18511  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18512  /*
18513  ** The sqlite3_mutex_try() routine is very rarely used, and when it
18514  ** is used it is merely an optimization.  So it is OK for it to always
18515  ** fail.
18516  **
18517  ** The TryEnterCriticalSection() interface is only available on WinNT.
18518  ** And some windows compilers complain if you try to use it without
18519  ** first doing some #defines that prevent SQLite from building on Win98.
18520  ** For that reason, we will omit this optimization for now.  See
18521  ** ticket #2685.
18522  */
18523#if 0
18524  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18525    p->owner = tid;
18526    p->nRef++;
18527    rc = SQLITE_OK;
18528  }
18529#else
18530  UNUSED_PARAMETER(p);
18531#endif
18532#ifdef SQLITE_DEBUG
18533  if( rc==SQLITE_OK && p->trace ){
18534    printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18535  }
18536#endif
18537  return rc;
18538}
18539
18540/*
18541** The sqlite3_mutex_leave() routine exits a mutex that was
18542** previously entered by the same thread.  The behavior
18543** is undefined if the mutex is not currently entered or
18544** is not currently allocated.  SQLite will never do either.
18545*/
18546static void winMutexLeave(sqlite3_mutex *p){
18547#ifndef NDEBUG
18548  DWORD tid = GetCurrentThreadId();
18549  assert( p->nRef>0 );
18550  assert( p->owner==tid );
18551  p->nRef--;
18552  if( p->nRef==0 ) p->owner = 0;
18553  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18554#endif
18555  LeaveCriticalSection(&p->mutex);
18556#ifdef SQLITE_DEBUG
18557  if( p->trace ){
18558    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18559  }
18560#endif
18561}
18562
18563SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18564  static const sqlite3_mutex_methods sMutex = {
18565    winMutexInit,
18566    winMutexEnd,
18567    winMutexAlloc,
18568    winMutexFree,
18569    winMutexEnter,
18570    winMutexTry,
18571    winMutexLeave,
18572#ifdef SQLITE_DEBUG
18573    winMutexHeld,
18574    winMutexNotheld
18575#else
18576    0,
18577    0
18578#endif
18579  };
18580
18581  return &sMutex;
18582}
18583#endif /* SQLITE_MUTEX_W32 */
18584
18585/************** End of mutex_w32.c *******************************************/
18586/************** Begin file malloc.c ******************************************/
18587/*
18588** 2001 September 15
18589**
18590** The author disclaims copyright to this source code.  In place of
18591** a legal notice, here is a blessing:
18592**
18593**    May you do good and not evil.
18594**    May you find forgiveness for yourself and forgive others.
18595**    May you share freely, never taking more than you give.
18596**
18597*************************************************************************
18598**
18599** Memory allocation functions used throughout sqlite.
18600*/
18601/* #include <stdarg.h> */
18602
18603/*
18604** Attempt to release up to n bytes of non-essential memory currently
18605** held by SQLite. An example of non-essential memory is memory used to
18606** cache database pages that are not currently in use.
18607*/
18608SQLITE_API int sqlite3_release_memory(int n){
18609#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18610  return sqlite3PcacheReleaseMemory(n);
18611#else
18612  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18613  ** is a no-op returning zero if SQLite is not compiled with
18614  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18615  UNUSED_PARAMETER(n);
18616  return 0;
18617#endif
18618}
18619
18620/*
18621** An instance of the following object records the location of
18622** each unused scratch buffer.
18623*/
18624typedef struct ScratchFreeslot {
18625  struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18626} ScratchFreeslot;
18627
18628/*
18629** State information local to the memory allocation subsystem.
18630*/
18631static SQLITE_WSD struct Mem0Global {
18632  sqlite3_mutex *mutex;         /* Mutex to serialize access */
18633
18634  /*
18635  ** The alarm callback and its arguments.  The mem0.mutex lock will
18636  ** be held while the callback is running.  Recursive calls into
18637  ** the memory subsystem are allowed, but no new callbacks will be
18638  ** issued.
18639  */
18640  sqlite3_int64 alarmThreshold;
18641  void (*alarmCallback)(void*, sqlite3_int64,int);
18642  void *alarmArg;
18643
18644  /*
18645  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18646  ** (so that a range test can be used to determine if an allocation
18647  ** being freed came from pScratch) and a pointer to the list of
18648  ** unused scratch allocations.
18649  */
18650  void *pScratchEnd;
18651  ScratchFreeslot *pScratchFree;
18652  u32 nScratchFree;
18653
18654  /*
18655  ** True if heap is nearly "full" where "full" is defined by the
18656  ** sqlite3_soft_heap_limit() setting.
18657  */
18658  int nearlyFull;
18659} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18660
18661#define mem0 GLOBAL(struct Mem0Global, mem0)
18662
18663/*
18664** This routine runs when the memory allocator sees that the
18665** total memory allocation is about to exceed the soft heap
18666** limit.
18667*/
18668static void softHeapLimitEnforcer(
18669  void *NotUsed,
18670  sqlite3_int64 NotUsed2,
18671  int allocSize
18672){
18673  UNUSED_PARAMETER2(NotUsed, NotUsed2);
18674  sqlite3_release_memory(allocSize);
18675}
18676
18677/*
18678** Change the alarm callback
18679*/
18680static int sqlite3MemoryAlarm(
18681  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18682  void *pArg,
18683  sqlite3_int64 iThreshold
18684){
18685  int nUsed;
18686  sqlite3_mutex_enter(mem0.mutex);
18687  mem0.alarmCallback = xCallback;
18688  mem0.alarmArg = pArg;
18689  mem0.alarmThreshold = iThreshold;
18690  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18691  mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18692  sqlite3_mutex_leave(mem0.mutex);
18693  return SQLITE_OK;
18694}
18695
18696#ifndef SQLITE_OMIT_DEPRECATED
18697/*
18698** Deprecated external interface.  Internal/core SQLite code
18699** should call sqlite3MemoryAlarm.
18700*/
18701SQLITE_API int sqlite3_memory_alarm(
18702  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18703  void *pArg,
18704  sqlite3_int64 iThreshold
18705){
18706  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18707}
18708#endif
18709
18710/*
18711** Set the soft heap-size limit for the library. Passing a zero or
18712** negative value indicates no limit.
18713*/
18714SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18715  sqlite3_int64 priorLimit;
18716  sqlite3_int64 excess;
18717#ifndef SQLITE_OMIT_AUTOINIT
18718  int rc = sqlite3_initialize();
18719  if( rc ) return -1;
18720#endif
18721  sqlite3_mutex_enter(mem0.mutex);
18722  priorLimit = mem0.alarmThreshold;
18723  sqlite3_mutex_leave(mem0.mutex);
18724  if( n<0 ) return priorLimit;
18725  if( n>0 ){
18726    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18727  }else{
18728    sqlite3MemoryAlarm(0, 0, 0);
18729  }
18730  excess = sqlite3_memory_used() - n;
18731  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18732  return priorLimit;
18733}
18734SQLITE_API void sqlite3_soft_heap_limit(int n){
18735  if( n<0 ) n = 0;
18736  sqlite3_soft_heap_limit64(n);
18737}
18738
18739/*
18740** Initialize the memory allocation subsystem.
18741*/
18742SQLITE_PRIVATE int sqlite3MallocInit(void){
18743  if( sqlite3GlobalConfig.m.xMalloc==0 ){
18744    sqlite3MemSetDefault();
18745  }
18746  memset(&mem0, 0, sizeof(mem0));
18747  if( sqlite3GlobalConfig.bCoreMutex ){
18748    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18749  }
18750  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18751      && sqlite3GlobalConfig.nScratch>0 ){
18752    int i, n, sz;
18753    ScratchFreeslot *pSlot;
18754    sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18755    sqlite3GlobalConfig.szScratch = sz;
18756    pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18757    n = sqlite3GlobalConfig.nScratch;
18758    mem0.pScratchFree = pSlot;
18759    mem0.nScratchFree = n;
18760    for(i=0; i<n-1; i++){
18761      pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18762      pSlot = pSlot->pNext;
18763    }
18764    pSlot->pNext = 0;
18765    mem0.pScratchEnd = (void*)&pSlot[1];
18766  }else{
18767    mem0.pScratchEnd = 0;
18768    sqlite3GlobalConfig.pScratch = 0;
18769    sqlite3GlobalConfig.szScratch = 0;
18770    sqlite3GlobalConfig.nScratch = 0;
18771  }
18772  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18773      || sqlite3GlobalConfig.nPage<1 ){
18774    sqlite3GlobalConfig.pPage = 0;
18775    sqlite3GlobalConfig.szPage = 0;
18776    sqlite3GlobalConfig.nPage = 0;
18777  }
18778  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18779}
18780
18781/*
18782** Return true if the heap is currently under memory pressure - in other
18783** words if the amount of heap used is close to the limit set by
18784** sqlite3_soft_heap_limit().
18785*/
18786SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18787  return mem0.nearlyFull;
18788}
18789
18790/*
18791** Deinitialize the memory allocation subsystem.
18792*/
18793SQLITE_PRIVATE void sqlite3MallocEnd(void){
18794  if( sqlite3GlobalConfig.m.xShutdown ){
18795    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18796  }
18797  memset(&mem0, 0, sizeof(mem0));
18798}
18799
18800/*
18801** Return the amount of memory currently checked out.
18802*/
18803SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18804  int n, mx;
18805  sqlite3_int64 res;
18806  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18807  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
18808  return res;
18809}
18810
18811/*
18812** Return the maximum amount of memory that has ever been
18813** checked out since either the beginning of this process
18814** or since the most recent reset.
18815*/
18816SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18817  int n, mx;
18818  sqlite3_int64 res;
18819  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
18820  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
18821  return res;
18822}
18823
18824/*
18825** Trigger the alarm
18826*/
18827static void sqlite3MallocAlarm(int nByte){
18828  void (*xCallback)(void*,sqlite3_int64,int);
18829  sqlite3_int64 nowUsed;
18830  void *pArg;
18831  if( mem0.alarmCallback==0 ) return;
18832  xCallback = mem0.alarmCallback;
18833  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18834  pArg = mem0.alarmArg;
18835  mem0.alarmCallback = 0;
18836  sqlite3_mutex_leave(mem0.mutex);
18837  xCallback(pArg, nowUsed, nByte);
18838  sqlite3_mutex_enter(mem0.mutex);
18839  mem0.alarmCallback = xCallback;
18840  mem0.alarmArg = pArg;
18841}
18842
18843/*
18844** Do a memory allocation with statistics and alarms.  Assume the
18845** lock is already held.
18846*/
18847static int mallocWithAlarm(int n, void **pp){
18848  int nFull;
18849  void *p;
18850  assert( sqlite3_mutex_held(mem0.mutex) );
18851  nFull = sqlite3GlobalConfig.m.xRoundup(n);
18852  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
18853  if( mem0.alarmCallback!=0 ){
18854    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18855    if( nUsed >= mem0.alarmThreshold - nFull ){
18856      mem0.nearlyFull = 1;
18857      sqlite3MallocAlarm(nFull);
18858    }else{
18859      mem0.nearlyFull = 0;
18860    }
18861  }
18862  p = sqlite3GlobalConfig.m.xMalloc(nFull);
18863#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18864  if( p==0 && mem0.alarmCallback ){
18865    sqlite3MallocAlarm(nFull);
18866    p = sqlite3GlobalConfig.m.xMalloc(nFull);
18867  }
18868#endif
18869  if( p ){
18870    nFull = sqlite3MallocSize(p);
18871    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
18872    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
18873  }
18874  *pp = p;
18875  return nFull;
18876}
18877
18878/*
18879** Allocate memory.  This routine is like sqlite3_malloc() except that it
18880** assumes the memory subsystem has already been initialized.
18881*/
18882SQLITE_PRIVATE void *sqlite3Malloc(int n){
18883  void *p;
18884  if( n<=0               /* IMP: R-65312-04917 */
18885   || n>=0x7fffff00
18886  ){
18887    /* A memory allocation of a number of bytes which is near the maximum
18888    ** signed integer value might cause an integer overflow inside of the
18889    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
18890    ** 255 bytes of overhead.  SQLite itself will never use anything near
18891    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
18892    p = 0;
18893  }else if( sqlite3GlobalConfig.bMemstat ){
18894    sqlite3_mutex_enter(mem0.mutex);
18895    mallocWithAlarm(n, &p);
18896    sqlite3_mutex_leave(mem0.mutex);
18897  }else{
18898    p = sqlite3GlobalConfig.m.xMalloc(n);
18899  }
18900  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
18901  return p;
18902}
18903
18904/*
18905** This version of the memory allocation is for use by the application.
18906** First make sure the memory subsystem is initialized, then do the
18907** allocation.
18908*/
18909SQLITE_API void *sqlite3_malloc(int n){
18910#ifndef SQLITE_OMIT_AUTOINIT
18911  if( sqlite3_initialize() ) return 0;
18912#endif
18913  return sqlite3Malloc(n);
18914}
18915
18916/*
18917** Each thread may only have a single outstanding allocation from
18918** xScratchMalloc().  We verify this constraint in the single-threaded
18919** case by setting scratchAllocOut to 1 when an allocation
18920** is outstanding clearing it when the allocation is freed.
18921*/
18922#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18923static int scratchAllocOut = 0;
18924#endif
18925
18926
18927/*
18928** Allocate memory that is to be used and released right away.
18929** This routine is similar to alloca() in that it is not intended
18930** for situations where the memory might be held long-term.  This
18931** routine is intended to get memory to old large transient data
18932** structures that would not normally fit on the stack of an
18933** embedded processor.
18934*/
18935SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18936  void *p;
18937  assert( n>0 );
18938
18939  sqlite3_mutex_enter(mem0.mutex);
18940  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18941    p = mem0.pScratchFree;
18942    mem0.pScratchFree = mem0.pScratchFree->pNext;
18943    mem0.nScratchFree--;
18944    sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18945    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18946    sqlite3_mutex_leave(mem0.mutex);
18947  }else{
18948    if( sqlite3GlobalConfig.bMemstat ){
18949      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18950      n = mallocWithAlarm(n, &p);
18951      if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18952      sqlite3_mutex_leave(mem0.mutex);
18953    }else{
18954      sqlite3_mutex_leave(mem0.mutex);
18955      p = sqlite3GlobalConfig.m.xMalloc(n);
18956    }
18957    sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18958  }
18959  assert( sqlite3_mutex_notheld(mem0.mutex) );
18960
18961
18962#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18963  /* Verify that no more than two scratch allocations per thread
18964  ** are outstanding at one time.  (This is only checked in the
18965  ** single-threaded case since checking in the multi-threaded case
18966  ** would be much more complicated.) */
18967  assert( scratchAllocOut<=1 );
18968  if( p ) scratchAllocOut++;
18969#endif
18970
18971  return p;
18972}
18973SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18974  if( p ){
18975
18976#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18977    /* Verify that no more than two scratch allocation per thread
18978    ** is outstanding at one time.  (This is only checked in the
18979    ** single-threaded case since checking in the multi-threaded case
18980    ** would be much more complicated.) */
18981    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18982    scratchAllocOut--;
18983#endif
18984
18985    if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18986      /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18987      ScratchFreeslot *pSlot;
18988      pSlot = (ScratchFreeslot*)p;
18989      sqlite3_mutex_enter(mem0.mutex);
18990      pSlot->pNext = mem0.pScratchFree;
18991      mem0.pScratchFree = pSlot;
18992      mem0.nScratchFree++;
18993      assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18994      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18995      sqlite3_mutex_leave(mem0.mutex);
18996    }else{
18997      /* Release memory back to the heap */
18998      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18999      assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
19000      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19001      if( sqlite3GlobalConfig.bMemstat ){
19002        int iSize = sqlite3MallocSize(p);
19003        sqlite3_mutex_enter(mem0.mutex);
19004        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
19005        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
19006        sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19007        sqlite3GlobalConfig.m.xFree(p);
19008        sqlite3_mutex_leave(mem0.mutex);
19009      }else{
19010        sqlite3GlobalConfig.m.xFree(p);
19011      }
19012    }
19013  }
19014}
19015
19016/*
19017** TRUE if p is a lookaside memory allocation from db
19018*/
19019#ifndef SQLITE_OMIT_LOOKASIDE
19020static int isLookaside(sqlite3 *db, void *p){
19021  return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19022}
19023#else
19024#define isLookaside(A,B) 0
19025#endif
19026
19027/*
19028** Return the size of a memory allocation previously obtained from
19029** sqlite3Malloc() or sqlite3_malloc().
19030*/
19031SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19032  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19033  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19034  return sqlite3GlobalConfig.m.xSize(p);
19035}
19036SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19037  assert( db==0 || sqlite3_mutex_held(db->mutex) );
19038  if( db && isLookaside(db, p) ){
19039    return db->lookaside.sz;
19040  }else{
19041    assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19042    assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19043    assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19044    return sqlite3GlobalConfig.m.xSize(p);
19045  }
19046}
19047
19048/*
19049** Free memory previously obtained from sqlite3Malloc().
19050*/
19051SQLITE_API void sqlite3_free(void *p){
19052  if( p==0 ) return;  /* IMP: R-49053-54554 */
19053  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19054  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19055  if( sqlite3GlobalConfig.bMemstat ){
19056    sqlite3_mutex_enter(mem0.mutex);
19057    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19058    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19059    sqlite3GlobalConfig.m.xFree(p);
19060    sqlite3_mutex_leave(mem0.mutex);
19061  }else{
19062    sqlite3GlobalConfig.m.xFree(p);
19063  }
19064}
19065
19066/*
19067** Free memory that might be associated with a particular database
19068** connection.
19069*/
19070SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19071  assert( db==0 || sqlite3_mutex_held(db->mutex) );
19072  if( db ){
19073    if( db->pnBytesFreed ){
19074      *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19075      return;
19076    }
19077    if( isLookaside(db, p) ){
19078      LookasideSlot *pBuf = (LookasideSlot*)p;
19079      pBuf->pNext = db->lookaside.pFree;
19080      db->lookaside.pFree = pBuf;
19081      db->lookaside.nOut--;
19082      return;
19083    }
19084  }
19085  assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19086  assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19087  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19088  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19089  sqlite3_free(p);
19090}
19091
19092/*
19093** Change the size of an existing memory allocation
19094*/
19095SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19096  int nOld, nNew, nDiff;
19097  void *pNew;
19098  if( pOld==0 ){
19099    return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19100  }
19101  if( nBytes<=0 ){
19102    sqlite3_free(pOld); /* IMP: R-31593-10574 */
19103    return 0;
19104  }
19105  if( nBytes>=0x7fffff00 ){
19106    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19107    return 0;
19108  }
19109  nOld = sqlite3MallocSize(pOld);
19110  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19111  ** argument to xRealloc is always a value returned by a prior call to
19112  ** xRoundup. */
19113  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19114  if( nOld==nNew ){
19115    pNew = pOld;
19116  }else if( sqlite3GlobalConfig.bMemstat ){
19117    sqlite3_mutex_enter(mem0.mutex);
19118    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19119    nDiff = nNew - nOld;
19120    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
19121          mem0.alarmThreshold-nDiff ){
19122      sqlite3MallocAlarm(nDiff);
19123    }
19124    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19125    assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19126    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19127    if( pNew==0 && mem0.alarmCallback ){
19128      sqlite3MallocAlarm(nBytes);
19129      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19130    }
19131    if( pNew ){
19132      nNew = sqlite3MallocSize(pNew);
19133      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19134    }
19135    sqlite3_mutex_leave(mem0.mutex);
19136  }else{
19137    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19138  }
19139  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19140  return pNew;
19141}
19142
19143/*
19144** The public interface to sqlite3Realloc.  Make sure that the memory
19145** subsystem is initialized prior to invoking sqliteRealloc.
19146*/
19147SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19148#ifndef SQLITE_OMIT_AUTOINIT
19149  if( sqlite3_initialize() ) return 0;
19150#endif
19151  return sqlite3Realloc(pOld, n);
19152}
19153
19154
19155/*
19156** Allocate and zero memory.
19157*/
19158SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19159  void *p = sqlite3Malloc(n);
19160  if( p ){
19161    memset(p, 0, n);
19162  }
19163  return p;
19164}
19165
19166/*
19167** Allocate and zero memory.  If the allocation fails, make
19168** the mallocFailed flag in the connection pointer.
19169*/
19170SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19171  void *p = sqlite3DbMallocRaw(db, n);
19172  if( p ){
19173    memset(p, 0, n);
19174  }
19175  return p;
19176}
19177
19178/*
19179** Allocate and zero memory.  If the allocation fails, make
19180** the mallocFailed flag in the connection pointer.
19181**
19182** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19183** failure on the same database connection) then always return 0.
19184** Hence for a particular database connection, once malloc starts
19185** failing, it fails consistently until mallocFailed is reset.
19186** This is an important assumption.  There are many places in the
19187** code that do things like this:
19188**
19189**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
19190**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
19191**         if( b ) a[10] = 9;
19192**
19193** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19194** that all prior mallocs (ex: "a") worked too.
19195*/
19196SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19197  void *p;
19198  assert( db==0 || sqlite3_mutex_held(db->mutex) );
19199  assert( db==0 || db->pnBytesFreed==0 );
19200#ifndef SQLITE_OMIT_LOOKASIDE
19201  if( db ){
19202    LookasideSlot *pBuf;
19203    if( db->mallocFailed ){
19204      return 0;
19205    }
19206    if( db->lookaside.bEnabled ){
19207      if( n>db->lookaside.sz ){
19208        db->lookaside.anStat[1]++;
19209      }else if( (pBuf = db->lookaside.pFree)==0 ){
19210        db->lookaside.anStat[2]++;
19211      }else{
19212        db->lookaside.pFree = pBuf->pNext;
19213        db->lookaside.nOut++;
19214        db->lookaside.anStat[0]++;
19215        if( db->lookaside.nOut>db->lookaside.mxOut ){
19216          db->lookaside.mxOut = db->lookaside.nOut;
19217        }
19218        return (void*)pBuf;
19219      }
19220    }
19221  }
19222#else
19223  if( db && db->mallocFailed ){
19224    return 0;
19225  }
19226#endif
19227  p = sqlite3Malloc(n);
19228  if( !p && db ){
19229    db->mallocFailed = 1;
19230  }
19231  sqlite3MemdebugSetType(p, MEMTYPE_DB |
19232         ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19233  return p;
19234}
19235
19236/*
19237** Resize the block of memory pointed to by p to n bytes. If the
19238** resize fails, set the mallocFailed flag in the connection object.
19239*/
19240SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19241  void *pNew = 0;
19242  assert( db!=0 );
19243  assert( sqlite3_mutex_held(db->mutex) );
19244  if( db->mallocFailed==0 ){
19245    if( p==0 ){
19246      return sqlite3DbMallocRaw(db, n);
19247    }
19248    if( isLookaside(db, p) ){
19249      if( n<=db->lookaside.sz ){
19250        return p;
19251      }
19252      pNew = sqlite3DbMallocRaw(db, n);
19253      if( pNew ){
19254        memcpy(pNew, p, db->lookaside.sz);
19255        sqlite3DbFree(db, p);
19256      }
19257    }else{
19258      assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19259      assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19260      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19261      pNew = sqlite3_realloc(p, n);
19262      if( !pNew ){
19263        sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19264        db->mallocFailed = 1;
19265      }
19266      sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
19267            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19268    }
19269  }
19270  return pNew;
19271}
19272
19273/*
19274** Attempt to reallocate p.  If the reallocation fails, then free p
19275** and set the mallocFailed flag in the database connection.
19276*/
19277SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19278  void *pNew;
19279  pNew = sqlite3DbRealloc(db, p, n);
19280  if( !pNew ){
19281    sqlite3DbFree(db, p);
19282  }
19283  return pNew;
19284}
19285
19286/*
19287** Make a copy of a string in memory obtained from sqliteMalloc(). These
19288** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19289** is because when memory debugging is turned on, these two functions are
19290** called via macros that record the current file and line number in the
19291** ThreadData structure.
19292*/
19293SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19294  char *zNew;
19295  size_t n;
19296  if( z==0 ){
19297    return 0;
19298  }
19299  n = sqlite3Strlen30(z) + 1;
19300  assert( (n&0x7fffffff)==n );
19301  zNew = sqlite3DbMallocRaw(db, (int)n);
19302  if( zNew ){
19303    memcpy(zNew, z, n);
19304  }
19305  return zNew;
19306}
19307SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19308  char *zNew;
19309  if( z==0 ){
19310    return 0;
19311  }
19312  assert( (n&0x7fffffff)==n );
19313  zNew = sqlite3DbMallocRaw(db, n+1);
19314  if( zNew ){
19315    memcpy(zNew, z, n);
19316    zNew[n] = 0;
19317  }
19318  return zNew;
19319}
19320
19321/*
19322** Create a string from the zFromat argument and the va_list that follows.
19323** Store the string in memory obtained from sqliteMalloc() and make *pz
19324** point to that string.
19325*/
19326SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19327  va_list ap;
19328  char *z;
19329
19330  va_start(ap, zFormat);
19331  z = sqlite3VMPrintf(db, zFormat, ap);
19332  va_end(ap);
19333  sqlite3DbFree(db, *pz);
19334  *pz = z;
19335}
19336
19337
19338/*
19339** This function must be called before exiting any API function (i.e.
19340** returning control to the user) that has called sqlite3_malloc or
19341** sqlite3_realloc.
19342**
19343** The returned value is normally a copy of the second argument to this
19344** function. However, if a malloc() failure has occurred since the previous
19345** invocation SQLITE_NOMEM is returned instead.
19346**
19347** If the first argument, db, is not NULL and a malloc() error has occurred,
19348** then the connection error-code (the value returned by sqlite3_errcode())
19349** is set to SQLITE_NOMEM.
19350*/
19351SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19352  /* If the db handle is not NULL, then we must hold the connection handle
19353  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
19354  ** is unsafe, as is the call to sqlite3Error().
19355  */
19356  assert( !db || sqlite3_mutex_held(db->mutex) );
19357  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19358    sqlite3Error(db, SQLITE_NOMEM, 0);
19359    db->mallocFailed = 0;
19360    rc = SQLITE_NOMEM;
19361  }
19362  return rc & (db ? db->errMask : 0xff);
19363}
19364
19365/************** End of malloc.c **********************************************/
19366/************** Begin file printf.c ******************************************/
19367/*
19368** The "printf" code that follows dates from the 1980's.  It is in
19369** the public domain.  The original comments are included here for
19370** completeness.  They are very out-of-date but might be useful as
19371** an historical reference.  Most of the "enhancements" have been backed
19372** out so that the functionality is now the same as standard printf().
19373**
19374**************************************************************************
19375**
19376** This file contains code for a set of "printf"-like routines.  These
19377** routines format strings much like the printf() from the standard C
19378** library, though the implementation here has enhancements to support
19379** SQLlite.
19380*/
19381
19382/*
19383** Conversion types fall into various categories as defined by the
19384** following enumeration.
19385*/
19386#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
19387#define etFLOAT       2 /* Floating point.  %f */
19388#define etEXP         3 /* Exponentional notation. %e and %E */
19389#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
19390#define etSIZE        5 /* Return number of characters processed so far. %n */
19391#define etSTRING      6 /* Strings. %s */
19392#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
19393#define etPERCENT     8 /* Percent symbol. %% */
19394#define etCHARX       9 /* Characters. %c */
19395/* The rest are extensions, not normally found in printf() */
19396#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
19397#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19398                          NULL pointers replaced by SQL NULL.  %Q */
19399#define etTOKEN      12 /* a pointer to a Token structure */
19400#define etSRCLIST    13 /* a pointer to a SrcList */
19401#define etPOINTER    14 /* The %p conversion */
19402#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19403#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
19404
19405#define etINVALID     0 /* Any unrecognized conversion type */
19406
19407
19408/*
19409** An "etByte" is an 8-bit unsigned value.
19410*/
19411typedef unsigned char etByte;
19412
19413/*
19414** Each builtin conversion character (ex: the 'd' in "%d") is described
19415** by an instance of the following structure
19416*/
19417typedef struct et_info {   /* Information about each format field */
19418  char fmttype;            /* The format field code letter */
19419  etByte base;             /* The base for radix conversion */
19420  etByte flags;            /* One or more of FLAG_ constants below */
19421  etByte type;             /* Conversion paradigm */
19422  etByte charset;          /* Offset into aDigits[] of the digits string */
19423  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
19424} et_info;
19425
19426/*
19427** Allowed values for et_info.flags
19428*/
19429#define FLAG_SIGNED  1     /* True if the value to convert is signed */
19430#define FLAG_INTERN  2     /* True if for internal use only */
19431#define FLAG_STRING  4     /* Allow infinity precision */
19432
19433
19434/*
19435** The following table is searched linearly, so it is good to put the
19436** most frequently used conversion types first.
19437*/
19438static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19439static const char aPrefix[] = "-x0\000X0";
19440static const et_info fmtinfo[] = {
19441  {  'd', 10, 1, etRADIX,      0,  0 },
19442  {  's',  0, 4, etSTRING,     0,  0 },
19443  {  'g',  0, 1, etGENERIC,    30, 0 },
19444  {  'z',  0, 4, etDYNSTRING,  0,  0 },
19445  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
19446  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
19447  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
19448  {  'c',  0, 0, etCHARX,      0,  0 },
19449  {  'o',  8, 0, etRADIX,      0,  2 },
19450  {  'u', 10, 0, etRADIX,      0,  0 },
19451  {  'x', 16, 0, etRADIX,      16, 1 },
19452  {  'X', 16, 0, etRADIX,      0,  4 },
19453#ifndef SQLITE_OMIT_FLOATING_POINT
19454  {  'f',  0, 1, etFLOAT,      0,  0 },
19455  {  'e',  0, 1, etEXP,        30, 0 },
19456  {  'E',  0, 1, etEXP,        14, 0 },
19457  {  'G',  0, 1, etGENERIC,    14, 0 },
19458#endif
19459  {  'i', 10, 1, etRADIX,      0,  0 },
19460  {  'n',  0, 0, etSIZE,       0,  0 },
19461  {  '%',  0, 0, etPERCENT,    0,  0 },
19462  {  'p', 16, 0, etPOINTER,    0,  1 },
19463
19464/* All the rest have the FLAG_INTERN bit set and are thus for internal
19465** use only */
19466  {  'T',  0, 2, etTOKEN,      0,  0 },
19467  {  'S',  0, 2, etSRCLIST,    0,  0 },
19468  {  'r', 10, 3, etORDINAL,    0,  0 },
19469};
19470
19471/*
19472** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19473** conversions will work.
19474*/
19475#ifndef SQLITE_OMIT_FLOATING_POINT
19476/*
19477** "*val" is a double such that 0.1 <= *val < 10.0
19478** Return the ascii code for the leading digit of *val, then
19479** multiply "*val" by 10.0 to renormalize.
19480**
19481** Example:
19482**     input:     *val = 3.14159
19483**     output:    *val = 1.4159    function return = '3'
19484**
19485** The counter *cnt is incremented each time.  After counter exceeds
19486** 16 (the number of significant digits in a 64-bit float) '0' is
19487** always returned.
19488*/
19489static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19490  int digit;
19491  LONGDOUBLE_TYPE d;
19492  if( (*cnt)++ >= 16 ) return '0';
19493  digit = (int)*val;
19494  d = digit;
19495  digit += '0';
19496  *val = (*val - d)*10.0;
19497  return (char)digit;
19498}
19499#endif /* SQLITE_OMIT_FLOATING_POINT */
19500
19501/*
19502** Append N space characters to the given string buffer.
19503*/
19504SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
19505  static const char zSpaces[] = "                             ";
19506  while( N>=(int)sizeof(zSpaces)-1 ){
19507    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19508    N -= sizeof(zSpaces)-1;
19509  }
19510  if( N>0 ){
19511    sqlite3StrAccumAppend(pAccum, zSpaces, N);
19512  }
19513}
19514
19515/*
19516** On machines with a small stack size, you can redefine the
19517** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19518*/
19519#ifndef SQLITE_PRINT_BUF_SIZE
19520# define SQLITE_PRINT_BUF_SIZE 70
19521#endif
19522#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
19523
19524/*
19525** Render a string given by "fmt" into the StrAccum object.
19526*/
19527SQLITE_PRIVATE void sqlite3VXPrintf(
19528  StrAccum *pAccum,                  /* Accumulate results here */
19529  int useExtended,                   /* Allow extended %-conversions */
19530  const char *fmt,                   /* Format string */
19531  va_list ap                         /* arguments */
19532){
19533  int c;                     /* Next character in the format string */
19534  char *bufpt;               /* Pointer to the conversion buffer */
19535  int precision;             /* Precision of the current field */
19536  int length;                /* Length of the field */
19537  int idx;                   /* A general purpose loop counter */
19538  int width;                 /* Width of the current field */
19539  etByte flag_leftjustify;   /* True if "-" flag is present */
19540  etByte flag_plussign;      /* True if "+" flag is present */
19541  etByte flag_blanksign;     /* True if " " flag is present */
19542  etByte flag_alternateform; /* True if "#" flag is present */
19543  etByte flag_altform2;      /* True if "!" flag is present */
19544  etByte flag_zeropad;       /* True if field width constant starts with zero */
19545  etByte flag_long;          /* True if "l" flag is present */
19546  etByte flag_longlong;      /* True if the "ll" flag is present */
19547  etByte done;               /* Loop termination flag */
19548  etByte xtype = 0;          /* Conversion paradigm */
19549  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19550  sqlite_uint64 longvalue;   /* Value for integer types */
19551  LONGDOUBLE_TYPE realvalue; /* Value for real types */
19552  const et_info *infop;      /* Pointer to the appropriate info structure */
19553  char *zOut;                /* Rendering buffer */
19554  int nOut;                  /* Size of the rendering buffer */
19555  char *zExtra;              /* Malloced memory used by some conversion */
19556#ifndef SQLITE_OMIT_FLOATING_POINT
19557  int  exp, e2;              /* exponent of real numbers */
19558  int nsd;                   /* Number of significant digits returned */
19559  double rounder;            /* Used for rounding floating point values */
19560  etByte flag_dp;            /* True if decimal point should be shown */
19561  etByte flag_rtz;           /* True if trailing zeros should be removed */
19562#endif
19563  char buf[etBUFSIZE];       /* Conversion buffer */
19564
19565  bufpt = 0;
19566  for(; (c=(*fmt))!=0; ++fmt){
19567    if( c!='%' ){
19568      int amt;
19569      bufpt = (char *)fmt;
19570      amt = 1;
19571      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19572      sqlite3StrAccumAppend(pAccum, bufpt, amt);
19573      if( c==0 ) break;
19574    }
19575    if( (c=(*++fmt))==0 ){
19576      sqlite3StrAccumAppend(pAccum, "%", 1);
19577      break;
19578    }
19579    /* Find out what flags are present */
19580    flag_leftjustify = flag_plussign = flag_blanksign =
19581     flag_alternateform = flag_altform2 = flag_zeropad = 0;
19582    done = 0;
19583    do{
19584      switch( c ){
19585        case '-':   flag_leftjustify = 1;     break;
19586        case '+':   flag_plussign = 1;        break;
19587        case ' ':   flag_blanksign = 1;       break;
19588        case '#':   flag_alternateform = 1;   break;
19589        case '!':   flag_altform2 = 1;        break;
19590        case '0':   flag_zeropad = 1;         break;
19591        default:    done = 1;                 break;
19592      }
19593    }while( !done && (c=(*++fmt))!=0 );
19594    /* Get the field width */
19595    width = 0;
19596    if( c=='*' ){
19597      width = va_arg(ap,int);
19598      if( width<0 ){
19599        flag_leftjustify = 1;
19600        width = -width;
19601      }
19602      c = *++fmt;
19603    }else{
19604      while( c>='0' && c<='9' ){
19605        width = width*10 + c - '0';
19606        c = *++fmt;
19607      }
19608    }
19609    /* Get the precision */
19610    if( c=='.' ){
19611      precision = 0;
19612      c = *++fmt;
19613      if( c=='*' ){
19614        precision = va_arg(ap,int);
19615        if( precision<0 ) precision = -precision;
19616        c = *++fmt;
19617      }else{
19618        while( c>='0' && c<='9' ){
19619          precision = precision*10 + c - '0';
19620          c = *++fmt;
19621        }
19622      }
19623    }else{
19624      precision = -1;
19625    }
19626    /* Get the conversion type modifier */
19627    if( c=='l' ){
19628      flag_long = 1;
19629      c = *++fmt;
19630      if( c=='l' ){
19631        flag_longlong = 1;
19632        c = *++fmt;
19633      }else{
19634        flag_longlong = 0;
19635      }
19636    }else{
19637      flag_long = flag_longlong = 0;
19638    }
19639    /* Fetch the info entry for the field */
19640    infop = &fmtinfo[0];
19641    xtype = etINVALID;
19642    for(idx=0; idx<ArraySize(fmtinfo); idx++){
19643      if( c==fmtinfo[idx].fmttype ){
19644        infop = &fmtinfo[idx];
19645        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19646          xtype = infop->type;
19647        }else{
19648          return;
19649        }
19650        break;
19651      }
19652    }
19653    zExtra = 0;
19654
19655    /*
19656    ** At this point, variables are initialized as follows:
19657    **
19658    **   flag_alternateform          TRUE if a '#' is present.
19659    **   flag_altform2               TRUE if a '!' is present.
19660    **   flag_plussign               TRUE if a '+' is present.
19661    **   flag_leftjustify            TRUE if a '-' is present or if the
19662    **                               field width was negative.
19663    **   flag_zeropad                TRUE if the width began with 0.
19664    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
19665    **                               the conversion character.
19666    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
19667    **                               the conversion character.
19668    **   flag_blanksign              TRUE if a ' ' is present.
19669    **   width                       The specified field width.  This is
19670    **                               always non-negative.  Zero is the default.
19671    **   precision                   The specified precision.  The default
19672    **                               is -1.
19673    **   xtype                       The class of the conversion.
19674    **   infop                       Pointer to the appropriate info struct.
19675    */
19676    switch( xtype ){
19677      case etPOINTER:
19678        flag_longlong = sizeof(char*)==sizeof(i64);
19679        flag_long = sizeof(char*)==sizeof(long int);
19680        /* Fall through into the next case */
19681      case etORDINAL:
19682      case etRADIX:
19683        if( infop->flags & FLAG_SIGNED ){
19684          i64 v;
19685          if( flag_longlong ){
19686            v = va_arg(ap,i64);
19687          }else if( flag_long ){
19688            v = va_arg(ap,long int);
19689          }else{
19690            v = va_arg(ap,int);
19691          }
19692          if( v<0 ){
19693            if( v==SMALLEST_INT64 ){
19694              longvalue = ((u64)1)<<63;
19695            }else{
19696              longvalue = -v;
19697            }
19698            prefix = '-';
19699          }else{
19700            longvalue = v;
19701            if( flag_plussign )        prefix = '+';
19702            else if( flag_blanksign )  prefix = ' ';
19703            else                       prefix = 0;
19704          }
19705        }else{
19706          if( flag_longlong ){
19707            longvalue = va_arg(ap,u64);
19708          }else if( flag_long ){
19709            longvalue = va_arg(ap,unsigned long int);
19710          }else{
19711            longvalue = va_arg(ap,unsigned int);
19712          }
19713          prefix = 0;
19714        }
19715        if( longvalue==0 ) flag_alternateform = 0;
19716        if( flag_zeropad && precision<width-(prefix!=0) ){
19717          precision = width-(prefix!=0);
19718        }
19719        if( precision<etBUFSIZE-10 ){
19720          nOut = etBUFSIZE;
19721          zOut = buf;
19722        }else{
19723          nOut = precision + 10;
19724          zOut = zExtra = sqlite3Malloc( nOut );
19725          if( zOut==0 ){
19726            pAccum->mallocFailed = 1;
19727            return;
19728          }
19729        }
19730        bufpt = &zOut[nOut-1];
19731        if( xtype==etORDINAL ){
19732          static const char zOrd[] = "thstndrd";
19733          int x = (int)(longvalue % 10);
19734          if( x>=4 || (longvalue/10)%10==1 ){
19735            x = 0;
19736          }
19737          *(--bufpt) = zOrd[x*2+1];
19738          *(--bufpt) = zOrd[x*2];
19739        }
19740        {
19741          register const char *cset;      /* Use registers for speed */
19742          register int base;
19743          cset = &aDigits[infop->charset];
19744          base = infop->base;
19745          do{                                           /* Convert to ascii */
19746            *(--bufpt) = cset[longvalue%base];
19747            longvalue = longvalue/base;
19748          }while( longvalue>0 );
19749        }
19750        length = (int)(&zOut[nOut-1]-bufpt);
19751        for(idx=precision-length; idx>0; idx--){
19752          *(--bufpt) = '0';                             /* Zero pad */
19753        }
19754        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
19755        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
19756          const char *pre;
19757          char x;
19758          pre = &aPrefix[infop->prefix];
19759          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19760        }
19761        length = (int)(&zOut[nOut-1]-bufpt);
19762        break;
19763      case etFLOAT:
19764      case etEXP:
19765      case etGENERIC:
19766        realvalue = va_arg(ap,double);
19767#ifdef SQLITE_OMIT_FLOATING_POINT
19768        length = 0;
19769#else
19770        if( precision<0 ) precision = 6;         /* Set default precision */
19771        if( realvalue<0.0 ){
19772          realvalue = -realvalue;
19773          prefix = '-';
19774        }else{
19775          if( flag_plussign )          prefix = '+';
19776          else if( flag_blanksign )    prefix = ' ';
19777          else                         prefix = 0;
19778        }
19779        if( xtype==etGENERIC && precision>0 ) precision--;
19780#if 0
19781        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
19782        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19783#else
19784        /* It makes more sense to use 0.5 */
19785        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19786#endif
19787        if( xtype==etFLOAT ) realvalue += rounder;
19788        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19789        exp = 0;
19790        if( sqlite3IsNaN((double)realvalue) ){
19791          bufpt = "NaN";
19792          length = 3;
19793          break;
19794        }
19795        if( realvalue>0.0 ){
19796          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
19797          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
19798          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
19799          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19800          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19801          if( exp>350 ){
19802            if( prefix=='-' ){
19803              bufpt = "-Inf";
19804            }else if( prefix=='+' ){
19805              bufpt = "+Inf";
19806            }else{
19807              bufpt = "Inf";
19808            }
19809            length = sqlite3Strlen30(bufpt);
19810            break;
19811          }
19812        }
19813        bufpt = buf;
19814        /*
19815        ** If the field type is etGENERIC, then convert to either etEXP
19816        ** or etFLOAT, as appropriate.
19817        */
19818        if( xtype!=etFLOAT ){
19819          realvalue += rounder;
19820          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19821        }
19822        if( xtype==etGENERIC ){
19823          flag_rtz = !flag_alternateform;
19824          if( exp<-4 || exp>precision ){
19825            xtype = etEXP;
19826          }else{
19827            precision = precision - exp;
19828            xtype = etFLOAT;
19829          }
19830        }else{
19831          flag_rtz = 0;
19832        }
19833        if( xtype==etEXP ){
19834          e2 = 0;
19835        }else{
19836          e2 = exp;
19837        }
19838        if( e2+precision+width > etBUFSIZE - 15 ){
19839          bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
19840          if( bufpt==0 ){
19841            pAccum->mallocFailed = 1;
19842            return;
19843          }
19844        }
19845        zOut = bufpt;
19846        nsd = 0;
19847        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19848        /* The sign in front of the number */
19849        if( prefix ){
19850          *(bufpt++) = prefix;
19851        }
19852        /* Digits prior to the decimal point */
19853        if( e2<0 ){
19854          *(bufpt++) = '0';
19855        }else{
19856          for(; e2>=0; e2--){
19857            *(bufpt++) = et_getdigit(&realvalue,&nsd);
19858          }
19859        }
19860        /* The decimal point */
19861        if( flag_dp ){
19862          *(bufpt++) = '.';
19863        }
19864        /* "0" digits after the decimal point but before the first
19865        ** significant digit of the number */
19866        for(e2++; e2<0; precision--, e2++){
19867          assert( precision>0 );
19868          *(bufpt++) = '0';
19869        }
19870        /* Significant digits after the decimal point */
19871        while( (precision--)>0 ){
19872          *(bufpt++) = et_getdigit(&realvalue,&nsd);
19873        }
19874        /* Remove trailing zeros and the "." if no digits follow the "." */
19875        if( flag_rtz && flag_dp ){
19876          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19877          assert( bufpt>zOut );
19878          if( bufpt[-1]=='.' ){
19879            if( flag_altform2 ){
19880              *(bufpt++) = '0';
19881            }else{
19882              *(--bufpt) = 0;
19883            }
19884          }
19885        }
19886        /* Add the "eNNN" suffix */
19887        if( xtype==etEXP ){
19888          *(bufpt++) = aDigits[infop->charset];
19889          if( exp<0 ){
19890            *(bufpt++) = '-'; exp = -exp;
19891          }else{
19892            *(bufpt++) = '+';
19893          }
19894          if( exp>=100 ){
19895            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
19896            exp %= 100;
19897          }
19898          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
19899          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
19900        }
19901        *bufpt = 0;
19902
19903        /* The converted number is in buf[] and zero terminated. Output it.
19904        ** Note that the number is in the usual order, not reversed as with
19905        ** integer conversions. */
19906        length = (int)(bufpt-zOut);
19907        bufpt = zOut;
19908
19909        /* Special case:  Add leading zeros if the flag_zeropad flag is
19910        ** set and we are not left justified */
19911        if( flag_zeropad && !flag_leftjustify && length < width){
19912          int i;
19913          int nPad = width - length;
19914          for(i=width; i>=nPad; i--){
19915            bufpt[i] = bufpt[i-nPad];
19916          }
19917          i = prefix!=0;
19918          while( nPad-- ) bufpt[i++] = '0';
19919          length = width;
19920        }
19921#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19922        break;
19923      case etSIZE:
19924        *(va_arg(ap,int*)) = pAccum->nChar;
19925        length = width = 0;
19926        break;
19927      case etPERCENT:
19928        buf[0] = '%';
19929        bufpt = buf;
19930        length = 1;
19931        break;
19932      case etCHARX:
19933        c = va_arg(ap,int);
19934        buf[0] = (char)c;
19935        if( precision>=0 ){
19936          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19937          length = precision;
19938        }else{
19939          length =1;
19940        }
19941        bufpt = buf;
19942        break;
19943      case etSTRING:
19944      case etDYNSTRING:
19945        bufpt = va_arg(ap,char*);
19946        if( bufpt==0 ){
19947          bufpt = "";
19948        }else if( xtype==etDYNSTRING ){
19949          zExtra = bufpt;
19950        }
19951        if( precision>=0 ){
19952          for(length=0; length<precision && bufpt[length]; length++){}
19953        }else{
19954          length = sqlite3Strlen30(bufpt);
19955        }
19956        break;
19957      case etSQLESCAPE:
19958      case etSQLESCAPE2:
19959      case etSQLESCAPE3: {
19960        int i, j, k, n, isnull;
19961        int needQuote;
19962        char ch;
19963        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
19964        char *escarg = va_arg(ap,char*);
19965        isnull = escarg==0;
19966        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19967        k = precision;
19968        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19969          if( ch==q )  n++;
19970        }
19971        needQuote = !isnull && xtype==etSQLESCAPE2;
19972        n += i + 1 + needQuote*2;
19973        if( n>etBUFSIZE ){
19974          bufpt = zExtra = sqlite3Malloc( n );
19975          if( bufpt==0 ){
19976            pAccum->mallocFailed = 1;
19977            return;
19978          }
19979        }else{
19980          bufpt = buf;
19981        }
19982        j = 0;
19983        if( needQuote ) bufpt[j++] = q;
19984        k = i;
19985        for(i=0; i<k; i++){
19986          bufpt[j++] = ch = escarg[i];
19987          if( ch==q ) bufpt[j++] = ch;
19988        }
19989        if( needQuote ) bufpt[j++] = q;
19990        bufpt[j] = 0;
19991        length = j;
19992        /* The precision in %q and %Q means how many input characters to
19993        ** consume, not the length of the output...
19994        ** if( precision>=0 && precision<length ) length = precision; */
19995        break;
19996      }
19997      case etTOKEN: {
19998        Token *pToken = va_arg(ap, Token*);
19999        if( pToken ){
20000          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
20001        }
20002        length = width = 0;
20003        break;
20004      }
20005      case etSRCLIST: {
20006        SrcList *pSrc = va_arg(ap, SrcList*);
20007        int k = va_arg(ap, int);
20008        struct SrcList_item *pItem = &pSrc->a[k];
20009        assert( k>=0 && k<pSrc->nSrc );
20010        if( pItem->zDatabase ){
20011          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
20012          sqlite3StrAccumAppend(pAccum, ".", 1);
20013        }
20014        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
20015        length = width = 0;
20016        break;
20017      }
20018      default: {
20019        assert( xtype==etINVALID );
20020        return;
20021      }
20022    }/* End switch over the format type */
20023    /*
20024    ** The text of the conversion is pointed to by "bufpt" and is
20025    ** "length" characters long.  The field width is "width".  Do
20026    ** the output.
20027    */
20028    if( !flag_leftjustify ){
20029      register int nspace;
20030      nspace = width-length;
20031      if( nspace>0 ){
20032        sqlite3AppendSpace(pAccum, nspace);
20033      }
20034    }
20035    if( length>0 ){
20036      sqlite3StrAccumAppend(pAccum, bufpt, length);
20037    }
20038    if( flag_leftjustify ){
20039      register int nspace;
20040      nspace = width-length;
20041      if( nspace>0 ){
20042        sqlite3AppendSpace(pAccum, nspace);
20043      }
20044    }
20045    sqlite3_free(zExtra);
20046  }/* End for loop over the format string */
20047} /* End of function */
20048
20049/*
20050** Append N bytes of text from z to the StrAccum object.
20051*/
20052SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
20053  assert( z!=0 || N==0 );
20054  if( p->tooBig | p->mallocFailed ){
20055    testcase(p->tooBig);
20056    testcase(p->mallocFailed);
20057    return;
20058  }
20059  assert( p->zText!=0 || p->nChar==0 );
20060  if( N<0 ){
20061    N = sqlite3Strlen30(z);
20062  }
20063  if( N==0 || NEVER(z==0) ){
20064    return;
20065  }
20066  if( p->nChar+N >= p->nAlloc ){
20067    char *zNew;
20068    if( !p->useMalloc ){
20069      p->tooBig = 1;
20070      N = p->nAlloc - p->nChar - 1;
20071      if( N<=0 ){
20072        return;
20073      }
20074    }else{
20075      char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20076      i64 szNew = p->nChar;
20077      szNew += N + 1;
20078      if( szNew > p->mxAlloc ){
20079        sqlite3StrAccumReset(p);
20080        p->tooBig = 1;
20081        return;
20082      }else{
20083        p->nAlloc = (int)szNew;
20084      }
20085      if( p->useMalloc==1 ){
20086        zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20087      }else{
20088        zNew = sqlite3_realloc(zOld, p->nAlloc);
20089      }
20090      if( zNew ){
20091        if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
20092        p->zText = zNew;
20093      }else{
20094        p->mallocFailed = 1;
20095        sqlite3StrAccumReset(p);
20096        return;
20097      }
20098    }
20099  }
20100  assert( p->zText );
20101  memcpy(&p->zText[p->nChar], z, N);
20102  p->nChar += N;
20103}
20104
20105/*
20106** Finish off a string by making sure it is zero-terminated.
20107** Return a pointer to the resulting string.  Return a NULL
20108** pointer if any kind of error was encountered.
20109*/
20110SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
20111  if( p->zText ){
20112    p->zText[p->nChar] = 0;
20113    if( p->useMalloc && p->zText==p->zBase ){
20114      if( p->useMalloc==1 ){
20115        p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
20116      }else{
20117        p->zText = sqlite3_malloc(p->nChar+1);
20118      }
20119      if( p->zText ){
20120        memcpy(p->zText, p->zBase, p->nChar+1);
20121      }else{
20122        p->mallocFailed = 1;
20123      }
20124    }
20125  }
20126  return p->zText;
20127}
20128
20129/*
20130** Reset an StrAccum string.  Reclaim all malloced memory.
20131*/
20132SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20133  if( p->zText!=p->zBase ){
20134    if( p->useMalloc==1 ){
20135      sqlite3DbFree(p->db, p->zText);
20136    }else{
20137      sqlite3_free(p->zText);
20138    }
20139  }
20140  p->zText = 0;
20141}
20142
20143/*
20144** Initialize a string accumulator
20145*/
20146SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20147  p->zText = p->zBase = zBase;
20148  p->db = 0;
20149  p->nChar = 0;
20150  p->nAlloc = n;
20151  p->mxAlloc = mx;
20152  p->useMalloc = 1;
20153  p->tooBig = 0;
20154  p->mallocFailed = 0;
20155}
20156
20157/*
20158** Print into memory obtained from sqliteMalloc().  Use the internal
20159** %-conversion extensions.
20160*/
20161SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20162  char *z;
20163  char zBase[SQLITE_PRINT_BUF_SIZE];
20164  StrAccum acc;
20165  assert( db!=0 );
20166  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20167                      db->aLimit[SQLITE_LIMIT_LENGTH]);
20168  acc.db = db;
20169  sqlite3VXPrintf(&acc, 1, zFormat, ap);
20170  z = sqlite3StrAccumFinish(&acc);
20171  if( acc.mallocFailed ){
20172    db->mallocFailed = 1;
20173  }
20174  return z;
20175}
20176
20177/*
20178** Print into memory obtained from sqliteMalloc().  Use the internal
20179** %-conversion extensions.
20180*/
20181SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20182  va_list ap;
20183  char *z;
20184  va_start(ap, zFormat);
20185  z = sqlite3VMPrintf(db, zFormat, ap);
20186  va_end(ap);
20187  return z;
20188}
20189
20190/*
20191** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20192** the string and before returnning.  This routine is intended to be used
20193** to modify an existing string.  For example:
20194**
20195**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20196**
20197*/
20198SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20199  va_list ap;
20200  char *z;
20201  va_start(ap, zFormat);
20202  z = sqlite3VMPrintf(db, zFormat, ap);
20203  va_end(ap);
20204  sqlite3DbFree(db, zStr);
20205  return z;
20206}
20207
20208/*
20209** Print into memory obtained from sqlite3_malloc().  Omit the internal
20210** %-conversion extensions.
20211*/
20212SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20213  char *z;
20214  char zBase[SQLITE_PRINT_BUF_SIZE];
20215  StrAccum acc;
20216#ifndef SQLITE_OMIT_AUTOINIT
20217  if( sqlite3_initialize() ) return 0;
20218#endif
20219  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20220  acc.useMalloc = 2;
20221  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20222  z = sqlite3StrAccumFinish(&acc);
20223  return z;
20224}
20225
20226/*
20227** Print into memory obtained from sqlite3_malloc()().  Omit the internal
20228** %-conversion extensions.
20229*/
20230SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20231  va_list ap;
20232  char *z;
20233#ifndef SQLITE_OMIT_AUTOINIT
20234  if( sqlite3_initialize() ) return 0;
20235#endif
20236  va_start(ap, zFormat);
20237  z = sqlite3_vmprintf(zFormat, ap);
20238  va_end(ap);
20239  return z;
20240}
20241
20242/*
20243** sqlite3_snprintf() works like snprintf() except that it ignores the
20244** current locale settings.  This is important for SQLite because we
20245** are not able to use a "," as the decimal point in place of "." as
20246** specified by some locales.
20247**
20248** Oops:  The first two arguments of sqlite3_snprintf() are backwards
20249** from the snprintf() standard.  Unfortunately, it is too late to change
20250** this without breaking compatibility, so we just have to live with the
20251** mistake.
20252**
20253** sqlite3_vsnprintf() is the varargs version.
20254*/
20255SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20256  StrAccum acc;
20257  if( n<=0 ) return zBuf;
20258  sqlite3StrAccumInit(&acc, zBuf, n, 0);
20259  acc.useMalloc = 0;
20260  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20261  return sqlite3StrAccumFinish(&acc);
20262}
20263SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20264  char *z;
20265  va_list ap;
20266  va_start(ap,zFormat);
20267  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20268  va_end(ap);
20269  return z;
20270}
20271
20272/*
20273** This is the routine that actually formats the sqlite3_log() message.
20274** We house it in a separate routine from sqlite3_log() to avoid using
20275** stack space on small-stack systems when logging is disabled.
20276**
20277** sqlite3_log() must render into a static buffer.  It cannot dynamically
20278** allocate memory because it might be called while the memory allocator
20279** mutex is held.
20280*/
20281static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20282  StrAccum acc;                          /* String accumulator */
20283  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
20284
20285  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20286  acc.useMalloc = 0;
20287  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20288  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20289                           sqlite3StrAccumFinish(&acc));
20290}
20291
20292/*
20293** Format and write a message to the log if logging is enabled.
20294*/
20295SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20296  va_list ap;                             /* Vararg list */
20297  if( sqlite3GlobalConfig.xLog ){
20298    va_start(ap, zFormat);
20299    renderLogMsg(iErrCode, zFormat, ap);
20300    va_end(ap);
20301  }
20302}
20303
20304#if defined(SQLITE_DEBUG)
20305/*
20306** A version of printf() that understands %lld.  Used for debugging.
20307** The printf() built into some versions of windows does not understand %lld
20308** and segfaults if you give it a long long int.
20309*/
20310SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20311  va_list ap;
20312  StrAccum acc;
20313  char zBuf[500];
20314  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20315  acc.useMalloc = 0;
20316  va_start(ap,zFormat);
20317  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20318  va_end(ap);
20319  sqlite3StrAccumFinish(&acc);
20320  fprintf(stdout,"%s", zBuf);
20321  fflush(stdout);
20322}
20323#endif
20324
20325#ifndef SQLITE_OMIT_TRACE
20326/*
20327** variable-argument wrapper around sqlite3VXPrintf().
20328*/
20329SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
20330  va_list ap;
20331  va_start(ap,zFormat);
20332  sqlite3VXPrintf(p, 1, zFormat, ap);
20333  va_end(ap);
20334}
20335#endif
20336
20337/************** End of printf.c **********************************************/
20338/************** Begin file random.c ******************************************/
20339/*
20340** 2001 September 15
20341**
20342** The author disclaims copyright to this source code.  In place of
20343** a legal notice, here is a blessing:
20344**
20345**    May you do good and not evil.
20346**    May you find forgiveness for yourself and forgive others.
20347**    May you share freely, never taking more than you give.
20348**
20349*************************************************************************
20350** This file contains code to implement a pseudo-random number
20351** generator (PRNG) for SQLite.
20352**
20353** Random numbers are used by some of the database backends in order
20354** to generate random integer keys for tables or random filenames.
20355*/
20356
20357
20358/* All threads share a single random number generator.
20359** This structure is the current state of the generator.
20360*/
20361static SQLITE_WSD struct sqlite3PrngType {
20362  unsigned char isInit;          /* True if initialized */
20363  unsigned char i, j;            /* State variables */
20364  unsigned char s[256];          /* State variables */
20365} sqlite3Prng;
20366
20367/*
20368** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
20369** must be held while executing this routine.
20370**
20371** Why not just use a library random generator like lrand48() for this?
20372** Because the OP_NewRowid opcode in the VDBE depends on having a very
20373** good source of random numbers.  The lrand48() library function may
20374** well be good enough.  But maybe not.  Or maybe lrand48() has some
20375** subtle problems on some systems that could cause problems.  It is hard
20376** to know.  To minimize the risk of problems due to bad lrand48()
20377** implementations, SQLite uses this random number generator based
20378** on RC4, which we know works very well.
20379**
20380** (Later):  Actually, OP_NewRowid does not depend on a good source of
20381** randomness any more.  But we will leave this code in all the same.
20382*/
20383static u8 randomByte(void){
20384  unsigned char t;
20385
20386
20387  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
20388  ** state vector.  If writable static data is unsupported on the target,
20389  ** we have to locate the state vector at run-time.  In the more common
20390  ** case where writable static data is supported, wsdPrng can refer directly
20391  ** to the "sqlite3Prng" state vector declared above.
20392  */
20393#ifdef SQLITE_OMIT_WSD
20394  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
20395# define wsdPrng p[0]
20396#else
20397# define wsdPrng sqlite3Prng
20398#endif
20399
20400
20401  /* Initialize the state of the random number generator once,
20402  ** the first time this routine is called.  The seed value does
20403  ** not need to contain a lot of randomness since we are not
20404  ** trying to do secure encryption or anything like that...
20405  **
20406  ** Nothing in this file or anywhere else in SQLite does any kind of
20407  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
20408  ** number generator) not as an encryption device.
20409  */
20410  if( !wsdPrng.isInit ){
20411    int i;
20412    char k[256];
20413    wsdPrng.j = 0;
20414    wsdPrng.i = 0;
20415    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20416    for(i=0; i<256; i++){
20417      wsdPrng.s[i] = (u8)i;
20418    }
20419    for(i=0; i<256; i++){
20420      wsdPrng.j += wsdPrng.s[i] + k[i];
20421      t = wsdPrng.s[wsdPrng.j];
20422      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20423      wsdPrng.s[i] = t;
20424    }
20425    wsdPrng.isInit = 1;
20426  }
20427
20428  /* Generate and return single random byte
20429  */
20430  wsdPrng.i++;
20431  t = wsdPrng.s[wsdPrng.i];
20432  wsdPrng.j += t;
20433  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20434  wsdPrng.s[wsdPrng.j] = t;
20435  t += wsdPrng.s[wsdPrng.i];
20436  return wsdPrng.s[t];
20437}
20438
20439/*
20440** Return N random bytes.
20441*/
20442SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20443  unsigned char *zBuf = pBuf;
20444#if SQLITE_THREADSAFE
20445  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20446#endif
20447  sqlite3_mutex_enter(mutex);
20448  while( N-- ){
20449    *(zBuf++) = randomByte();
20450  }
20451  sqlite3_mutex_leave(mutex);
20452}
20453
20454#ifndef SQLITE_OMIT_BUILTIN_TEST
20455/*
20456** For testing purposes, we sometimes want to preserve the state of
20457** PRNG and restore the PRNG to its saved state at a later time, or
20458** to reset the PRNG to its initial state.  These routines accomplish
20459** those tasks.
20460**
20461** The sqlite3_test_control() interface calls these routines to
20462** control the PRNG.
20463*/
20464static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20465SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20466  memcpy(
20467    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20468    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20469    sizeof(sqlite3Prng)
20470  );
20471}
20472SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20473  memcpy(
20474    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20475    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20476    sizeof(sqlite3Prng)
20477  );
20478}
20479SQLITE_PRIVATE void sqlite3PrngResetState(void){
20480  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20481}
20482#endif /* SQLITE_OMIT_BUILTIN_TEST */
20483
20484/************** End of random.c **********************************************/
20485/************** Begin file utf.c *********************************************/
20486/*
20487** 2004 April 13
20488**
20489** The author disclaims copyright to this source code.  In place of
20490** a legal notice, here is a blessing:
20491**
20492**    May you do good and not evil.
20493**    May you find forgiveness for yourself and forgive others.
20494**    May you share freely, never taking more than you give.
20495**
20496*************************************************************************
20497** This file contains routines used to translate between UTF-8,
20498** UTF-16, UTF-16BE, and UTF-16LE.
20499**
20500** Notes on UTF-8:
20501**
20502**   Byte-0    Byte-1    Byte-2    Byte-3    Value
20503**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
20504**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
20505**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
20506**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
20507**
20508**
20509** Notes on UTF-16:  (with wwww+1==uuuuu)
20510**
20511**      Word-0               Word-1          Value
20512**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
20513**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
20514**
20515**
20516** BOM or Byte Order Mark:
20517**     0xff 0xfe   little-endian utf-16 follows
20518**     0xfe 0xff   big-endian utf-16 follows
20519**
20520*/
20521/* #include <assert.h> */
20522
20523#ifndef SQLITE_AMALGAMATION
20524/*
20525** The following constant value is used by the SQLITE_BIGENDIAN and
20526** SQLITE_LITTLEENDIAN macros.
20527*/
20528SQLITE_PRIVATE const int sqlite3one = 1;
20529#endif /* SQLITE_AMALGAMATION */
20530
20531/*
20532** This lookup table is used to help decode the first byte of
20533** a multi-byte UTF8 character.
20534*/
20535static const unsigned char sqlite3Utf8Trans1[] = {
20536  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20537  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20538  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20539  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20540  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20541  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20542  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20543  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20544};
20545
20546
20547#define WRITE_UTF8(zOut, c) {                          \
20548  if( c<0x00080 ){                                     \
20549    *zOut++ = (u8)(c&0xFF);                            \
20550  }                                                    \
20551  else if( c<0x00800 ){                                \
20552    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20553    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20554  }                                                    \
20555  else if( c<0x10000 ){                                \
20556    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20557    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20558    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20559  }else{                                               \
20560    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20561    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20562    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20563    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20564  }                                                    \
20565}
20566
20567#define WRITE_UTF16LE(zOut, c) {                                    \
20568  if( c<=0xFFFF ){                                                  \
20569    *zOut++ = (u8)(c&0x00FF);                                       \
20570    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20571  }else{                                                            \
20572    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20573    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20574    *zOut++ = (u8)(c&0x00FF);                                       \
20575    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20576  }                                                                 \
20577}
20578
20579#define WRITE_UTF16BE(zOut, c) {                                    \
20580  if( c<=0xFFFF ){                                                  \
20581    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20582    *zOut++ = (u8)(c&0x00FF);                                       \
20583  }else{                                                            \
20584    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20585    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20586    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20587    *zOut++ = (u8)(c&0x00FF);                                       \
20588  }                                                                 \
20589}
20590
20591#define READ_UTF16LE(zIn, TERM, c){                                   \
20592  c = (*zIn++);                                                       \
20593  c += ((*zIn++)<<8);                                                 \
20594  if( c>=0xD800 && c<0xE000 && TERM ){                                \
20595    int c2 = (*zIn++);                                                \
20596    c2 += ((*zIn++)<<8);                                              \
20597    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20598  }                                                                   \
20599}
20600
20601#define READ_UTF16BE(zIn, TERM, c){                                   \
20602  c = ((*zIn++)<<8);                                                  \
20603  c += (*zIn++);                                                      \
20604  if( c>=0xD800 && c<0xE000 && TERM ){                                \
20605    int c2 = ((*zIn++)<<8);                                           \
20606    c2 += (*zIn++);                                                   \
20607    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20608  }                                                                   \
20609}
20610
20611/*
20612** Translate a single UTF-8 character.  Return the unicode value.
20613**
20614** During translation, assume that the byte that zTerm points
20615** is a 0x00.
20616**
20617** Write a pointer to the next unread byte back into *pzNext.
20618**
20619** Notes On Invalid UTF-8:
20620**
20621**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20622**     be encoded as a multi-byte character.  Any multi-byte character that
20623**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20624**
20625**  *  This routine never allows a UTF16 surrogate value to be encoded.
20626**     If a multi-byte character attempts to encode a value between
20627**     0xd800 and 0xe000 then it is rendered as 0xfffd.
20628**
20629**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20630**     byte of a character are interpreted as single-byte characters
20631**     and rendered as themselves even though they are technically
20632**     invalid characters.
20633**
20634**  *  This routine accepts an infinite number of different UTF8 encodings
20635**     for unicode values 0x80 and greater.  It do not change over-length
20636**     encodings to 0xfffd as some systems recommend.
20637*/
20638#define READ_UTF8(zIn, zTerm, c)                           \
20639  c = *(zIn++);                                            \
20640  if( c>=0xc0 ){                                           \
20641    c = sqlite3Utf8Trans1[c-0xc0];                         \
20642    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20643      c = (c<<6) + (0x3f & *(zIn++));                      \
20644    }                                                      \
20645    if( c<0x80                                             \
20646        || (c&0xFFFFF800)==0xD800                          \
20647        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20648  }
20649SQLITE_PRIVATE u32 sqlite3Utf8Read(
20650  const unsigned char *zIn,       /* First byte of UTF-8 character */
20651  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
20652){
20653  unsigned int c;
20654
20655  /* Same as READ_UTF8() above but without the zTerm parameter.
20656  ** For this routine, we assume the UTF8 string is always zero-terminated.
20657  */
20658  c = *(zIn++);
20659  if( c>=0xc0 ){
20660    c = sqlite3Utf8Trans1[c-0xc0];
20661    while( (*zIn & 0xc0)==0x80 ){
20662      c = (c<<6) + (0x3f & *(zIn++));
20663    }
20664    if( c<0x80
20665        || (c&0xFFFFF800)==0xD800
20666        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
20667  }
20668  *pzNext = zIn;
20669  return c;
20670}
20671
20672
20673
20674
20675/*
20676** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20677** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20678*/
20679/* #define TRANSLATE_TRACE 1 */
20680
20681#ifndef SQLITE_OMIT_UTF16
20682/*
20683** This routine transforms the internal text encoding used by pMem to
20684** desiredEnc. It is an error if the string is already of the desired
20685** encoding, or if *pMem does not contain a string value.
20686*/
20687SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20688  int len;                    /* Maximum length of output string in bytes */
20689  unsigned char *zOut;                  /* Output buffer */
20690  unsigned char *zIn;                   /* Input iterator */
20691  unsigned char *zTerm;                 /* End of input */
20692  unsigned char *z;                     /* Output iterator */
20693  unsigned int c;
20694
20695  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20696  assert( pMem->flags&MEM_Str );
20697  assert( pMem->enc!=desiredEnc );
20698  assert( pMem->enc!=0 );
20699  assert( pMem->n>=0 );
20700
20701#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20702  {
20703    char zBuf[100];
20704    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20705    fprintf(stderr, "INPUT:  %s\n", zBuf);
20706  }
20707#endif
20708
20709  /* If the translation is between UTF-16 little and big endian, then
20710  ** all that is required is to swap the byte order. This case is handled
20711  ** differently from the others.
20712  */
20713  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20714    u8 temp;
20715    int rc;
20716    rc = sqlite3VdbeMemMakeWriteable(pMem);
20717    if( rc!=SQLITE_OK ){
20718      assert( rc==SQLITE_NOMEM );
20719      return SQLITE_NOMEM;
20720    }
20721    zIn = (u8*)pMem->z;
20722    zTerm = &zIn[pMem->n&~1];
20723    while( zIn<zTerm ){
20724      temp = *zIn;
20725      *zIn = *(zIn+1);
20726      zIn++;
20727      *zIn++ = temp;
20728    }
20729    pMem->enc = desiredEnc;
20730    goto translate_out;
20731  }
20732
20733  /* Set len to the maximum number of bytes required in the output buffer. */
20734  if( desiredEnc==SQLITE_UTF8 ){
20735    /* When converting from UTF-16, the maximum growth results from
20736    ** translating a 2-byte character to a 4-byte UTF-8 character.
20737    ** A single byte is required for the output string
20738    ** nul-terminator.
20739    */
20740    pMem->n &= ~1;
20741    len = pMem->n * 2 + 1;
20742  }else{
20743    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20744    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20745    ** character. Two bytes are required in the output buffer for the
20746    ** nul-terminator.
20747    */
20748    len = pMem->n * 2 + 2;
20749  }
20750
20751  /* Set zIn to point at the start of the input buffer and zTerm to point 1
20752  ** byte past the end.
20753  **
20754  ** Variable zOut is set to point at the output buffer, space obtained
20755  ** from sqlite3_malloc().
20756  */
20757  zIn = (u8*)pMem->z;
20758  zTerm = &zIn[pMem->n];
20759  zOut = sqlite3DbMallocRaw(pMem->db, len);
20760  if( !zOut ){
20761    return SQLITE_NOMEM;
20762  }
20763  z = zOut;
20764
20765  if( pMem->enc==SQLITE_UTF8 ){
20766    if( desiredEnc==SQLITE_UTF16LE ){
20767      /* UTF-8 -> UTF-16 Little-endian */
20768      while( zIn<zTerm ){
20769        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20770        READ_UTF8(zIn, zTerm, c);
20771        WRITE_UTF16LE(z, c);
20772      }
20773    }else{
20774      assert( desiredEnc==SQLITE_UTF16BE );
20775      /* UTF-8 -> UTF-16 Big-endian */
20776      while( zIn<zTerm ){
20777        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20778        READ_UTF8(zIn, zTerm, c);
20779        WRITE_UTF16BE(z, c);
20780      }
20781    }
20782    pMem->n = (int)(z - zOut);
20783    *z++ = 0;
20784  }else{
20785    assert( desiredEnc==SQLITE_UTF8 );
20786    if( pMem->enc==SQLITE_UTF16LE ){
20787      /* UTF-16 Little-endian -> UTF-8 */
20788      while( zIn<zTerm ){
20789        READ_UTF16LE(zIn, zIn<zTerm, c);
20790        WRITE_UTF8(z, c);
20791      }
20792    }else{
20793      /* UTF-16 Big-endian -> UTF-8 */
20794      while( zIn<zTerm ){
20795        READ_UTF16BE(zIn, zIn<zTerm, c);
20796        WRITE_UTF8(z, c);
20797      }
20798    }
20799    pMem->n = (int)(z - zOut);
20800  }
20801  *z = 0;
20802  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20803
20804  sqlite3VdbeMemRelease(pMem);
20805  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20806  pMem->enc = desiredEnc;
20807  pMem->flags |= (MEM_Term|MEM_Dyn);
20808  pMem->z = (char*)zOut;
20809  pMem->zMalloc = pMem->z;
20810
20811translate_out:
20812#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20813  {
20814    char zBuf[100];
20815    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20816    fprintf(stderr, "OUTPUT: %s\n", zBuf);
20817  }
20818#endif
20819  return SQLITE_OK;
20820}
20821
20822/*
20823** This routine checks for a byte-order mark at the beginning of the
20824** UTF-16 string stored in *pMem. If one is present, it is removed and
20825** the encoding of the Mem adjusted. This routine does not do any
20826** byte-swapping, it just sets Mem.enc appropriately.
20827**
20828** The allocation (static, dynamic etc.) and encoding of the Mem may be
20829** changed by this function.
20830*/
20831SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20832  int rc = SQLITE_OK;
20833  u8 bom = 0;
20834
20835  assert( pMem->n>=0 );
20836  if( pMem->n>1 ){
20837    u8 b1 = *(u8 *)pMem->z;
20838    u8 b2 = *(((u8 *)pMem->z) + 1);
20839    if( b1==0xFE && b2==0xFF ){
20840      bom = SQLITE_UTF16BE;
20841    }
20842    if( b1==0xFF && b2==0xFE ){
20843      bom = SQLITE_UTF16LE;
20844    }
20845  }
20846
20847  if( bom ){
20848    rc = sqlite3VdbeMemMakeWriteable(pMem);
20849    if( rc==SQLITE_OK ){
20850      pMem->n -= 2;
20851      memmove(pMem->z, &pMem->z[2], pMem->n);
20852      pMem->z[pMem->n] = '\0';
20853      pMem->z[pMem->n+1] = '\0';
20854      pMem->flags |= MEM_Term;
20855      pMem->enc = bom;
20856    }
20857  }
20858  return rc;
20859}
20860#endif /* SQLITE_OMIT_UTF16 */
20861
20862/*
20863** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20864** return the number of unicode characters in pZ up to (but not including)
20865** the first 0x00 byte. If nByte is not less than zero, return the
20866** number of unicode characters in the first nByte of pZ (or up to
20867** the first 0x00, whichever comes first).
20868*/
20869SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20870  int r = 0;
20871  const u8 *z = (const u8*)zIn;
20872  const u8 *zTerm;
20873  if( nByte>=0 ){
20874    zTerm = &z[nByte];
20875  }else{
20876    zTerm = (const u8*)(-1);
20877  }
20878  assert( z<=zTerm );
20879  while( *z!=0 && z<zTerm ){
20880    SQLITE_SKIP_UTF8(z);
20881    r++;
20882  }
20883  return r;
20884}
20885
20886/* This test function is not currently used by the automated test-suite.
20887** Hence it is only available in debug builds.
20888*/
20889#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20890/*
20891** Translate UTF-8 to UTF-8.
20892**
20893** This has the effect of making sure that the string is well-formed
20894** UTF-8.  Miscoded characters are removed.
20895**
20896** The translation is done in-place and aborted if the output
20897** overruns the input.
20898*/
20899SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20900  unsigned char *zOut = zIn;
20901  unsigned char *zStart = zIn;
20902  u32 c;
20903
20904  while( zIn[0] && zOut<=zIn ){
20905    c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
20906    if( c!=0xfffd ){
20907      WRITE_UTF8(zOut, c);
20908    }
20909  }
20910  *zOut = 0;
20911  return (int)(zOut - zStart);
20912}
20913#endif
20914
20915#ifndef SQLITE_OMIT_UTF16
20916/*
20917** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20918** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20919** be freed by the calling function.
20920**
20921** NULL is returned if there is an allocation error.
20922*/
20923SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20924  Mem m;
20925  memset(&m, 0, sizeof(m));
20926  m.db = db;
20927  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20928  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20929  if( db->mallocFailed ){
20930    sqlite3VdbeMemRelease(&m);
20931    m.z = 0;
20932  }
20933  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20934  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20935  assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20936  assert( m.z || db->mallocFailed );
20937  return m.z;
20938}
20939
20940/*
20941** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20942** enc. A pointer to the new string is returned, and the value of *pnOut
20943** is set to the length of the returned string in bytes. The call should
20944** arrange to call sqlite3DbFree() on the returned pointer when it is
20945** no longer required.
20946**
20947** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20948** flag set.
20949*/
20950#ifdef SQLITE_ENABLE_STAT3
20951SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20952  Mem m;
20953  memset(&m, 0, sizeof(m));
20954  m.db = db;
20955  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20956  if( sqlite3VdbeMemTranslate(&m, enc) ){
20957    assert( db->mallocFailed );
20958    return 0;
20959  }
20960  assert( m.z==m.zMalloc );
20961  *pnOut = m.n;
20962  return m.z;
20963}
20964#endif
20965
20966/*
20967** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20968** Return the number of bytes in the first nChar unicode characters
20969** in pZ.  nChar must be non-negative.
20970*/
20971SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20972  int c;
20973  unsigned char const *z = zIn;
20974  int n = 0;
20975
20976  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20977    while( n<nChar ){
20978      READ_UTF16BE(z, 1, c);
20979      n++;
20980    }
20981  }else{
20982    while( n<nChar ){
20983      READ_UTF16LE(z, 1, c);
20984      n++;
20985    }
20986  }
20987  return (int)(z-(unsigned char const *)zIn);
20988}
20989
20990#if defined(SQLITE_TEST)
20991/*
20992** This routine is called from the TCL test function "translate_selftest".
20993** It checks that the primitives for serializing and deserializing
20994** characters in each encoding are inverses of each other.
20995*/
20996SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20997  unsigned int i, t;
20998  unsigned char zBuf[20];
20999  unsigned char *z;
21000  int n;
21001  unsigned int c;
21002
21003  for(i=0; i<0x00110000; i++){
21004    z = zBuf;
21005    WRITE_UTF8(z, i);
21006    n = (int)(z-zBuf);
21007    assert( n>0 && n<=4 );
21008    z[0] = 0;
21009    z = zBuf;
21010    c = sqlite3Utf8Read(z, (const u8**)&z);
21011    t = i;
21012    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21013    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21014    assert( c==t );
21015    assert( (z-zBuf)==n );
21016  }
21017  for(i=0; i<0x00110000; i++){
21018    if( i>=0xD800 && i<0xE000 ) continue;
21019    z = zBuf;
21020    WRITE_UTF16LE(z, i);
21021    n = (int)(z-zBuf);
21022    assert( n>0 && n<=4 );
21023    z[0] = 0;
21024    z = zBuf;
21025    READ_UTF16LE(z, 1, c);
21026    assert( c==i );
21027    assert( (z-zBuf)==n );
21028  }
21029  for(i=0; i<0x00110000; i++){
21030    if( i>=0xD800 && i<0xE000 ) continue;
21031    z = zBuf;
21032    WRITE_UTF16BE(z, i);
21033    n = (int)(z-zBuf);
21034    assert( n>0 && n<=4 );
21035    z[0] = 0;
21036    z = zBuf;
21037    READ_UTF16BE(z, 1, c);
21038    assert( c==i );
21039    assert( (z-zBuf)==n );
21040  }
21041}
21042#endif /* SQLITE_TEST */
21043#endif /* SQLITE_OMIT_UTF16 */
21044
21045/************** End of utf.c *************************************************/
21046/************** Begin file util.c ********************************************/
21047/*
21048** 2001 September 15
21049**
21050** The author disclaims copyright to this source code.  In place of
21051** a legal notice, here is a blessing:
21052**
21053**    May you do good and not evil.
21054**    May you find forgiveness for yourself and forgive others.
21055**    May you share freely, never taking more than you give.
21056**
21057*************************************************************************
21058** Utility functions used throughout sqlite.
21059**
21060** This file contains functions for allocating memory, comparing
21061** strings, and stuff like that.
21062**
21063*/
21064/* #include <stdarg.h> */
21065#ifdef SQLITE_HAVE_ISNAN
21066# include <math.h>
21067#endif
21068
21069/*
21070** Routine needed to support the testcase() macro.
21071*/
21072#ifdef SQLITE_COVERAGE_TEST
21073SQLITE_PRIVATE void sqlite3Coverage(int x){
21074  static unsigned dummy = 0;
21075  dummy += (unsigned)x;
21076}
21077#endif
21078
21079#ifndef SQLITE_OMIT_FLOATING_POINT
21080/*
21081** Return true if the floating point value is Not a Number (NaN).
21082**
21083** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
21084** Otherwise, we have our own implementation that works on most systems.
21085*/
21086SQLITE_PRIVATE int sqlite3IsNaN(double x){
21087  int rc;   /* The value return */
21088#if !defined(SQLITE_HAVE_ISNAN)
21089  /*
21090  ** Systems that support the isnan() library function should probably
21091  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
21092  ** found that many systems do not have a working isnan() function so
21093  ** this implementation is provided as an alternative.
21094  **
21095  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
21096  ** On the other hand, the use of -ffast-math comes with the following
21097  ** warning:
21098  **
21099  **      This option [-ffast-math] should never be turned on by any
21100  **      -O option since it can result in incorrect output for programs
21101  **      which depend on an exact implementation of IEEE or ISO
21102  **      rules/specifications for math functions.
21103  **
21104  ** Under MSVC, this NaN test may fail if compiled with a floating-
21105  ** point precision mode other than /fp:precise.  From the MSDN
21106  ** documentation:
21107  **
21108  **      The compiler [with /fp:precise] will properly handle comparisons
21109  **      involving NaN. For example, x != x evaluates to true if x is NaN
21110  **      ...
21111  */
21112#ifdef __FAST_MATH__
21113# error SQLite will not work correctly with the -ffast-math option of GCC.
21114#endif
21115  volatile double y = x;
21116  volatile double z = y;
21117  rc = (y!=z);
21118#else  /* if defined(SQLITE_HAVE_ISNAN) */
21119  rc = isnan(x);
21120#endif /* SQLITE_HAVE_ISNAN */
21121  testcase( rc );
21122  return rc;
21123}
21124#endif /* SQLITE_OMIT_FLOATING_POINT */
21125
21126/*
21127** Compute a string length that is limited to what can be stored in
21128** lower 30 bits of a 32-bit signed integer.
21129**
21130** The value returned will never be negative.  Nor will it ever be greater
21131** than the actual length of the string.  For very long strings (greater
21132** than 1GiB) the value returned might be less than the true string length.
21133*/
21134SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21135  const char *z2 = z;
21136  if( z==0 ) return 0;
21137  while( *z2 ){ z2++; }
21138  return 0x3fffffff & (int)(z2 - z);
21139}
21140
21141/*
21142** Set the most recent error code and error string for the sqlite
21143** handle "db". The error code is set to "err_code".
21144**
21145** If it is not NULL, string zFormat specifies the format of the
21146** error string in the style of the printf functions: The following
21147** format characters are allowed:
21148**
21149**      %s      Insert a string
21150**      %z      A string that should be freed after use
21151**      %d      Insert an integer
21152**      %T      Insert a token
21153**      %S      Insert the first element of a SrcList
21154**
21155** zFormat and any string tokens that follow it are assumed to be
21156** encoded in UTF-8.
21157**
21158** To clear the most recent error for sqlite handle "db", sqlite3Error
21159** should be called with err_code set to SQLITE_OK and zFormat set
21160** to NULL.
21161*/
21162SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21163  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21164    db->errCode = err_code;
21165    if( zFormat ){
21166      char *z;
21167      va_list ap;
21168      va_start(ap, zFormat);
21169      z = sqlite3VMPrintf(db, zFormat, ap);
21170      va_end(ap);
21171      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21172    }else{
21173      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
21174    }
21175  }
21176}
21177
21178/*
21179** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21180** The following formatting characters are allowed:
21181**
21182**      %s      Insert a string
21183**      %z      A string that should be freed after use
21184**      %d      Insert an integer
21185**      %T      Insert a token
21186**      %S      Insert the first element of a SrcList
21187**
21188** This function should be used to report any error that occurs whilst
21189** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21190** last thing the sqlite3_prepare() function does is copy the error
21191** stored by this function into the database handle using sqlite3Error().
21192** Function sqlite3Error() should be used during statement execution
21193** (sqlite3_step() etc.).
21194*/
21195SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21196  char *zMsg;
21197  va_list ap;
21198  sqlite3 *db = pParse->db;
21199  va_start(ap, zFormat);
21200  zMsg = sqlite3VMPrintf(db, zFormat, ap);
21201  va_end(ap);
21202  if( db->suppressErr ){
21203    sqlite3DbFree(db, zMsg);
21204  }else{
21205    pParse->nErr++;
21206    sqlite3DbFree(db, pParse->zErrMsg);
21207    pParse->zErrMsg = zMsg;
21208    pParse->rc = SQLITE_ERROR;
21209  }
21210}
21211
21212/*
21213** Convert an SQL-style quoted string into a normal string by removing
21214** the quote characters.  The conversion is done in-place.  If the
21215** input does not begin with a quote character, then this routine
21216** is a no-op.
21217**
21218** The input string must be zero-terminated.  A new zero-terminator
21219** is added to the dequoted string.
21220**
21221** The return value is -1 if no dequoting occurs or the length of the
21222** dequoted string, exclusive of the zero terminator, if dequoting does
21223** occur.
21224**
21225** 2002-Feb-14: This routine is extended to remove MS-Access style
21226** brackets from around identifers.  For example:  "[a-b-c]" becomes
21227** "a-b-c".
21228*/
21229SQLITE_PRIVATE int sqlite3Dequote(char *z){
21230  char quote;
21231  int i, j;
21232  if( z==0 ) return -1;
21233  quote = z[0];
21234  switch( quote ){
21235    case '\'':  break;
21236    case '"':   break;
21237    case '`':   break;                /* For MySQL compatibility */
21238    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
21239    default:    return -1;
21240  }
21241  for(i=1, j=0; ALWAYS(z[i]); i++){
21242    if( z[i]==quote ){
21243      if( z[i+1]==quote ){
21244        z[j++] = quote;
21245        i++;
21246      }else{
21247        break;
21248      }
21249    }else{
21250      z[j++] = z[i];
21251    }
21252  }
21253  z[j] = 0;
21254  return j;
21255}
21256
21257/* Convenient short-hand */
21258#define UpperToLower sqlite3UpperToLower
21259
21260/*
21261** Some systems have stricmp().  Others have strcasecmp().  Because
21262** there is no consistency, we will define our own.
21263**
21264** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21265** sqlite3_strnicmp() APIs allow applications and extensions to compare
21266** the contents of two buffers containing UTF-8 strings in a
21267** case-independent fashion, using the same definition of "case
21268** independence" that SQLite uses internally when comparing identifiers.
21269*/
21270SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21271  register unsigned char *a, *b;
21272  a = (unsigned char *)zLeft;
21273  b = (unsigned char *)zRight;
21274  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21275  return UpperToLower[*a] - UpperToLower[*b];
21276}
21277SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21278  register unsigned char *a, *b;
21279  a = (unsigned char *)zLeft;
21280  b = (unsigned char *)zRight;
21281  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21282  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21283}
21284
21285/*
21286** The string z[] is an text representation of a real number.
21287** Convert this string to a double and write it into *pResult.
21288**
21289** The string z[] is length bytes in length (bytes, not characters) and
21290** uses the encoding enc.  The string is not necessarily zero-terminated.
21291**
21292** Return TRUE if the result is a valid real number (or integer) and FALSE
21293** if the string is empty or contains extraneous text.  Valid numbers
21294** are in one of these formats:
21295**
21296**    [+-]digits[E[+-]digits]
21297**    [+-]digits.[digits][E[+-]digits]
21298**    [+-].digits[E[+-]digits]
21299**
21300** Leading and trailing whitespace is ignored for the purpose of determining
21301** validity.
21302**
21303** If some prefix of the input string is a valid number, this routine
21304** returns FALSE but it still converts the prefix and writes the result
21305** into *pResult.
21306*/
21307SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21308#ifndef SQLITE_OMIT_FLOATING_POINT
21309  int incr = (enc==SQLITE_UTF8?1:2);
21310  const char *zEnd = z + length;
21311  /* sign * significand * (10 ^ (esign * exponent)) */
21312  int sign = 1;    /* sign of significand */
21313  i64 s = 0;       /* significand */
21314  int d = 0;       /* adjust exponent for shifting decimal point */
21315  int esign = 1;   /* sign of exponent */
21316  int e = 0;       /* exponent */
21317  int eValid = 1;  /* True exponent is either not used or is well-formed */
21318  double result;
21319  int nDigits = 0;
21320
21321  *pResult = 0.0;   /* Default return value, in case of an error */
21322
21323  if( enc==SQLITE_UTF16BE ) z++;
21324
21325  /* skip leading spaces */
21326  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21327  if( z>=zEnd ) return 0;
21328
21329  /* get sign of significand */
21330  if( *z=='-' ){
21331    sign = -1;
21332    z+=incr;
21333  }else if( *z=='+' ){
21334    z+=incr;
21335  }
21336
21337  /* skip leading zeroes */
21338  while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21339
21340  /* copy max significant digits to significand */
21341  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21342    s = s*10 + (*z - '0');
21343    z+=incr, nDigits++;
21344  }
21345
21346  /* skip non-significant significand digits
21347  ** (increase exponent by d to shift decimal left) */
21348  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21349  if( z>=zEnd ) goto do_atof_calc;
21350
21351  /* if decimal point is present */
21352  if( *z=='.' ){
21353    z+=incr;
21354    /* copy digits from after decimal to significand
21355    ** (decrease exponent by d to shift decimal right) */
21356    while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21357      s = s*10 + (*z - '0');
21358      z+=incr, nDigits++, d--;
21359    }
21360    /* skip non-significant digits */
21361    while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21362  }
21363  if( z>=zEnd ) goto do_atof_calc;
21364
21365  /* if exponent is present */
21366  if( *z=='e' || *z=='E' ){
21367    z+=incr;
21368    eValid = 0;
21369    if( z>=zEnd ) goto do_atof_calc;
21370    /* get sign of exponent */
21371    if( *z=='-' ){
21372      esign = -1;
21373      z+=incr;
21374    }else if( *z=='+' ){
21375      z+=incr;
21376    }
21377    /* copy digits to exponent */
21378    while( z<zEnd && sqlite3Isdigit(*z) ){
21379      e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21380      z+=incr;
21381      eValid = 1;
21382    }
21383  }
21384
21385  /* skip trailing spaces */
21386  if( nDigits && eValid ){
21387    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21388  }
21389
21390do_atof_calc:
21391  /* adjust exponent by d, and update sign */
21392  e = (e*esign) + d;
21393  if( e<0 ) {
21394    esign = -1;
21395    e *= -1;
21396  } else {
21397    esign = 1;
21398  }
21399
21400  /* if 0 significand */
21401  if( !s ) {
21402    /* In the IEEE 754 standard, zero is signed.
21403    ** Add the sign if we've seen at least one digit */
21404    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
21405  } else {
21406    /* attempt to reduce exponent */
21407    if( esign>0 ){
21408      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
21409    }else{
21410      while( !(s%10) && e>0 ) e--,s/=10;
21411    }
21412
21413    /* adjust the sign of significand */
21414    s = sign<0 ? -s : s;
21415
21416    /* if exponent, scale significand as appropriate
21417    ** and store in result. */
21418    if( e ){
21419      double scale = 1.0;
21420      /* attempt to handle extremely small/large numbers better */
21421      if( e>307 && e<342 ){
21422        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21423        if( esign<0 ){
21424          result = s / scale;
21425          result /= 1.0e+308;
21426        }else{
21427          result = s * scale;
21428          result *= 1.0e+308;
21429        }
21430      }else if( e>=342 ){
21431        if( esign<0 ){
21432          result = 0.0*s;
21433        }else{
21434          result = 1e308*1e308*s;  /* Infinity */
21435        }
21436      }else{
21437        /* 1.0e+22 is the largest power of 10 than can be
21438        ** represented exactly. */
21439        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21440        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21441        if( esign<0 ){
21442          result = s / scale;
21443        }else{
21444          result = s * scale;
21445        }
21446      }
21447    } else {
21448      result = (double)s;
21449    }
21450  }
21451
21452  /* store the result */
21453  *pResult = result;
21454
21455  /* return true if number and no extra non-whitespace chracters after */
21456  return z>=zEnd && nDigits>0 && eValid;
21457#else
21458  return !sqlite3Atoi64(z, pResult, length, enc);
21459#endif /* SQLITE_OMIT_FLOATING_POINT */
21460}
21461
21462/*
21463** Compare the 19-character string zNum against the text representation
21464** value 2^63:  9223372036854775808.  Return negative, zero, or positive
21465** if zNum is less than, equal to, or greater than the string.
21466** Note that zNum must contain exactly 19 characters.
21467**
21468** Unlike memcmp() this routine is guaranteed to return the difference
21469** in the values of the last digit if the only difference is in the
21470** last digit.  So, for example,
21471**
21472**      compare2pow63("9223372036854775800", 1)
21473**
21474** will return -8.
21475*/
21476static int compare2pow63(const char *zNum, int incr){
21477  int c = 0;
21478  int i;
21479                    /* 012345678901234567 */
21480  const char *pow63 = "922337203685477580";
21481  for(i=0; c==0 && i<18; i++){
21482    c = (zNum[i*incr]-pow63[i])*10;
21483  }
21484  if( c==0 ){
21485    c = zNum[18*incr] - '8';
21486    testcase( c==(-1) );
21487    testcase( c==0 );
21488    testcase( c==(+1) );
21489  }
21490  return c;
21491}
21492
21493
21494/*
21495** Convert zNum to a 64-bit signed integer.
21496**
21497** If the zNum value is representable as a 64-bit twos-complement
21498** integer, then write that value into *pNum and return 0.
21499**
21500** If zNum is exactly 9223372036854665808, return 2.  This special
21501** case is broken out because while 9223372036854665808 cannot be a
21502** signed 64-bit integer, its negative -9223372036854665808 can be.
21503**
21504** If zNum is too big for a 64-bit integer and is not
21505** 9223372036854665808 then return 1.
21506**
21507** length is the number of bytes in the string (bytes, not characters).
21508** The string is not necessarily zero-terminated.  The encoding is
21509** given by enc.
21510*/
21511SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21512  int incr = (enc==SQLITE_UTF8?1:2);
21513  u64 u = 0;
21514  int neg = 0; /* assume positive */
21515  int i;
21516  int c = 0;
21517  const char *zStart;
21518  const char *zEnd = zNum + length;
21519  if( enc==SQLITE_UTF16BE ) zNum++;
21520  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21521  if( zNum<zEnd ){
21522    if( *zNum=='-' ){
21523      neg = 1;
21524      zNum+=incr;
21525    }else if( *zNum=='+' ){
21526      zNum+=incr;
21527    }
21528  }
21529  zStart = zNum;
21530  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21531  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21532    u = u*10 + c - '0';
21533  }
21534  if( u>LARGEST_INT64 ){
21535    *pNum = SMALLEST_INT64;
21536  }else if( neg ){
21537    *pNum = -(i64)u;
21538  }else{
21539    *pNum = (i64)u;
21540  }
21541  testcase( i==18 );
21542  testcase( i==19 );
21543  testcase( i==20 );
21544  if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
21545    /* zNum is empty or contains non-numeric text or is longer
21546    ** than 19 digits (thus guaranteeing that it is too large) */
21547    return 1;
21548  }else if( i<19*incr ){
21549    /* Less than 19 digits, so we know that it fits in 64 bits */
21550    assert( u<=LARGEST_INT64 );
21551    return 0;
21552  }else{
21553    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21554    c = compare2pow63(zNum, incr);
21555    if( c<0 ){
21556      /* zNum is less than 9223372036854775808 so it fits */
21557      assert( u<=LARGEST_INT64 );
21558      return 0;
21559    }else if( c>0 ){
21560      /* zNum is greater than 9223372036854775808 so it overflows */
21561      return 1;
21562    }else{
21563      /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21564      ** special case 2 overflow if positive */
21565      assert( u-1==LARGEST_INT64 );
21566      assert( (*pNum)==SMALLEST_INT64 );
21567      return neg ? 0 : 2;
21568    }
21569  }
21570}
21571
21572/*
21573** If zNum represents an integer that will fit in 32-bits, then set
21574** *pValue to that integer and return true.  Otherwise return false.
21575**
21576** Any non-numeric characters that following zNum are ignored.
21577** This is different from sqlite3Atoi64() which requires the
21578** input number to be zero-terminated.
21579*/
21580SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21581  sqlite_int64 v = 0;
21582  int i, c;
21583  int neg = 0;
21584  if( zNum[0]=='-' ){
21585    neg = 1;
21586    zNum++;
21587  }else if( zNum[0]=='+' ){
21588    zNum++;
21589  }
21590  while( zNum[0]=='0' ) zNum++;
21591  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21592    v = v*10 + c;
21593  }
21594
21595  /* The longest decimal representation of a 32 bit integer is 10 digits:
21596  **
21597  **             1234567890
21598  **     2^31 -> 2147483648
21599  */
21600  testcase( i==10 );
21601  if( i>10 ){
21602    return 0;
21603  }
21604  testcase( v-neg==2147483647 );
21605  if( v-neg>2147483647 ){
21606    return 0;
21607  }
21608  if( neg ){
21609    v = -v;
21610  }
21611  *pValue = (int)v;
21612  return 1;
21613}
21614
21615/*
21616** Return a 32-bit integer value extracted from a string.  If the
21617** string is not an integer, just return 0.
21618*/
21619SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21620  int x = 0;
21621  if( z ) sqlite3GetInt32(z, &x);
21622  return x;
21623}
21624
21625/*
21626** The variable-length integer encoding is as follows:
21627**
21628** KEY:
21629**         A = 0xxxxxxx    7 bits of data and one flag bit
21630**         B = 1xxxxxxx    7 bits of data and one flag bit
21631**         C = xxxxxxxx    8 bits of data
21632**
21633**  7 bits - A
21634** 14 bits - BA
21635** 21 bits - BBA
21636** 28 bits - BBBA
21637** 35 bits - BBBBA
21638** 42 bits - BBBBBA
21639** 49 bits - BBBBBBA
21640** 56 bits - BBBBBBBA
21641** 64 bits - BBBBBBBBC
21642*/
21643
21644/*
21645** Write a 64-bit variable-length integer to memory starting at p[0].
21646** The length of data write will be between 1 and 9 bytes.  The number
21647** of bytes written is returned.
21648**
21649** A variable-length integer consists of the lower 7 bits of each byte
21650** for all bytes that have the 8th bit set and one byte with the 8th
21651** bit clear.  Except, if we get to the 9th byte, it stores the full
21652** 8 bits and is the last byte.
21653*/
21654SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21655  int i, j, n;
21656  u8 buf[10];
21657  if( v & (((u64)0xff000000)<<32) ){
21658    p[8] = (u8)v;
21659    v >>= 8;
21660    for(i=7; i>=0; i--){
21661      p[i] = (u8)((v & 0x7f) | 0x80);
21662      v >>= 7;
21663    }
21664    return 9;
21665  }
21666  n = 0;
21667  do{
21668    buf[n++] = (u8)((v & 0x7f) | 0x80);
21669    v >>= 7;
21670  }while( v!=0 );
21671  buf[0] &= 0x7f;
21672  assert( n<=9 );
21673  for(i=0, j=n-1; j>=0; j--, i++){
21674    p[i] = buf[j];
21675  }
21676  return n;
21677}
21678
21679/*
21680** This routine is a faster version of sqlite3PutVarint() that only
21681** works for 32-bit positive integers and which is optimized for
21682** the common case of small integers.  A MACRO version, putVarint32,
21683** is provided which inlines the single-byte case.  All code should use
21684** the MACRO version as this function assumes the single-byte case has
21685** already been handled.
21686*/
21687SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21688#ifndef putVarint32
21689  if( (v & ~0x7f)==0 ){
21690    p[0] = v;
21691    return 1;
21692  }
21693#endif
21694  if( (v & ~0x3fff)==0 ){
21695    p[0] = (u8)((v>>7) | 0x80);
21696    p[1] = (u8)(v & 0x7f);
21697    return 2;
21698  }
21699  return sqlite3PutVarint(p, v);
21700}
21701
21702/*
21703** Bitmasks used by sqlite3GetVarint().  These precomputed constants
21704** are defined here rather than simply putting the constant expressions
21705** inline in order to work around bugs in the RVT compiler.
21706**
21707** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
21708**
21709** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
21710*/
21711#define SLOT_2_0     0x001fc07f
21712#define SLOT_4_2_0   0xf01fc07f
21713
21714
21715/*
21716** Read a 64-bit variable-length integer from memory starting at p[0].
21717** Return the number of bytes read.  The value is stored in *v.
21718*/
21719SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21720  u32 a,b,s;
21721
21722  a = *p;
21723  /* a: p0 (unmasked) */
21724  if (!(a&0x80))
21725  {
21726    *v = a;
21727    return 1;
21728  }
21729
21730  p++;
21731  b = *p;
21732  /* b: p1 (unmasked) */
21733  if (!(b&0x80))
21734  {
21735    a &= 0x7f;
21736    a = a<<7;
21737    a |= b;
21738    *v = a;
21739    return 2;
21740  }
21741
21742  /* Verify that constants are precomputed correctly */
21743  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21744  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21745
21746  p++;
21747  a = a<<14;
21748  a |= *p;
21749  /* a: p0<<14 | p2 (unmasked) */
21750  if (!(a&0x80))
21751  {
21752    a &= SLOT_2_0;
21753    b &= 0x7f;
21754    b = b<<7;
21755    a |= b;
21756    *v = a;
21757    return 3;
21758  }
21759
21760  /* CSE1 from below */
21761  a &= SLOT_2_0;
21762  p++;
21763  b = b<<14;
21764  b |= *p;
21765  /* b: p1<<14 | p3 (unmasked) */
21766  if (!(b&0x80))
21767  {
21768    b &= SLOT_2_0;
21769    /* moved CSE1 up */
21770    /* a &= (0x7f<<14)|(0x7f); */
21771    a = a<<7;
21772    a |= b;
21773    *v = a;
21774    return 4;
21775  }
21776
21777  /* a: p0<<14 | p2 (masked) */
21778  /* b: p1<<14 | p3 (unmasked) */
21779  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21780  /* moved CSE1 up */
21781  /* a &= (0x7f<<14)|(0x7f); */
21782  b &= SLOT_2_0;
21783  s = a;
21784  /* s: p0<<14 | p2 (masked) */
21785
21786  p++;
21787  a = a<<14;
21788  a |= *p;
21789  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21790  if (!(a&0x80))
21791  {
21792    /* we can skip these cause they were (effectively) done above in calc'ing s */
21793    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21794    /* b &= (0x7f<<14)|(0x7f); */
21795    b = b<<7;
21796    a |= b;
21797    s = s>>18;
21798    *v = ((u64)s)<<32 | a;
21799    return 5;
21800  }
21801
21802  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21803  s = s<<7;
21804  s |= b;
21805  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21806
21807  p++;
21808  b = b<<14;
21809  b |= *p;
21810  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
21811  if (!(b&0x80))
21812  {
21813    /* we can skip this cause it was (effectively) done above in calc'ing s */
21814    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21815    a &= SLOT_2_0;
21816    a = a<<7;
21817    a |= b;
21818    s = s>>18;
21819    *v = ((u64)s)<<32 | a;
21820    return 6;
21821  }
21822
21823  p++;
21824  a = a<<14;
21825  a |= *p;
21826  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21827  if (!(a&0x80))
21828  {
21829    a &= SLOT_4_2_0;
21830    b &= SLOT_2_0;
21831    b = b<<7;
21832    a |= b;
21833    s = s>>11;
21834    *v = ((u64)s)<<32 | a;
21835    return 7;
21836  }
21837
21838  /* CSE2 from below */
21839  a &= SLOT_2_0;
21840  p++;
21841  b = b<<14;
21842  b |= *p;
21843  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21844  if (!(b&0x80))
21845  {
21846    b &= SLOT_4_2_0;
21847    /* moved CSE2 up */
21848    /* a &= (0x7f<<14)|(0x7f); */
21849    a = a<<7;
21850    a |= b;
21851    s = s>>4;
21852    *v = ((u64)s)<<32 | a;
21853    return 8;
21854  }
21855
21856  p++;
21857  a = a<<15;
21858  a |= *p;
21859  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21860
21861  /* moved CSE2 up */
21862  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21863  b &= SLOT_2_0;
21864  b = b<<8;
21865  a |= b;
21866
21867  s = s<<4;
21868  b = p[-4];
21869  b &= 0x7f;
21870  b = b>>3;
21871  s |= b;
21872
21873  *v = ((u64)s)<<32 | a;
21874
21875  return 9;
21876}
21877
21878/*
21879** Read a 32-bit variable-length integer from memory starting at p[0].
21880** Return the number of bytes read.  The value is stored in *v.
21881**
21882** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21883** integer, then set *v to 0xffffffff.
21884**
21885** A MACRO version, getVarint32, is provided which inlines the
21886** single-byte case.  All code should use the MACRO version as
21887** this function assumes the single-byte case has already been handled.
21888*/
21889SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21890  u32 a,b;
21891
21892  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
21893  ** by the getVarin32() macro */
21894  a = *p;
21895  /* a: p0 (unmasked) */
21896#ifndef getVarint32
21897  if (!(a&0x80))
21898  {
21899    /* Values between 0 and 127 */
21900    *v = a;
21901    return 1;
21902  }
21903#endif
21904
21905  /* The 2-byte case */
21906  p++;
21907  b = *p;
21908  /* b: p1 (unmasked) */
21909  if (!(b&0x80))
21910  {
21911    /* Values between 128 and 16383 */
21912    a &= 0x7f;
21913    a = a<<7;
21914    *v = a | b;
21915    return 2;
21916  }
21917
21918  /* The 3-byte case */
21919  p++;
21920  a = a<<14;
21921  a |= *p;
21922  /* a: p0<<14 | p2 (unmasked) */
21923  if (!(a&0x80))
21924  {
21925    /* Values between 16384 and 2097151 */
21926    a &= (0x7f<<14)|(0x7f);
21927    b &= 0x7f;
21928    b = b<<7;
21929    *v = a | b;
21930    return 3;
21931  }
21932
21933  /* A 32-bit varint is used to store size information in btrees.
21934  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21935  ** A 3-byte varint is sufficient, for example, to record the size
21936  ** of a 1048569-byte BLOB or string.
21937  **
21938  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
21939  ** rare larger cases can be handled by the slower 64-bit varint
21940  ** routine.
21941  */
21942#if 1
21943  {
21944    u64 v64;
21945    u8 n;
21946
21947    p -= 2;
21948    n = sqlite3GetVarint(p, &v64);
21949    assert( n>3 && n<=9 );
21950    if( (v64 & SQLITE_MAX_U32)!=v64 ){
21951      *v = 0xffffffff;
21952    }else{
21953      *v = (u32)v64;
21954    }
21955    return n;
21956  }
21957
21958#else
21959  /* For following code (kept for historical record only) shows an
21960  ** unrolling for the 3- and 4-byte varint cases.  This code is
21961  ** slightly faster, but it is also larger and much harder to test.
21962  */
21963  p++;
21964  b = b<<14;
21965  b |= *p;
21966  /* b: p1<<14 | p3 (unmasked) */
21967  if (!(b&0x80))
21968  {
21969    /* Values between 2097152 and 268435455 */
21970    b &= (0x7f<<14)|(0x7f);
21971    a &= (0x7f<<14)|(0x7f);
21972    a = a<<7;
21973    *v = a | b;
21974    return 4;
21975  }
21976
21977  p++;
21978  a = a<<14;
21979  a |= *p;
21980  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21981  if (!(a&0x80))
21982  {
21983    /* Values  between 268435456 and 34359738367 */
21984    a &= SLOT_4_2_0;
21985    b &= SLOT_4_2_0;
21986    b = b<<7;
21987    *v = a | b;
21988    return 5;
21989  }
21990
21991  /* We can only reach this point when reading a corrupt database
21992  ** file.  In that case we are not in any hurry.  Use the (relatively
21993  ** slow) general-purpose sqlite3GetVarint() routine to extract the
21994  ** value. */
21995  {
21996    u64 v64;
21997    u8 n;
21998
21999    p -= 4;
22000    n = sqlite3GetVarint(p, &v64);
22001    assert( n>5 && n<=9 );
22002    *v = (u32)v64;
22003    return n;
22004  }
22005#endif
22006}
22007
22008/*
22009** Return the number of bytes that will be needed to store the given
22010** 64-bit integer.
22011*/
22012SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22013  int i = 0;
22014  do{
22015    i++;
22016    v >>= 7;
22017  }while( v!=0 && ALWAYS(i<9) );
22018  return i;
22019}
22020
22021
22022/*
22023** Read or write a four-byte big-endian integer value.
22024*/
22025SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22026  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22027}
22028SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22029  p[0] = (u8)(v>>24);
22030  p[1] = (u8)(v>>16);
22031  p[2] = (u8)(v>>8);
22032  p[3] = (u8)v;
22033}
22034
22035
22036
22037/*
22038** Translate a single byte of Hex into an integer.
22039** This routine only works if h really is a valid hexadecimal
22040** character:  0..9a..fA..F
22041*/
22042SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22043  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
22044#ifdef SQLITE_ASCII
22045  h += 9*(1&(h>>6));
22046#endif
22047#ifdef SQLITE_EBCDIC
22048  h += 9*(1&~(h>>4));
22049#endif
22050  return (u8)(h & 0xf);
22051}
22052
22053#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22054/*
22055** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
22056** value.  Return a pointer to its binary value.  Space to hold the
22057** binary value has been obtained from malloc and must be freed by
22058** the calling routine.
22059*/
22060SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
22061  char *zBlob;
22062  int i;
22063
22064  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
22065  n--;
22066  if( zBlob ){
22067    for(i=0; i<n; i+=2){
22068      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
22069    }
22070    zBlob[i/2] = 0;
22071  }
22072  return zBlob;
22073}
22074#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
22075
22076/*
22077** Log an error that is an API call on a connection pointer that should
22078** not have been used.  The "type" of connection pointer is given as the
22079** argument.  The zType is a word like "NULL" or "closed" or "invalid".
22080*/
22081static void logBadConnection(const char *zType){
22082  sqlite3_log(SQLITE_MISUSE,
22083     "API call with %s database connection pointer",
22084     zType
22085  );
22086}
22087
22088/*
22089** Check to make sure we have a valid db pointer.  This test is not
22090** foolproof but it does provide some measure of protection against
22091** misuse of the interface such as passing in db pointers that are
22092** NULL or which have been previously closed.  If this routine returns
22093** 1 it means that the db pointer is valid and 0 if it should not be
22094** dereferenced for any reason.  The calling function should invoke
22095** SQLITE_MISUSE immediately.
22096**
22097** sqlite3SafetyCheckOk() requires that the db pointer be valid for
22098** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
22099** open properly and is not fit for general use but which can be
22100** used as an argument to sqlite3_errmsg() or sqlite3_close().
22101*/
22102SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
22103  u32 magic;
22104  if( db==0 ){
22105    logBadConnection("NULL");
22106    return 0;
22107  }
22108  magic = db->magic;
22109  if( magic!=SQLITE_MAGIC_OPEN ){
22110    if( sqlite3SafetyCheckSickOrOk(db) ){
22111      testcase( sqlite3GlobalConfig.xLog!=0 );
22112      logBadConnection("unopened");
22113    }
22114    return 0;
22115  }else{
22116    return 1;
22117  }
22118}
22119SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22120  u32 magic;
22121  magic = db->magic;
22122  if( magic!=SQLITE_MAGIC_SICK &&
22123      magic!=SQLITE_MAGIC_OPEN &&
22124      magic!=SQLITE_MAGIC_BUSY ){
22125    testcase( sqlite3GlobalConfig.xLog!=0 );
22126    logBadConnection("invalid");
22127    return 0;
22128  }else{
22129    return 1;
22130  }
22131}
22132
22133/*
22134** Attempt to add, substract, or multiply the 64-bit signed value iB against
22135** the other 64-bit signed integer at *pA and store the result in *pA.
22136** Return 0 on success.  Or if the operation would have resulted in an
22137** overflow, leave *pA unchanged and return 1.
22138*/
22139SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22140  i64 iA = *pA;
22141  testcase( iA==0 ); testcase( iA==1 );
22142  testcase( iB==-1 ); testcase( iB==0 );
22143  if( iB>=0 ){
22144    testcase( iA>0 && LARGEST_INT64 - iA == iB );
22145    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22146    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22147    *pA += iB;
22148  }else{
22149    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22150    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22151    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22152    *pA += iB;
22153  }
22154  return 0;
22155}
22156SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22157  testcase( iB==SMALLEST_INT64+1 );
22158  if( iB==SMALLEST_INT64 ){
22159    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22160    if( (*pA)>=0 ) return 1;
22161    *pA -= iB;
22162    return 0;
22163  }else{
22164    return sqlite3AddInt64(pA, -iB);
22165  }
22166}
22167#define TWOPOWER32 (((i64)1)<<32)
22168#define TWOPOWER31 (((i64)1)<<31)
22169SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22170  i64 iA = *pA;
22171  i64 iA1, iA0, iB1, iB0, r;
22172
22173  iA1 = iA/TWOPOWER32;
22174  iA0 = iA % TWOPOWER32;
22175  iB1 = iB/TWOPOWER32;
22176  iB0 = iB % TWOPOWER32;
22177  if( iA1*iB1 != 0 ) return 1;
22178  assert( iA1*iB0==0 || iA0*iB1==0 );
22179  r = iA1*iB0 + iA0*iB1;
22180  testcase( r==(-TWOPOWER31)-1 );
22181  testcase( r==(-TWOPOWER31) );
22182  testcase( r==TWOPOWER31 );
22183  testcase( r==TWOPOWER31-1 );
22184  if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22185  r *= TWOPOWER32;
22186  if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22187  *pA = r;
22188  return 0;
22189}
22190
22191/*
22192** Compute the absolute value of a 32-bit signed integer, of possible.  Or
22193** if the integer has a value of -2147483648, return +2147483647
22194*/
22195SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22196  if( x>=0 ) return x;
22197  if( x==(int)0x80000000 ) return 0x7fffffff;
22198  return -x;
22199}
22200
22201#ifdef SQLITE_ENABLE_8_3_NAMES
22202/*
22203** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22204** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22205** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22206** three characters, then shorten the suffix on z[] to be the last three
22207** characters of the original suffix.
22208**
22209** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22210** do the suffix shortening regardless of URI parameter.
22211**
22212** Examples:
22213**
22214**     test.db-journal    =>   test.nal
22215**     test.db-wal        =>   test.wal
22216**     test.db-shm        =>   test.shm
22217**     test.db-mj7f3319fa =>   test.9fa
22218*/
22219SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22220#if SQLITE_ENABLE_8_3_NAMES<2
22221  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22222#endif
22223  {
22224    int i, sz;
22225    sz = sqlite3Strlen30(z);
22226    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22227    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22228  }
22229}
22230#endif
22231
22232/************** End of util.c ************************************************/
22233/************** Begin file hash.c ********************************************/
22234/*
22235** 2001 September 22
22236**
22237** The author disclaims copyright to this source code.  In place of
22238** a legal notice, here is a blessing:
22239**
22240**    May you do good and not evil.
22241**    May you find forgiveness for yourself and forgive others.
22242**    May you share freely, never taking more than you give.
22243**
22244*************************************************************************
22245** This is the implementation of generic hash-tables
22246** used in SQLite.
22247*/
22248/* #include <assert.h> */
22249
22250/* Turn bulk memory into a hash table object by initializing the
22251** fields of the Hash structure.
22252**
22253** "pNew" is a pointer to the hash table that is to be initialized.
22254*/
22255SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22256  assert( pNew!=0 );
22257  pNew->first = 0;
22258  pNew->count = 0;
22259  pNew->htsize = 0;
22260  pNew->ht = 0;
22261}
22262
22263/* Remove all entries from a hash table.  Reclaim all memory.
22264** Call this routine to delete a hash table or to reset a hash table
22265** to the empty state.
22266*/
22267SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22268  HashElem *elem;         /* For looping over all elements of the table */
22269
22270  assert( pH!=0 );
22271  elem = pH->first;
22272  pH->first = 0;
22273  sqlite3_free(pH->ht);
22274  pH->ht = 0;
22275  pH->htsize = 0;
22276  while( elem ){
22277    HashElem *next_elem = elem->next;
22278    sqlite3_free(elem);
22279    elem = next_elem;
22280  }
22281  pH->count = 0;
22282}
22283
22284/*
22285** The hashing function.
22286*/
22287static unsigned int strHash(const char *z, int nKey){
22288  int h = 0;
22289  assert( nKey>=0 );
22290  while( nKey > 0  ){
22291    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22292    nKey--;
22293  }
22294  return h;
22295}
22296
22297
22298/* Link pNew element into the hash table pH.  If pEntry!=0 then also
22299** insert pNew into the pEntry hash bucket.
22300*/
22301static void insertElement(
22302  Hash *pH,              /* The complete hash table */
22303  struct _ht *pEntry,    /* The entry into which pNew is inserted */
22304  HashElem *pNew         /* The element to be inserted */
22305){
22306  HashElem *pHead;       /* First element already in pEntry */
22307  if( pEntry ){
22308    pHead = pEntry->count ? pEntry->chain : 0;
22309    pEntry->count++;
22310    pEntry->chain = pNew;
22311  }else{
22312    pHead = 0;
22313  }
22314  if( pHead ){
22315    pNew->next = pHead;
22316    pNew->prev = pHead->prev;
22317    if( pHead->prev ){ pHead->prev->next = pNew; }
22318    else             { pH->first = pNew; }
22319    pHead->prev = pNew;
22320  }else{
22321    pNew->next = pH->first;
22322    if( pH->first ){ pH->first->prev = pNew; }
22323    pNew->prev = 0;
22324    pH->first = pNew;
22325  }
22326}
22327
22328
22329/* Resize the hash table so that it cantains "new_size" buckets.
22330**
22331** The hash table might fail to resize if sqlite3_malloc() fails or
22332** if the new size is the same as the prior size.
22333** Return TRUE if the resize occurs and false if not.
22334*/
22335static int rehash(Hash *pH, unsigned int new_size){
22336  struct _ht *new_ht;            /* The new hash table */
22337  HashElem *elem, *next_elem;    /* For looping over existing elements */
22338
22339#if SQLITE_MALLOC_SOFT_LIMIT>0
22340  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
22341    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
22342  }
22343  if( new_size==pH->htsize ) return 0;
22344#endif
22345
22346  /* The inability to allocates space for a larger hash table is
22347  ** a performance hit but it is not a fatal error.  So mark the
22348  ** allocation as a benign.
22349  */
22350  sqlite3BeginBenignMalloc();
22351  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
22352  sqlite3EndBenignMalloc();
22353
22354  if( new_ht==0 ) return 0;
22355  sqlite3_free(pH->ht);
22356  pH->ht = new_ht;
22357  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
22358  memset(new_ht, 0, new_size*sizeof(struct _ht));
22359  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
22360    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
22361    next_elem = elem->next;
22362    insertElement(pH, &new_ht[h], elem);
22363  }
22364  return 1;
22365}
22366
22367/* This function (for internal use only) locates an element in an
22368** hash table that matches the given key.  The hash for this key has
22369** already been computed and is passed as the 4th parameter.
22370*/
22371static HashElem *findElementGivenHash(
22372  const Hash *pH,     /* The pH to be searched */
22373  const char *pKey,   /* The key we are searching for */
22374  int nKey,           /* Bytes in key (not counting zero terminator) */
22375  unsigned int h      /* The hash for this key. */
22376){
22377  HashElem *elem;                /* Used to loop thru the element list */
22378  int count;                     /* Number of elements left to test */
22379
22380  if( pH->ht ){
22381    struct _ht *pEntry = &pH->ht[h];
22382    elem = pEntry->chain;
22383    count = pEntry->count;
22384  }else{
22385    elem = pH->first;
22386    count = pH->count;
22387  }
22388  while( count-- && ALWAYS(elem) ){
22389    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
22390      return elem;
22391    }
22392    elem = elem->next;
22393  }
22394  return 0;
22395}
22396
22397/* Remove a single entry from the hash table given a pointer to that
22398** element and a hash on the element's key.
22399*/
22400static void removeElementGivenHash(
22401  Hash *pH,         /* The pH containing "elem" */
22402  HashElem* elem,   /* The element to be removed from the pH */
22403  unsigned int h    /* Hash value for the element */
22404){
22405  struct _ht *pEntry;
22406  if( elem->prev ){
22407    elem->prev->next = elem->next;
22408  }else{
22409    pH->first = elem->next;
22410  }
22411  if( elem->next ){
22412    elem->next->prev = elem->prev;
22413  }
22414  if( pH->ht ){
22415    pEntry = &pH->ht[h];
22416    if( pEntry->chain==elem ){
22417      pEntry->chain = elem->next;
22418    }
22419    pEntry->count--;
22420    assert( pEntry->count>=0 );
22421  }
22422  sqlite3_free( elem );
22423  pH->count--;
22424  if( pH->count<=0 ){
22425    assert( pH->first==0 );
22426    assert( pH->count==0 );
22427    sqlite3HashClear(pH);
22428  }
22429}
22430
22431/* Attempt to locate an element of the hash table pH with a key
22432** that matches pKey,nKey.  Return the data for this element if it is
22433** found, or NULL if there is no match.
22434*/
22435SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22436  HashElem *elem;    /* The element that matches key */
22437  unsigned int h;    /* A hash on key */
22438
22439  assert( pH!=0 );
22440  assert( pKey!=0 );
22441  assert( nKey>=0 );
22442  if( pH->ht ){
22443    h = strHash(pKey, nKey) % pH->htsize;
22444  }else{
22445    h = 0;
22446  }
22447  elem = findElementGivenHash(pH, pKey, nKey, h);
22448  return elem ? elem->data : 0;
22449}
22450
22451/* Insert an element into the hash table pH.  The key is pKey,nKey
22452** and the data is "data".
22453**
22454** If no element exists with a matching key, then a new
22455** element is created and NULL is returned.
22456**
22457** If another element already exists with the same key, then the
22458** new data replaces the old data and the old data is returned.
22459** The key is not copied in this instance.  If a malloc fails, then
22460** the new data is returned and the hash table is unchanged.
22461**
22462** If the "data" parameter to this function is NULL, then the
22463** element corresponding to "key" is removed from the hash table.
22464*/
22465SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22466  unsigned int h;       /* the hash of the key modulo hash table size */
22467  HashElem *elem;       /* Used to loop thru the element list */
22468  HashElem *new_elem;   /* New element added to the pH */
22469
22470  assert( pH!=0 );
22471  assert( pKey!=0 );
22472  assert( nKey>=0 );
22473  if( pH->htsize ){
22474    h = strHash(pKey, nKey) % pH->htsize;
22475  }else{
22476    h = 0;
22477  }
22478  elem = findElementGivenHash(pH,pKey,nKey,h);
22479  if( elem ){
22480    void *old_data = elem->data;
22481    if( data==0 ){
22482      removeElementGivenHash(pH,elem,h);
22483    }else{
22484      elem->data = data;
22485      elem->pKey = pKey;
22486      assert(nKey==elem->nKey);
22487    }
22488    return old_data;
22489  }
22490  if( data==0 ) return 0;
22491  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22492  if( new_elem==0 ) return data;
22493  new_elem->pKey = pKey;
22494  new_elem->nKey = nKey;
22495  new_elem->data = data;
22496  pH->count++;
22497  if( pH->count>=10 && pH->count > 2*pH->htsize ){
22498    if( rehash(pH, pH->count*2) ){
22499      assert( pH->htsize>0 );
22500      h = strHash(pKey, nKey) % pH->htsize;
22501    }
22502  }
22503  if( pH->ht ){
22504    insertElement(pH, &pH->ht[h], new_elem);
22505  }else{
22506    insertElement(pH, 0, new_elem);
22507  }
22508  return 0;
22509}
22510
22511/************** End of hash.c ************************************************/
22512/************** Begin file opcodes.c *****************************************/
22513/* Automatically generated.  Do not edit */
22514/* See the mkopcodec.awk script for details. */
22515#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22516SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22517 static const char *const azName[] = { "?",
22518     /*   1 */ "Goto",
22519     /*   2 */ "Gosub",
22520     /*   3 */ "Return",
22521     /*   4 */ "Yield",
22522     /*   5 */ "HaltIfNull",
22523     /*   6 */ "Halt",
22524     /*   7 */ "Integer",
22525     /*   8 */ "Int64",
22526     /*   9 */ "String",
22527     /*  10 */ "Null",
22528     /*  11 */ "Blob",
22529     /*  12 */ "Variable",
22530     /*  13 */ "Move",
22531     /*  14 */ "Copy",
22532     /*  15 */ "SCopy",
22533     /*  16 */ "ResultRow",
22534     /*  17 */ "CollSeq",
22535     /*  18 */ "Function",
22536     /*  19 */ "Not",
22537     /*  20 */ "AddImm",
22538     /*  21 */ "MustBeInt",
22539     /*  22 */ "RealAffinity",
22540     /*  23 */ "Permutation",
22541     /*  24 */ "Compare",
22542     /*  25 */ "Jump",
22543     /*  26 */ "Once",
22544     /*  27 */ "If",
22545     /*  28 */ "IfNot",
22546     /*  29 */ "Column",
22547     /*  30 */ "Affinity",
22548     /*  31 */ "MakeRecord",
22549     /*  32 */ "Count",
22550     /*  33 */ "Savepoint",
22551     /*  34 */ "AutoCommit",
22552     /*  35 */ "Transaction",
22553     /*  36 */ "ReadCookie",
22554     /*  37 */ "SetCookie",
22555     /*  38 */ "VerifyCookie",
22556     /*  39 */ "OpenRead",
22557     /*  40 */ "OpenWrite",
22558     /*  41 */ "OpenAutoindex",
22559     /*  42 */ "OpenEphemeral",
22560     /*  43 */ "SorterOpen",
22561     /*  44 */ "OpenPseudo",
22562     /*  45 */ "Close",
22563     /*  46 */ "SeekLt",
22564     /*  47 */ "SeekLe",
22565     /*  48 */ "SeekGe",
22566     /*  49 */ "SeekGt",
22567     /*  50 */ "Seek",
22568     /*  51 */ "NotFound",
22569     /*  52 */ "Found",
22570     /*  53 */ "IsUnique",
22571     /*  54 */ "NotExists",
22572     /*  55 */ "Sequence",
22573     /*  56 */ "NewRowid",
22574     /*  57 */ "Insert",
22575     /*  58 */ "InsertInt",
22576     /*  59 */ "Delete",
22577     /*  60 */ "ResetCount",
22578     /*  61 */ "SorterCompare",
22579     /*  62 */ "SorterData",
22580     /*  63 */ "RowKey",
22581     /*  64 */ "RowData",
22582     /*  65 */ "Rowid",
22583     /*  66 */ "NullRow",
22584     /*  67 */ "Last",
22585     /*  68 */ "Or",
22586     /*  69 */ "And",
22587     /*  70 */ "SorterSort",
22588     /*  71 */ "Sort",
22589     /*  72 */ "Rewind",
22590     /*  73 */ "IsNull",
22591     /*  74 */ "NotNull",
22592     /*  75 */ "Ne",
22593     /*  76 */ "Eq",
22594     /*  77 */ "Gt",
22595     /*  78 */ "Le",
22596     /*  79 */ "Lt",
22597     /*  80 */ "Ge",
22598     /*  81 */ "SorterNext",
22599     /*  82 */ "BitAnd",
22600     /*  83 */ "BitOr",
22601     /*  84 */ "ShiftLeft",
22602     /*  85 */ "ShiftRight",
22603     /*  86 */ "Add",
22604     /*  87 */ "Subtract",
22605     /*  88 */ "Multiply",
22606     /*  89 */ "Divide",
22607     /*  90 */ "Remainder",
22608     /*  91 */ "Concat",
22609     /*  92 */ "Prev",
22610     /*  93 */ "BitNot",
22611     /*  94 */ "String8",
22612     /*  95 */ "Next",
22613     /*  96 */ "SorterInsert",
22614     /*  97 */ "IdxInsert",
22615     /*  98 */ "IdxDelete",
22616     /*  99 */ "IdxRowid",
22617     /* 100 */ "IdxLT",
22618     /* 101 */ "IdxGE",
22619     /* 102 */ "Destroy",
22620     /* 103 */ "Clear",
22621     /* 104 */ "CreateIndex",
22622     /* 105 */ "CreateTable",
22623     /* 106 */ "ParseSchema",
22624     /* 107 */ "LoadAnalysis",
22625     /* 108 */ "DropTable",
22626     /* 109 */ "DropIndex",
22627     /* 110 */ "DropTrigger",
22628     /* 111 */ "IntegrityCk",
22629     /* 112 */ "RowSetAdd",
22630     /* 113 */ "RowSetRead",
22631     /* 114 */ "RowSetTest",
22632     /* 115 */ "Program",
22633     /* 116 */ "Param",
22634     /* 117 */ "FkCounter",
22635     /* 118 */ "FkIfZero",
22636     /* 119 */ "MemMax",
22637     /* 120 */ "IfPos",
22638     /* 121 */ "IfNeg",
22639     /* 122 */ "IfZero",
22640     /* 123 */ "AggStep",
22641     /* 124 */ "AggFinal",
22642     /* 125 */ "Checkpoint",
22643     /* 126 */ "JournalMode",
22644     /* 127 */ "Vacuum",
22645     /* 128 */ "IncrVacuum",
22646     /* 129 */ "Expire",
22647     /* 130 */ "Real",
22648     /* 131 */ "TableLock",
22649     /* 132 */ "VBegin",
22650     /* 133 */ "VCreate",
22651     /* 134 */ "VDestroy",
22652     /* 135 */ "VOpen",
22653     /* 136 */ "VFilter",
22654     /* 137 */ "VColumn",
22655     /* 138 */ "VNext",
22656     /* 139 */ "VRename",
22657     /* 140 */ "VUpdate",
22658     /* 141 */ "ToText",
22659     /* 142 */ "ToBlob",
22660     /* 143 */ "ToNumeric",
22661     /* 144 */ "ToInt",
22662     /* 145 */ "ToReal",
22663     /* 146 */ "Pagecount",
22664     /* 147 */ "MaxPgcnt",
22665     /* 148 */ "Trace",
22666     /* 149 */ "Noop",
22667     /* 150 */ "Explain",
22668  };
22669  return azName[i];
22670}
22671#endif
22672
22673/************** End of opcodes.c *********************************************/
22674/************** Begin file os_os2.c ******************************************/
22675/*
22676** 2006 Feb 14
22677**
22678** The author disclaims copyright to this source code.  In place of
22679** a legal notice, here is a blessing:
22680**
22681**    May you do good and not evil.
22682**    May you find forgiveness for yourself and forgive others.
22683**    May you share freely, never taking more than you give.
22684**
22685******************************************************************************
22686**
22687** This file contains code that is specific to OS/2.
22688*/
22689
22690
22691#if SQLITE_OS_OS2
22692
22693/*
22694** A Note About Memory Allocation:
22695**
22696** This driver uses malloc()/free() directly rather than going through
22697** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
22698** are designed for use on embedded systems where memory is scarce and
22699** malloc failures happen frequently.  OS/2 does not typically run on
22700** embedded systems, and when it does the developers normally have bigger
22701** problems to worry about than running out of memory.  So there is not
22702** a compelling need to use the wrappers.
22703**
22704** But there is a good reason to not use the wrappers.  If we use the
22705** wrappers then we will get simulated malloc() failures within this
22706** driver.  And that causes all kinds of problems for our tests.  We
22707** could enhance SQLite to deal with simulated malloc failures within
22708** the OS driver, but the code to deal with those failure would not
22709** be exercised on Linux (which does not need to malloc() in the driver)
22710** and so we would have difficulty writing coverage tests for that
22711** code.  Better to leave the code out, we think.
22712**
22713** The point of this discussion is as follows:  When creating a new
22714** OS layer for an embedded system, if you use this file as an example,
22715** avoid the use of malloc()/free().  Those routines work ok on OS/2
22716** desktops but not so well in embedded systems.
22717*/
22718
22719/*
22720** Macros used to determine whether or not to use threads.
22721*/
22722#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
22723# define SQLITE_OS2_THREADS 1
22724#endif
22725
22726/*
22727** Include code that is common to all os_*.c files
22728*/
22729/************** Include os_common.h in the middle of os_os2.c ****************/
22730/************** Begin file os_common.h ***************************************/
22731/*
22732** 2004 May 22
22733**
22734** The author disclaims copyright to this source code.  In place of
22735** a legal notice, here is a blessing:
22736**
22737**    May you do good and not evil.
22738**    May you find forgiveness for yourself and forgive others.
22739**    May you share freely, never taking more than you give.
22740**
22741******************************************************************************
22742**
22743** This file contains macros and a little bit of code that is common to
22744** all of the platform-specific files (os_*.c) and is #included into those
22745** files.
22746**
22747** This file should be #included by the os_*.c files only.  It is not a
22748** general purpose header file.
22749*/
22750#ifndef _OS_COMMON_H_
22751#define _OS_COMMON_H_
22752
22753/*
22754** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22755** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22756** switch.  The following code should catch this problem at compile-time.
22757*/
22758#ifdef MEMORY_DEBUG
22759# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22760#endif
22761
22762#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
22763# ifndef SQLITE_DEBUG_OS_TRACE
22764#   define SQLITE_DEBUG_OS_TRACE 0
22765# endif
22766  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
22767# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22768#else
22769# define OSTRACE(X)
22770#endif
22771
22772/*
22773** Macros for performance tracing.  Normally turned off.  Only works
22774** on i486 hardware.
22775*/
22776#ifdef SQLITE_PERFORMANCE_TRACE
22777
22778/*
22779** hwtime.h contains inline assembler code for implementing
22780** high-performance timing routines.
22781*/
22782/************** Include hwtime.h in the middle of os_common.h ****************/
22783/************** Begin file hwtime.h ******************************************/
22784/*
22785** 2008 May 27
22786**
22787** The author disclaims copyright to this source code.  In place of
22788** a legal notice, here is a blessing:
22789**
22790**    May you do good and not evil.
22791**    May you find forgiveness for yourself and forgive others.
22792**    May you share freely, never taking more than you give.
22793**
22794******************************************************************************
22795**
22796** This file contains inline asm code for retrieving "high-performance"
22797** counters for x86 class CPUs.
22798*/
22799#ifndef _HWTIME_H_
22800#define _HWTIME_H_
22801
22802/*
22803** The following routine only works on pentium-class (or newer) processors.
22804** It uses the RDTSC opcode to read the cycle count value out of the
22805** processor and returns that value.  This can be used for high-res
22806** profiling.
22807*/
22808#if (defined(__GNUC__) || defined(_MSC_VER)) && \
22809      (defined(i386) || defined(__i386__) || defined(_M_IX86))
22810
22811  #if defined(__GNUC__)
22812
22813  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22814     unsigned int lo, hi;
22815     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22816     return (sqlite_uint64)hi << 32 | lo;
22817  }
22818
22819  #elif defined(_MSC_VER)
22820
22821  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22822     __asm {
22823        rdtsc
22824        ret       ; return value at EDX:EAX
22825     }
22826  }
22827
22828  #endif
22829
22830#elif (defined(__GNUC__) && defined(__x86_64__))
22831
22832  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22833      unsigned long val;
22834      __asm__ __volatile__ ("rdtsc" : "=A" (val));
22835      return val;
22836  }
22837
22838#elif (defined(__GNUC__) && defined(__ppc__))
22839
22840  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22841      unsigned long long retval;
22842      unsigned long junk;
22843      __asm__ __volatile__ ("\n\
22844          1:      mftbu   %1\n\
22845                  mftb    %L0\n\
22846                  mftbu   %0\n\
22847                  cmpw    %0,%1\n\
22848                  bne     1b"
22849                  : "=r" (retval), "=r" (junk));
22850      return retval;
22851  }
22852
22853#else
22854
22855  #error Need implementation of sqlite3Hwtime() for your platform.
22856
22857  /*
22858  ** To compile without implementing sqlite3Hwtime() for your platform,
22859  ** you can remove the above #error and use the following
22860  ** stub function.  You will lose timing support for many
22861  ** of the debugging and testing utilities, but it should at
22862  ** least compile and run.
22863  */
22864SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22865
22866#endif
22867
22868#endif /* !defined(_HWTIME_H_) */
22869
22870/************** End of hwtime.h **********************************************/
22871/************** Continuing where we left off in os_common.h ******************/
22872
22873static sqlite_uint64 g_start;
22874static sqlite_uint64 g_elapsed;
22875#define TIMER_START       g_start=sqlite3Hwtime()
22876#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22877#define TIMER_ELAPSED     g_elapsed
22878#else
22879#define TIMER_START
22880#define TIMER_END
22881#define TIMER_ELAPSED     ((sqlite_uint64)0)
22882#endif
22883
22884/*
22885** If we compile with the SQLITE_TEST macro set, then the following block
22886** of code will give us the ability to simulate a disk I/O error.  This
22887** is used for testing the I/O recovery logic.
22888*/
22889#ifdef SQLITE_TEST
22890SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22891SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22892SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22893SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22894SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22895SQLITE_API int sqlite3_diskfull_pending = 0;
22896SQLITE_API int sqlite3_diskfull = 0;
22897#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22898#define SimulateIOError(CODE)  \
22899  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22900       || sqlite3_io_error_pending-- == 1 )  \
22901              { local_ioerr(); CODE; }
22902static void local_ioerr(){
22903  IOTRACE(("IOERR\n"));
22904  sqlite3_io_error_hit++;
22905  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22906}
22907#define SimulateDiskfullError(CODE) \
22908   if( sqlite3_diskfull_pending ){ \
22909     if( sqlite3_diskfull_pending == 1 ){ \
22910       local_ioerr(); \
22911       sqlite3_diskfull = 1; \
22912       sqlite3_io_error_hit = 1; \
22913       CODE; \
22914     }else{ \
22915       sqlite3_diskfull_pending--; \
22916     } \
22917   }
22918#else
22919#define SimulateIOErrorBenign(X)
22920#define SimulateIOError(A)
22921#define SimulateDiskfullError(A)
22922#endif
22923
22924/*
22925** When testing, keep a count of the number of open files.
22926*/
22927#ifdef SQLITE_TEST
22928SQLITE_API int sqlite3_open_file_count = 0;
22929#define OpenCounter(X)  sqlite3_open_file_count+=(X)
22930#else
22931#define OpenCounter(X)
22932#endif
22933
22934#endif /* !defined(_OS_COMMON_H_) */
22935
22936/************** End of os_common.h *******************************************/
22937/************** Continuing where we left off in os_os2.c *********************/
22938
22939/* Forward references */
22940typedef struct os2File os2File;         /* The file structure */
22941typedef struct os2ShmNode os2ShmNode;   /* A shared descritive memory node */
22942typedef struct os2ShmLink os2ShmLink;   /* A connection to shared-memory */
22943
22944/*
22945** The os2File structure is subclass of sqlite3_file specific for the OS/2
22946** protability layer.
22947*/
22948struct os2File {
22949  const sqlite3_io_methods *pMethod;  /* Always the first entry */
22950  HFILE h;                  /* Handle for accessing the file */
22951  int flags;                /* Flags provided to os2Open() */
22952  int locktype;             /* Type of lock currently held on this file */
22953  int szChunk;              /* Chunk size configured by FCNTL_CHUNK_SIZE */
22954  char *zFullPathCp;        /* Full path name of this file */
22955  os2ShmLink *pShmLink;     /* Instance of shared memory on this file */
22956};
22957
22958#define LOCK_TIMEOUT 10L /* the default locking timeout */
22959
22960/*
22961** Missing from some versions of the OS/2 toolkit -
22962** used to allocate from high memory if possible
22963*/
22964#ifndef OBJ_ANY
22965# define OBJ_ANY 0x00000400
22966#endif
22967
22968/*****************************************************************************
22969** The next group of routines implement the I/O methods specified
22970** by the sqlite3_io_methods object.
22971******************************************************************************/
22972
22973/*
22974** Close a file.
22975*/
22976static int os2Close( sqlite3_file *id ){
22977  APIRET rc;
22978  os2File *pFile = (os2File*)id;
22979
22980  assert( id!=0 );
22981  OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
22982
22983  rc = DosClose( pFile->h );
22984
22985  if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
22986    DosForceDelete( (PSZ)pFile->zFullPathCp );
22987
22988  free( pFile->zFullPathCp );
22989  pFile->zFullPathCp = NULL;
22990  pFile->locktype = NO_LOCK;
22991  pFile->h = (HFILE)-1;
22992  pFile->flags = 0;
22993
22994  OpenCounter( -1 );
22995  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22996}
22997
22998/*
22999** Read data from a file into a buffer.  Return SQLITE_OK if all
23000** bytes were read successfully and SQLITE_IOERR if anything goes
23001** wrong.
23002*/
23003static int os2Read(
23004  sqlite3_file *id,               /* File to read from */
23005  void *pBuf,                     /* Write content into this buffer */
23006  int amt,                        /* Number of bytes to read */
23007  sqlite3_int64 offset            /* Begin reading at this offset */
23008){
23009  ULONG fileLocation = 0L;
23010  ULONG got;
23011  os2File *pFile = (os2File*)id;
23012  assert( id!=0 );
23013  SimulateIOError( return SQLITE_IOERR_READ );
23014  OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
23015  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
23016    return SQLITE_IOERR;
23017  }
23018  if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
23019    return SQLITE_IOERR_READ;
23020  }
23021  if( got == (ULONG)amt )
23022    return SQLITE_OK;
23023  else {
23024    /* Unread portions of the input buffer must be zero-filled */
23025    memset(&((char*)pBuf)[got], 0, amt-got);
23026    return SQLITE_IOERR_SHORT_READ;
23027  }
23028}
23029
23030/*
23031** Write data from a buffer into a file.  Return SQLITE_OK on success
23032** or some other error code on failure.
23033*/
23034static int os2Write(
23035  sqlite3_file *id,               /* File to write into */
23036  const void *pBuf,               /* The bytes to be written */
23037  int amt,                        /* Number of bytes to write */
23038  sqlite3_int64 offset            /* Offset into the file to begin writing at */
23039){
23040  ULONG fileLocation = 0L;
23041  APIRET rc = NO_ERROR;
23042  ULONG wrote;
23043  os2File *pFile = (os2File*)id;
23044  assert( id!=0 );
23045  SimulateIOError( return SQLITE_IOERR_WRITE );
23046  SimulateDiskfullError( return SQLITE_FULL );
23047  OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
23048  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
23049    return SQLITE_IOERR;
23050  }
23051  assert( amt>0 );
23052  while( amt > 0 &&
23053         ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
23054         wrote > 0
23055  ){
23056    amt -= wrote;
23057    pBuf = &((char*)pBuf)[wrote];
23058  }
23059
23060  return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
23061}
23062
23063/*
23064** Truncate an open file to a specified size
23065*/
23066static int os2Truncate( sqlite3_file *id, i64 nByte ){
23067  APIRET rc;
23068  os2File *pFile = (os2File*)id;
23069  assert( id!=0 );
23070  OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
23071  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
23072
23073  /* If the user has configured a chunk-size for this file, truncate the
23074  ** file so that it consists of an integer number of chunks (i.e. the
23075  ** actual file size after the operation may be larger than the requested
23076  ** size).
23077  */
23078  if( pFile->szChunk ){
23079    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
23080  }
23081
23082  rc = DosSetFileSize( pFile->h, nByte );
23083  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
23084}
23085
23086#ifdef SQLITE_TEST
23087/*
23088** Count the number of fullsyncs and normal syncs.  This is used to test
23089** that syncs and fullsyncs are occuring at the right times.
23090*/
23091SQLITE_API int sqlite3_sync_count = 0;
23092SQLITE_API int sqlite3_fullsync_count = 0;
23093#endif
23094
23095/*
23096** Make sure all writes to a particular file are committed to disk.
23097*/
23098static int os2Sync( sqlite3_file *id, int flags ){
23099  os2File *pFile = (os2File*)id;
23100  OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
23101#ifdef SQLITE_TEST
23102  if( flags & SQLITE_SYNC_FULL){
23103    sqlite3_fullsync_count++;
23104  }
23105  sqlite3_sync_count++;
23106#endif
23107  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
23108  ** no-op
23109  */
23110#ifdef SQLITE_NO_SYNC
23111  UNUSED_PARAMETER(pFile);
23112  return SQLITE_OK;
23113#else
23114  return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23115#endif
23116}
23117
23118/*
23119** Determine the current size of a file in bytes
23120*/
23121static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
23122  APIRET rc = NO_ERROR;
23123  FILESTATUS3 fsts3FileInfo;
23124  memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
23125  assert( id!=0 );
23126  SimulateIOError( return SQLITE_IOERR_FSTAT );
23127  rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
23128  if( rc == NO_ERROR ){
23129    *pSize = fsts3FileInfo.cbFile;
23130    return SQLITE_OK;
23131  }else{
23132    return SQLITE_IOERR_FSTAT;
23133  }
23134}
23135
23136/*
23137** Acquire a reader lock.
23138*/
23139static int getReadLock( os2File *pFile ){
23140  FILELOCK  LockArea,
23141            UnlockArea;
23142  APIRET res;
23143  memset(&LockArea, 0, sizeof(LockArea));
23144  memset(&UnlockArea, 0, sizeof(UnlockArea));
23145  LockArea.lOffset = SHARED_FIRST;
23146  LockArea.lRange = SHARED_SIZE;
23147  UnlockArea.lOffset = 0L;
23148  UnlockArea.lRange = 0L;
23149  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
23150  OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
23151  return res;
23152}
23153
23154/*
23155** Undo a readlock
23156*/
23157static int unlockReadLock( os2File *id ){
23158  FILELOCK  LockArea,
23159            UnlockArea;
23160  APIRET res;
23161  memset(&LockArea, 0, sizeof(LockArea));
23162  memset(&UnlockArea, 0, sizeof(UnlockArea));
23163  LockArea.lOffset = 0L;
23164  LockArea.lRange = 0L;
23165  UnlockArea.lOffset = SHARED_FIRST;
23166  UnlockArea.lRange = SHARED_SIZE;
23167  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
23168  OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
23169  return res;
23170}
23171
23172/*
23173** Lock the file with the lock specified by parameter locktype - one
23174** of the following:
23175**
23176**     (1) SHARED_LOCK
23177**     (2) RESERVED_LOCK
23178**     (3) PENDING_LOCK
23179**     (4) EXCLUSIVE_LOCK
23180**
23181** Sometimes when requesting one lock state, additional lock states
23182** are inserted in between.  The locking might fail on one of the later
23183** transitions leaving the lock state different from what it started but
23184** still short of its goal.  The following chart shows the allowed
23185** transitions and the inserted intermediate states:
23186**
23187**    UNLOCKED -> SHARED
23188**    SHARED -> RESERVED
23189**    SHARED -> (PENDING) -> EXCLUSIVE
23190**    RESERVED -> (PENDING) -> EXCLUSIVE
23191**    PENDING -> EXCLUSIVE
23192**
23193** This routine will only increase a lock.  The os2Unlock() routine
23194** erases all locks at once and returns us immediately to locking level 0.
23195** It is not possible to lower the locking level one step at a time.  You
23196** must go straight to locking level 0.
23197*/
23198static int os2Lock( sqlite3_file *id, int locktype ){
23199  int rc = SQLITE_OK;       /* Return code from subroutines */
23200  APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
23201  int newLocktype;       /* Set pFile->locktype to this value before exiting */
23202  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
23203  FILELOCK  LockArea,
23204            UnlockArea;
23205  os2File *pFile = (os2File*)id;
23206  memset(&LockArea, 0, sizeof(LockArea));
23207  memset(&UnlockArea, 0, sizeof(UnlockArea));
23208  assert( pFile!=0 );
23209  OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
23210
23211  /* If there is already a lock of this type or more restrictive on the
23212  ** os2File, do nothing. Don't use the end_lock: exit path, as
23213  ** sqlite3_mutex_enter() hasn't been called yet.
23214  */
23215  if( pFile->locktype>=locktype ){
23216    OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
23217    return SQLITE_OK;
23218  }
23219
23220  /* Make sure the locking sequence is correct
23221  */
23222  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23223  assert( locktype!=PENDING_LOCK );
23224  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23225
23226  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
23227  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
23228  ** the PENDING_LOCK byte is temporary.
23229  */
23230  newLocktype = pFile->locktype;
23231  if( pFile->locktype==NO_LOCK
23232      || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
23233  ){
23234    LockArea.lOffset = PENDING_BYTE;
23235    LockArea.lRange = 1L;
23236    UnlockArea.lOffset = 0L;
23237    UnlockArea.lRange = 0L;
23238
23239    /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
23240    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
23241    if( res == NO_ERROR ){
23242      gotPendingLock = 1;
23243      OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
23244    }
23245  }
23246
23247  /* Acquire a shared lock
23248  */
23249  if( locktype==SHARED_LOCK && res == NO_ERROR ){
23250    assert( pFile->locktype==NO_LOCK );
23251    res = getReadLock(pFile);
23252    if( res == NO_ERROR ){
23253      newLocktype = SHARED_LOCK;
23254    }
23255    OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
23256  }
23257
23258  /* Acquire a RESERVED lock
23259  */
23260  if( locktype==RESERVED_LOCK && res == NO_ERROR ){
23261    assert( pFile->locktype==SHARED_LOCK );
23262    LockArea.lOffset = RESERVED_BYTE;
23263    LockArea.lRange = 1L;
23264    UnlockArea.lOffset = 0L;
23265    UnlockArea.lRange = 0L;
23266    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23267    if( res == NO_ERROR ){
23268      newLocktype = RESERVED_LOCK;
23269    }
23270    OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
23271  }
23272
23273  /* Acquire a PENDING lock
23274  */
23275  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
23276    newLocktype = PENDING_LOCK;
23277    gotPendingLock = 0;
23278    OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
23279               pFile->h ));
23280  }
23281
23282  /* Acquire an EXCLUSIVE lock
23283  */
23284  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
23285    assert( pFile->locktype>=SHARED_LOCK );
23286    res = unlockReadLock(pFile);
23287    OSTRACE(( "unreadlock = %d\n", res ));
23288    LockArea.lOffset = SHARED_FIRST;
23289    LockArea.lRange = SHARED_SIZE;
23290    UnlockArea.lOffset = 0L;
23291    UnlockArea.lRange = 0L;
23292    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23293    if( res == NO_ERROR ){
23294      newLocktype = EXCLUSIVE_LOCK;
23295    }else{
23296      OSTRACE(( "OS/2 error-code = %d\n", res ));
23297      getReadLock(pFile);
23298    }
23299    OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
23300  }
23301
23302  /* If we are holding a PENDING lock that ought to be released, then
23303  ** release it now.
23304  */
23305  if( gotPendingLock && locktype==SHARED_LOCK ){
23306    int r;
23307    LockArea.lOffset = 0L;
23308    LockArea.lRange = 0L;
23309    UnlockArea.lOffset = PENDING_BYTE;
23310    UnlockArea.lRange = 1L;
23311    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23312    OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
23313  }
23314
23315  /* Update the state of the lock has held in the file descriptor then
23316  ** return the appropriate result code.
23317  */
23318  if( res == NO_ERROR ){
23319    rc = SQLITE_OK;
23320  }else{
23321    OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
23322              locktype, newLocktype ));
23323    rc = SQLITE_BUSY;
23324  }
23325  pFile->locktype = newLocktype;
23326  OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
23327  return rc;
23328}
23329
23330/*
23331** This routine checks if there is a RESERVED lock held on the specified
23332** file by this or any other process. If such a lock is held, return
23333** non-zero, otherwise zero.
23334*/
23335static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
23336  int r = 0;
23337  os2File *pFile = (os2File*)id;
23338  assert( pFile!=0 );
23339  if( pFile->locktype>=RESERVED_LOCK ){
23340    r = 1;
23341    OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
23342  }else{
23343    FILELOCK  LockArea,
23344              UnlockArea;
23345    APIRET rc = NO_ERROR;
23346    memset(&LockArea, 0, sizeof(LockArea));
23347    memset(&UnlockArea, 0, sizeof(UnlockArea));
23348    LockArea.lOffset = RESERVED_BYTE;
23349    LockArea.lRange = 1L;
23350    UnlockArea.lOffset = 0L;
23351    UnlockArea.lRange = 0L;
23352    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23353    OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
23354    if( rc == NO_ERROR ){
23355      APIRET rcu = NO_ERROR; /* return code for unlocking */
23356      LockArea.lOffset = 0L;
23357      LockArea.lRange = 0L;
23358      UnlockArea.lOffset = RESERVED_BYTE;
23359      UnlockArea.lRange = 1L;
23360      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23361      OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
23362    }
23363    r = !(rc == NO_ERROR);
23364    OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
23365  }
23366  *pOut = r;
23367  return SQLITE_OK;
23368}
23369
23370/*
23371** Lower the locking level on file descriptor id to locktype.  locktype
23372** must be either NO_LOCK or SHARED_LOCK.
23373**
23374** If the locking level of the file descriptor is already at or below
23375** the requested locking level, this routine is a no-op.
23376**
23377** It is not possible for this routine to fail if the second argument
23378** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
23379** might return SQLITE_IOERR;
23380*/
23381static int os2Unlock( sqlite3_file *id, int locktype ){
23382  int type;
23383  os2File *pFile = (os2File*)id;
23384  APIRET rc = SQLITE_OK;
23385  APIRET res = NO_ERROR;
23386  FILELOCK  LockArea,
23387            UnlockArea;
23388  memset(&LockArea, 0, sizeof(LockArea));
23389  memset(&UnlockArea, 0, sizeof(UnlockArea));
23390  assert( pFile!=0 );
23391  assert( locktype<=SHARED_LOCK );
23392  OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
23393  type = pFile->locktype;
23394  if( type>=EXCLUSIVE_LOCK ){
23395    LockArea.lOffset = 0L;
23396    LockArea.lRange = 0L;
23397    UnlockArea.lOffset = SHARED_FIRST;
23398    UnlockArea.lRange = SHARED_SIZE;
23399    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23400    OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
23401    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
23402      /* This should never happen.  We should always be able to
23403      ** reacquire the read lock */
23404      OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
23405      rc = SQLITE_IOERR_UNLOCK;
23406    }
23407  }
23408  if( type>=RESERVED_LOCK ){
23409    LockArea.lOffset = 0L;
23410    LockArea.lRange = 0L;
23411    UnlockArea.lOffset = RESERVED_BYTE;
23412    UnlockArea.lRange = 1L;
23413    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23414    OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
23415  }
23416  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
23417    res = unlockReadLock(pFile);
23418    OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
23419              pFile->h, type, locktype, res ));
23420  }
23421  if( type>=PENDING_LOCK ){
23422    LockArea.lOffset = 0L;
23423    LockArea.lRange = 0L;
23424    UnlockArea.lOffset = PENDING_BYTE;
23425    UnlockArea.lRange = 1L;
23426    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23427    OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
23428  }
23429  pFile->locktype = locktype;
23430  OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
23431  return rc;
23432}
23433
23434/*
23435** Control and query of the open file handle.
23436*/
23437static int os2FileControl(sqlite3_file *id, int op, void *pArg){
23438  switch( op ){
23439    case SQLITE_FCNTL_LOCKSTATE: {
23440      *(int*)pArg = ((os2File*)id)->locktype;
23441      OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
23442                ((os2File*)id)->h, ((os2File*)id)->locktype ));
23443      return SQLITE_OK;
23444    }
23445    case SQLITE_FCNTL_CHUNK_SIZE: {
23446      ((os2File*)id)->szChunk = *(int*)pArg;
23447      return SQLITE_OK;
23448    }
23449    case SQLITE_FCNTL_SIZE_HINT: {
23450      sqlite3_int64 sz = *(sqlite3_int64*)pArg;
23451      SimulateIOErrorBenign(1);
23452      os2Truncate(id, sz);
23453      SimulateIOErrorBenign(0);
23454      return SQLITE_OK;
23455    }
23456    case SQLITE_FCNTL_SYNC_OMITTED: {
23457      return SQLITE_OK;
23458    }
23459  }
23460  return SQLITE_NOTFOUND;
23461}
23462
23463/*
23464** Return the sector size in bytes of the underlying block device for
23465** the specified file. This is almost always 512 bytes, but may be
23466** larger for some devices.
23467**
23468** SQLite code assumes this function cannot fail. It also assumes that
23469** if two files are created in the same file-system directory (i.e.
23470** a database and its journal file) that the sector size will be the
23471** same for both.
23472*/
23473static int os2SectorSize(sqlite3_file *id){
23474  UNUSED_PARAMETER(id);
23475  return SQLITE_DEFAULT_SECTOR_SIZE;
23476}
23477
23478/*
23479** Return a vector of device characteristics.
23480*/
23481static int os2DeviceCharacteristics(sqlite3_file *id){
23482  UNUSED_PARAMETER(id);
23483  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
23484}
23485
23486
23487/*
23488** Character set conversion objects used by conversion routines.
23489*/
23490static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
23491static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
23492
23493/*
23494** Helper function to initialize the conversion objects from and to UTF-8.
23495*/
23496static void initUconvObjects( void ){
23497  if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
23498    ucUtf8 = NULL;
23499  if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
23500    uclCp = NULL;
23501}
23502
23503/*
23504** Helper function to free the conversion objects from and to UTF-8.
23505*/
23506static void freeUconvObjects( void ){
23507  if ( ucUtf8 )
23508    UniFreeUconvObject( ucUtf8 );
23509  if ( uclCp )
23510    UniFreeUconvObject( uclCp );
23511  ucUtf8 = NULL;
23512  uclCp = NULL;
23513}
23514
23515/*
23516** Helper function to convert UTF-8 filenames to local OS/2 codepage.
23517** The two-step process: first convert the incoming UTF-8 string
23518** into UCS-2 and then from UCS-2 to the current codepage.
23519** The returned char pointer has to be freed.
23520*/
23521static char *convertUtf8PathToCp( const char *in ){
23522  UniChar tempPath[CCHMAXPATH];
23523  char *out = (char *)calloc( CCHMAXPATH, 1 );
23524
23525  if( !out )
23526    return NULL;
23527
23528  if( !ucUtf8 || !uclCp )
23529    initUconvObjects();
23530
23531  /* determine string for the conversion of UTF-8 which is CP1208 */
23532  if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
23533    return out; /* if conversion fails, return the empty string */
23534
23535  /* conversion for current codepage which can be used for paths */
23536  UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
23537
23538  return out;
23539}
23540
23541/*
23542** Helper function to convert filenames from local codepage to UTF-8.
23543** The two-step process: first convert the incoming codepage-specific
23544** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
23545** The returned char pointer has to be freed.
23546**
23547** This function is non-static to be able to use this in shell.c and
23548** similar applications that take command line arguments.
23549*/
23550char *convertCpPathToUtf8( const char *in ){
23551  UniChar tempPath[CCHMAXPATH];
23552  char *out = (char *)calloc( CCHMAXPATH, 1 );
23553
23554  if( !out )
23555    return NULL;
23556
23557  if( !ucUtf8 || !uclCp )
23558    initUconvObjects();
23559
23560  /* conversion for current codepage which can be used for paths */
23561  if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
23562    return out; /* if conversion fails, return the empty string */
23563
23564  /* determine string for the conversion of UTF-8 which is CP1208 */
23565  UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
23566
23567  return out;
23568}
23569
23570
23571#ifndef SQLITE_OMIT_WAL
23572
23573/*
23574** Use main database file for interprocess locking. If un-defined
23575** a separate file is created for this purpose. The file will be
23576** used only to set file locks. There will be no data written to it.
23577*/
23578#define SQLITE_OS2_NO_WAL_LOCK_FILE
23579
23580#if 0
23581static void _ERR_TRACE( const char *fmt, ... ) {
23582  va_list  ap;
23583  va_start(ap, fmt);
23584  vfprintf(stderr, fmt, ap);
23585  fflush(stderr);
23586}
23587#define ERR_TRACE(rc, msg)        \
23588        if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
23589#else
23590#define ERR_TRACE(rc, msg)
23591#endif
23592
23593/*
23594** Helper functions to obtain and relinquish the global mutex. The
23595** global mutex is used to protect os2ShmNodeList.
23596**
23597** Function os2ShmMutexHeld() is used to assert() that the global mutex
23598** is held when required. This function is only used as part of assert()
23599** statements. e.g.
23600**
23601**   os2ShmEnterMutex()
23602**     assert( os2ShmMutexHeld() );
23603**   os2ShmLeaveMutex()
23604*/
23605static void os2ShmEnterMutex(void){
23606  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23607}
23608static void os2ShmLeaveMutex(void){
23609  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23610}
23611#ifdef SQLITE_DEBUG
23612static int os2ShmMutexHeld(void) {
23613  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23614}
23615int GetCurrentProcessId(void) {
23616  PPIB pib;
23617  DosGetInfoBlocks(NULL, &pib);
23618  return (int)pib->pib_ulpid;
23619}
23620#endif
23621
23622/*
23623** Object used to represent a the shared memory area for a single log file.
23624** When multiple threads all reference the same log-summary, each thread has
23625** its own os2File object, but they all point to a single instance of this
23626** object.  In other words, each log-summary is opened only once per process.
23627**
23628** os2ShmMutexHeld() must be true when creating or destroying
23629** this object or while reading or writing the following fields:
23630**
23631**      nRef
23632**      pNext
23633**
23634** The following fields are read-only after the object is created:
23635**
23636**      szRegion
23637**      hLockFile
23638**      shmBaseName
23639**
23640** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
23641** os2ShmMutexHeld() is true when reading or writing any other field
23642** in this structure.
23643**
23644*/
23645struct os2ShmNode {
23646  sqlite3_mutex *mutex;      /* Mutex to access this object */
23647  os2ShmNode *pNext;         /* Next in list of all os2ShmNode objects */
23648
23649  int szRegion;              /* Size of shared-memory regions */
23650
23651  int nRegion;               /* Size of array apRegion */
23652  void **apRegion;           /* Array of pointers to shared-memory regions */
23653
23654  int nRef;                  /* Number of os2ShmLink objects pointing to this */
23655  os2ShmLink *pFirst;        /* First os2ShmLink object pointing to this */
23656
23657  HFILE hLockFile;           /* File used for inter-process memory locking */
23658  char shmBaseName[1];       /* Name of the memory object !!! must last !!! */
23659};
23660
23661
23662/*
23663** Structure used internally by this VFS to record the state of an
23664** open shared memory connection.
23665**
23666** The following fields are initialized when this object is created and
23667** are read-only thereafter:
23668**
23669**    os2Shm.pShmNode
23670**    os2Shm.id
23671**
23672** All other fields are read/write.  The os2Shm.pShmNode->mutex must be held
23673** while accessing any read/write fields.
23674*/
23675struct os2ShmLink {
23676  os2ShmNode *pShmNode;      /* The underlying os2ShmNode object */
23677  os2ShmLink *pNext;         /* Next os2Shm with the same os2ShmNode */
23678  u32 sharedMask;            /* Mask of shared locks held */
23679  u32 exclMask;              /* Mask of exclusive locks held */
23680#ifdef SQLITE_DEBUG
23681  u8 id;                     /* Id of this connection with its os2ShmNode */
23682#endif
23683};
23684
23685
23686/*
23687** A global list of all os2ShmNode objects.
23688**
23689** The os2ShmMutexHeld() must be true while reading or writing this list.
23690*/
23691static os2ShmNode *os2ShmNodeList = NULL;
23692
23693/*
23694** Constants used for locking
23695*/
23696#ifdef  SQLITE_OS2_NO_WAL_LOCK_FILE
23697#define OS2_SHM_BASE   (PENDING_BYTE + 0x10000)         /* first lock byte */
23698#else
23699#define OS2_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
23700#endif
23701
23702#define OS2_SHM_DMS    (OS2_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
23703
23704/*
23705** Apply advisory locks for all n bytes beginning at ofst.
23706*/
23707#define _SHM_UNLCK  1   /* no lock */
23708#define _SHM_RDLCK  2   /* shared lock, no wait */
23709#define _SHM_WRLCK  3   /* exlusive lock, no wait */
23710#define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
23711static int os2ShmSystemLock(
23712  os2ShmNode *pNode,    /* Apply locks to this open shared-memory segment */
23713  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
23714  int ofst,             /* Offset to first byte to be locked/unlocked */
23715  int nByte             /* Number of bytes to lock or unlock */
23716){
23717  APIRET rc;
23718  FILELOCK area;
23719  ULONG mode, timeout;
23720
23721  /* Access to the os2ShmNode object is serialized by the caller */
23722  assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
23723
23724  mode = 1;     /* shared lock */
23725  timeout = 0;  /* no wait */
23726  area.lOffset = ofst;
23727  area.lRange = nByte;
23728
23729  switch( lockType ) {
23730    case _SHM_WRLCK_WAIT:
23731      timeout = (ULONG)-1;      /* wait forever */
23732    case _SHM_WRLCK:
23733      mode = 0;                 /* exclusive lock */
23734    case _SHM_RDLCK:
23735      rc = DosSetFileLocks(pNode->hLockFile,
23736                           NULL, &area, timeout, mode);
23737      break;
23738    /* case _SHM_UNLCK: */
23739    default:
23740      rc = DosSetFileLocks(pNode->hLockFile,
23741                           &area, NULL, 0, 0);
23742      break;
23743  }
23744
23745  OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
23746           pNode->hLockFile,
23747           rc==SQLITE_OK ? "ok" : "failed",
23748           lockType==_SHM_UNLCK ? "Unlock" : "Lock",
23749           rc));
23750
23751  ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
23752
23753  return ( rc == 0 ) ?  SQLITE_OK : SQLITE_BUSY;
23754}
23755
23756/*
23757** Find an os2ShmNode in global list or allocate a new one, if not found.
23758**
23759** This is not a VFS shared-memory method; it is a utility function called
23760** by VFS shared-memory methods.
23761*/
23762static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
23763  os2ShmLink *pLink;
23764  os2ShmNode *pNode;
23765  int cbShmName, rc = SQLITE_OK;
23766  char shmName[CCHMAXPATH + 30];
23767#ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23768  ULONG action;
23769#endif
23770
23771  /* We need some additional space at the end to append the region number */
23772  cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
23773  if( cbShmName >= CCHMAXPATH-8 )
23774    return SQLITE_IOERR_SHMOPEN;
23775
23776  /* Replace colon in file name to form a valid shared memory name */
23777  shmName[10+1] = '!';
23778
23779  /* Allocate link object (we free it later in case of failure) */
23780  pLink = sqlite3_malloc( sizeof(*pLink) );
23781  if( !pLink )
23782    return SQLITE_NOMEM;
23783
23784  /* Access node list */
23785  os2ShmEnterMutex();
23786
23787  /* Find node by it's shared memory base name */
23788  for( pNode = os2ShmNodeList;
23789       pNode && stricmp(shmName, pNode->shmBaseName) != 0;
23790       pNode = pNode->pNext )   ;
23791
23792  /* Not found: allocate a new node */
23793  if( !pNode ) {
23794    pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
23795    if( pNode ) {
23796      memset(pNode, 0, sizeof(*pNode) );
23797      pNode->szRegion = szRegion;
23798      pNode->hLockFile = (HFILE)-1;
23799      strcpy(pNode->shmBaseName, shmName);
23800
23801#ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
23802      if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
23803#else
23804      sprintf(shmName, "%s-lck", fd->zFullPathCp);
23805      if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL,
23806                  OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
23807                  OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE |
23808                  OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
23809                  NULL) != 0 ) {
23810#endif
23811        sqlite3_free(pNode);
23812        rc = SQLITE_IOERR;
23813      } else {
23814        pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
23815        if( !pNode->mutex ) {
23816          sqlite3_free(pNode);
23817          rc = SQLITE_NOMEM;
23818        }
23819      }
23820    } else {
23821      rc = SQLITE_NOMEM;
23822    }
23823
23824    if( rc == SQLITE_OK ) {
23825      pNode->pNext = os2ShmNodeList;
23826      os2ShmNodeList = pNode;
23827    } else {
23828      pNode = NULL;
23829    }
23830  } else if( pNode->szRegion != szRegion ) {
23831    rc = SQLITE_IOERR_SHMSIZE;
23832    pNode = NULL;
23833  }
23834
23835  if( pNode ) {
23836    sqlite3_mutex_enter(pNode->mutex);
23837
23838    memset(pLink, 0, sizeof(*pLink));
23839
23840    pLink->pShmNode = pNode;
23841    pLink->pNext = pNode->pFirst;
23842    pNode->pFirst = pLink;
23843    pNode->nRef++;
23844
23845    fd->pShmLink = pLink;
23846
23847    sqlite3_mutex_leave(pNode->mutex);
23848
23849  } else {
23850    /* Error occured. Free our link object. */
23851    sqlite3_free(pLink);
23852  }
23853
23854  os2ShmLeaveMutex();
23855
23856  ERR_TRACE(rc, ("os2OpenSharedMemory: %d  %s\n", rc, fd->zFullPathCp))
23857
23858  return rc;
23859}
23860
23861/*
23862** Purge the os2ShmNodeList list of all entries with nRef==0.
23863**
23864** This is not a VFS shared-memory method; it is a utility function called
23865** by VFS shared-memory methods.
23866*/
23867static void os2PurgeShmNodes( int deleteFlag ) {
23868  os2ShmNode *pNode;
23869  os2ShmNode **ppNode;
23870
23871  os2ShmEnterMutex();
23872
23873  ppNode = &os2ShmNodeList;
23874
23875  while( *ppNode ) {
23876    pNode = *ppNode;
23877
23878    if( pNode->nRef == 0 ) {
23879      *ppNode = pNode->pNext;
23880
23881      if( pNode->apRegion ) {
23882        /* Prevent other processes from resizing the shared memory */
23883        os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23884
23885        while( pNode->nRegion-- ) {
23886#ifdef SQLITE_DEBUG
23887          int rc =
23888#endif
23889          DosFreeMem(pNode->apRegion[pNode->nRegion]);
23890
23891          OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
23892                  (int)GetCurrentProcessId(), pNode->nRegion,
23893                  rc == 0 ? "ok" : "failed"));
23894        }
23895
23896        /* Allow other processes to resize the shared memory */
23897        os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23898
23899        sqlite3_free(pNode->apRegion);
23900      }
23901
23902      DosClose(pNode->hLockFile);
23903
23904#ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23905      if( deleteFlag ) {
23906         char fileName[CCHMAXPATH];
23907         /* Skip "\\SHAREMEM\\" */
23908         sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
23909         /* restore colon */
23910         fileName[1] = ':';
23911
23912         DosForceDelete(fileName);
23913      }
23914#endif
23915
23916      sqlite3_mutex_free(pNode->mutex);
23917
23918      sqlite3_free(pNode);
23919
23920    } else {
23921      ppNode = &pNode->pNext;
23922    }
23923  }
23924
23925  os2ShmLeaveMutex();
23926}
23927
23928/*
23929** This function is called to obtain a pointer to region iRegion of the
23930** shared-memory associated with the database file id. Shared-memory regions
23931** are numbered starting from zero. Each shared-memory region is szRegion
23932** bytes in size.
23933**
23934** If an error occurs, an error code is returned and *pp is set to NULL.
23935**
23936** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
23937** region has not been allocated (by any client, including one running in a
23938** separate process), then *pp is set to NULL and SQLITE_OK returned. If
23939** bExtend is non-zero and the requested shared-memory region has not yet
23940** been allocated, it is allocated by this function.
23941**
23942** If the shared-memory region has already been allocated or is allocated by
23943** this call as described above, then it is mapped into this processes
23944** address space (if it is not already), *pp is set to point to the mapped
23945** memory and SQLITE_OK returned.
23946*/
23947static int os2ShmMap(
23948  sqlite3_file *id,               /* Handle open on database file */
23949  int iRegion,                    /* Region to retrieve */
23950  int szRegion,                   /* Size of regions */
23951  int bExtend,                    /* True to extend block if necessary */
23952  void volatile **pp              /* OUT: Mapped memory */
23953){
23954  PVOID pvTemp;
23955  void **apRegion;
23956  os2ShmNode *pNode;
23957  int n, rc = SQLITE_OK;
23958  char shmName[CCHMAXPATH];
23959  os2File *pFile = (os2File*)id;
23960
23961  *pp = NULL;
23962
23963  if( !pFile->pShmLink )
23964    rc = os2OpenSharedMemory( pFile, szRegion );
23965
23966  if( rc == SQLITE_OK ) {
23967    pNode = pFile->pShmLink->pShmNode ;
23968
23969    sqlite3_mutex_enter(pNode->mutex);
23970
23971    assert( szRegion==pNode->szRegion );
23972
23973    /* Unmapped region ? */
23974    if( iRegion >= pNode->nRegion ) {
23975      /* Prevent other processes from resizing the shared memory */
23976      os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23977
23978      apRegion = sqlite3_realloc(
23979        pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
23980
23981      if( apRegion ) {
23982        pNode->apRegion = apRegion;
23983
23984        while( pNode->nRegion <= iRegion ) {
23985          sprintf(shmName, "%s-%u",
23986                  pNode->shmBaseName, pNode->nRegion);
23987
23988          if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName,
23989                PAG_READ | PAG_WRITE) != NO_ERROR ) {
23990            if( !bExtend )
23991              break;
23992
23993            if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23994                  PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR &&
23995                DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23996                  PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) {
23997              rc = SQLITE_NOMEM;
23998              break;
23999            }
24000          }
24001
24002          apRegion[pNode->nRegion++] = pvTemp;
24003        }
24004
24005        /* zero out remaining entries */
24006        for( n = pNode->nRegion; n <= iRegion; n++ )
24007          pNode->apRegion[n] = NULL;
24008
24009        /* Return this region (maybe zero) */
24010        *pp = pNode->apRegion[iRegion];
24011      } else {
24012        rc = SQLITE_NOMEM;
24013      }
24014
24015      /* Allow other processes to resize the shared memory */
24016      os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
24017
24018    } else {
24019      /* Region has been mapped previously */
24020      *pp = pNode->apRegion[iRegion];
24021    }
24022
24023    sqlite3_mutex_leave(pNode->mutex);
24024  }
24025
24026  ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n",
24027                 pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
24028
24029  return rc;
24030}
24031
24032/*
24033** Close a connection to shared-memory.  Delete the underlying
24034** storage if deleteFlag is true.
24035**
24036** If there is no shared memory associated with the connection then this
24037** routine is a harmless no-op.
24038*/
24039static int os2ShmUnmap(
24040  sqlite3_file *id,               /* The underlying database file */
24041  int deleteFlag                  /* Delete shared-memory if true */
24042){
24043  os2File *pFile = (os2File*)id;
24044  os2ShmLink *pLink = pFile->pShmLink;
24045
24046  if( pLink ) {
24047    int nRef = -1;
24048    os2ShmLink **ppLink;
24049    os2ShmNode *pNode = pLink->pShmNode;
24050
24051    sqlite3_mutex_enter(pNode->mutex);
24052
24053    for( ppLink = &pNode->pFirst;
24054         *ppLink && *ppLink != pLink;
24055         ppLink = &(*ppLink)->pNext )   ;
24056
24057    assert(*ppLink);
24058
24059    if( *ppLink ) {
24060      *ppLink = pLink->pNext;
24061      nRef = --pNode->nRef;
24062    } else {
24063      ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n",
24064                    pNode->shmBaseName))
24065    }
24066
24067    pFile->pShmLink = NULL;
24068    sqlite3_free(pLink);
24069
24070    sqlite3_mutex_leave(pNode->mutex);
24071
24072    if( nRef == 0 )
24073      os2PurgeShmNodes( deleteFlag );
24074  }
24075
24076  return SQLITE_OK;
24077}
24078
24079/*
24080** Change the lock state for a shared-memory segment.
24081**
24082** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
24083** different here than in posix.  In xShmLock(), one can go from unlocked
24084** to shared and back or from unlocked to exclusive and back.  But one may
24085** not go from shared to exclusive or from exclusive to shared.
24086*/
24087static int os2ShmLock(
24088  sqlite3_file *id,          /* Database file holding the shared memory */
24089  int ofst,                  /* First lock to acquire or release */
24090  int n,                     /* Number of locks to acquire or release */
24091  int flags                  /* What to do with the lock */
24092){
24093  u32 mask;                             /* Mask of locks to take or release */
24094  int rc = SQLITE_OK;                   /* Result code */
24095  os2File *pFile = (os2File*)id;
24096  os2ShmLink *p = pFile->pShmLink;      /* The shared memory being locked */
24097  os2ShmLink *pX;                       /* For looping over all siblings */
24098  os2ShmNode *pShmNode = p->pShmNode;   /* Our node */
24099
24100  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
24101  assert( n>=1 );
24102  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
24103       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
24104       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
24105       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
24106  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
24107
24108  mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
24109  assert( n>1 || mask==(1<<ofst) );
24110
24111
24112  sqlite3_mutex_enter(pShmNode->mutex);
24113
24114  if( flags & SQLITE_SHM_UNLOCK ){
24115    u32 allMask = 0; /* Mask of locks held by siblings */
24116
24117    /* See if any siblings hold this same lock */
24118    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
24119      if( pX==p ) continue;
24120      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
24121      allMask |= pX->sharedMask;
24122    }
24123
24124    /* Unlock the system-level locks */
24125    if( (mask & allMask)==0 ){
24126      rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
24127    }else{
24128      rc = SQLITE_OK;
24129    }
24130
24131    /* Undo the local locks */
24132    if( rc==SQLITE_OK ){
24133      p->exclMask &= ~mask;
24134      p->sharedMask &= ~mask;
24135    }
24136  }else if( flags & SQLITE_SHM_SHARED ){
24137    u32 allShared = 0;  /* Union of locks held by connections other than "p" */
24138
24139    /* Find out which shared locks are already held by sibling connections.
24140    ** If any sibling already holds an exclusive lock, go ahead and return
24141    ** SQLITE_BUSY.
24142    */
24143    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
24144      if( (pX->exclMask & mask)!=0 ){
24145        rc = SQLITE_BUSY;
24146        break;
24147      }
24148      allShared |= pX->sharedMask;
24149    }
24150
24151    /* Get shared locks at the system level, if necessary */
24152    if( rc==SQLITE_OK ){
24153      if( (allShared & mask)==0 ){
24154        rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
24155      }else{
24156        rc = SQLITE_OK;
24157      }
24158    }
24159
24160    /* Get the local shared locks */
24161    if( rc==SQLITE_OK ){
24162      p->sharedMask |= mask;
24163    }
24164  }else{
24165    /* Make sure no sibling connections hold locks that will block this
24166    ** lock.  If any do, return SQLITE_BUSY right away.
24167    */
24168    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
24169      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
24170        rc = SQLITE_BUSY;
24171        break;
24172      }
24173    }
24174
24175    /* Get the exclusive locks at the system level.  Then if successful
24176    ** also mark the local connection as being locked.
24177    */
24178    if( rc==SQLITE_OK ){
24179      rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
24180      if( rc==SQLITE_OK ){
24181        assert( (p->sharedMask & mask)==0 );
24182        p->exclMask |= mask;
24183      }
24184    }
24185  }
24186
24187  sqlite3_mutex_leave(pShmNode->mutex);
24188
24189  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
24190           p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
24191           rc ? "failed" : "ok"));
24192
24193  ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n",
24194                 ofst, n, flags, rc))
24195
24196  return rc;
24197}
24198
24199/*
24200** Implement a memory barrier or memory fence on shared memory.
24201**
24202** All loads and stores begun before the barrier must complete before
24203** any load or store begun after the barrier.
24204*/
24205static void os2ShmBarrier(
24206  sqlite3_file *id                /* Database file holding the shared memory */
24207){
24208  UNUSED_PARAMETER(id);
24209  os2ShmEnterMutex();
24210  os2ShmLeaveMutex();
24211}
24212
24213#else
24214# define os2ShmMap     0
24215# define os2ShmLock    0
24216# define os2ShmBarrier 0
24217# define os2ShmUnmap   0
24218#endif /* #ifndef SQLITE_OMIT_WAL */
24219
24220
24221/*
24222** This vector defines all the methods that can operate on an
24223** sqlite3_file for os2.
24224*/
24225static const sqlite3_io_methods os2IoMethod = {
24226  2,                              /* iVersion */
24227  os2Close,                       /* xClose */
24228  os2Read,                        /* xRead */
24229  os2Write,                       /* xWrite */
24230  os2Truncate,                    /* xTruncate */
24231  os2Sync,                        /* xSync */
24232  os2FileSize,                    /* xFileSize */
24233  os2Lock,                        /* xLock */
24234  os2Unlock,                      /* xUnlock */
24235  os2CheckReservedLock,           /* xCheckReservedLock */
24236  os2FileControl,                 /* xFileControl */
24237  os2SectorSize,                  /* xSectorSize */
24238  os2DeviceCharacteristics,       /* xDeviceCharacteristics */
24239  os2ShmMap,                      /* xShmMap */
24240  os2ShmLock,                     /* xShmLock */
24241  os2ShmBarrier,                  /* xShmBarrier */
24242  os2ShmUnmap                     /* xShmUnmap */
24243};
24244
24245
24246/***************************************************************************
24247** Here ends the I/O methods that form the sqlite3_io_methods object.
24248**
24249** The next block of code implements the VFS methods.
24250****************************************************************************/
24251
24252/*
24253** Create a temporary file name in zBuf.  zBuf must be big enough to
24254** hold at pVfs->mxPathname characters.
24255*/
24256static int getTempname(int nBuf, char *zBuf ){
24257  static const char zChars[] =
24258    "abcdefghijklmnopqrstuvwxyz"
24259    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
24260    "0123456789";
24261  int i, j;
24262  PSZ zTempPathCp;
24263  char zTempPath[CCHMAXPATH];
24264  ULONG ulDriveNum, ulDriveMap;
24265
24266  /* It's odd to simulate an io-error here, but really this is just
24267  ** using the io-error infrastructure to test that SQLite handles this
24268  ** function failing.
24269  */
24270  SimulateIOError( return SQLITE_IOERR );
24271
24272  if( sqlite3_temp_directory ) {
24273    sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
24274  } else if( DosScanEnv( (PSZ)"TEMP",   &zTempPathCp ) == NO_ERROR ||
24275             DosScanEnv( (PSZ)"TMP",    &zTempPathCp ) == NO_ERROR ||
24276             DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
24277    char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
24278    sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
24279    free( zTempPathUTF );
24280  } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
24281    zTempPath[0] = (char)('A' + ulDriveNum - 1);
24282    zTempPath[1] = ':';
24283    zTempPath[2] = '\0';
24284  } else {
24285    zTempPath[0] = '\0';
24286  }
24287
24288  /* Strip off a trailing slashes or backslashes, otherwise we would get *
24289   * multiple (back)slashes which causes DosOpen() to fail.              *
24290   * Trailing spaces are not allowed, either.                            */
24291  j = sqlite3Strlen30(zTempPath);
24292  while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ||
24293                    zTempPath[j-1] == ' ' ) ){
24294    j--;
24295  }
24296  zTempPath[j] = '\0';
24297
24298  /* We use 20 bytes to randomize the name */
24299  sqlite3_snprintf(nBuf-22, zBuf,
24300                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
24301  j = sqlite3Strlen30(zBuf);
24302  sqlite3_randomness( 20, &zBuf[j] );
24303  for( i = 0; i < 20; i++, j++ ){
24304    zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
24305  }
24306  zBuf[j] = 0;
24307
24308  OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
24309  return SQLITE_OK;
24310}
24311
24312
24313/*
24314** Turn a relative pathname into a full pathname.  Write the full
24315** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
24316** bytes in size.
24317*/
24318static int os2FullPathname(
24319  sqlite3_vfs *pVfs,          /* Pointer to vfs object */
24320  const char *zRelative,      /* Possibly relative input path */
24321  int nFull,                  /* Size of output buffer in bytes */
24322  char *zFull                 /* Output buffer */
24323){
24324  char *zRelativeCp = convertUtf8PathToCp( zRelative );
24325  char zFullCp[CCHMAXPATH] = "\0";
24326  char *zFullUTF;
24327  APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME,
24328                                zFullCp, CCHMAXPATH );
24329  free( zRelativeCp );
24330  zFullUTF = convertCpPathToUtf8( zFullCp );
24331  sqlite3_snprintf( nFull, zFull, zFullUTF );
24332  free( zFullUTF );
24333  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
24334}
24335
24336
24337/*
24338** Open a file.
24339*/
24340static int os2Open(
24341  sqlite3_vfs *pVfs,            /* Not used */
24342  const char *zName,            /* Name of the file (UTF-8) */
24343  sqlite3_file *id,             /* Write the SQLite file handle here */
24344  int flags,                    /* Open mode flags */
24345  int *pOutFlags                /* Status return flags */
24346){
24347  HFILE h;
24348  ULONG ulOpenFlags = 0;
24349  ULONG ulOpenMode = 0;
24350  ULONG ulAction = 0;
24351  ULONG rc;
24352  os2File *pFile = (os2File*)id;
24353  const char *zUtf8Name = zName;
24354  char *zNameCp;
24355  char  zTmpname[CCHMAXPATH];
24356
24357  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
24358  int isCreate     = (flags & SQLITE_OPEN_CREATE);
24359  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
24360#ifndef NDEBUG
24361  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
24362  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
24363  int eType        = (flags & 0xFFFFFF00);
24364  int isOpenJournal = (isCreate && (
24365        eType==SQLITE_OPEN_MASTER_JOURNAL
24366     || eType==SQLITE_OPEN_MAIN_JOURNAL
24367     || eType==SQLITE_OPEN_WAL
24368  ));
24369#endif
24370
24371  UNUSED_PARAMETER(pVfs);
24372  assert( id!=0 );
24373
24374  /* Check the following statements are true:
24375  **
24376  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
24377  **   (b) if CREATE is set, then READWRITE must also be set, and
24378  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
24379  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
24380  */
24381  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
24382  assert(isCreate==0 || isReadWrite);
24383  assert(isExclusive==0 || isCreate);
24384  assert(isDelete==0 || isCreate);
24385
24386  /* The main DB, main journal, WAL file and master journal are never
24387  ** automatically deleted. Nor are they ever temporary files.  */
24388  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
24389  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
24390  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
24391  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
24392
24393  /* Assert that the upper layer has set one of the "file-type" flags. */
24394  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
24395       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
24396       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
24397       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
24398  );
24399
24400  memset( pFile, 0, sizeof(*pFile) );
24401  pFile->h = (HFILE)-1;
24402
24403  /* If the second argument to this function is NULL, generate a
24404  ** temporary file name to use
24405  */
24406  if( !zUtf8Name ){
24407    assert(isDelete && !isOpenJournal);
24408    rc = getTempname(CCHMAXPATH, zTmpname);
24409    if( rc!=SQLITE_OK ){
24410      return rc;
24411    }
24412    zUtf8Name = zTmpname;
24413  }
24414
24415  if( isReadWrite ){
24416    ulOpenMode |= OPEN_ACCESS_READWRITE;
24417  }else{
24418    ulOpenMode |= OPEN_ACCESS_READONLY;
24419  }
24420
24421  /* Open in random access mode for possibly better speed.  Allow full
24422  ** sharing because file locks will provide exclusive access when needed.
24423  ** The handle should not be inherited by child processes and we don't
24424  ** want popups from the critical error handler.
24425  */
24426  ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE |
24427                OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
24428
24429  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
24430  ** created. SQLite doesn't use it to indicate "exclusive access"
24431  ** as it is usually understood.
24432  */
24433  if( isExclusive ){
24434    /* Creates a new file, only if it does not already exist. */
24435    /* If the file exists, it fails. */
24436    ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
24437  }else if( isCreate ){
24438    /* Open existing file, or create if it doesn't exist */
24439    ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
24440  }else{
24441    /* Opens a file, only if it exists. */
24442    ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
24443  }
24444
24445  zNameCp = convertUtf8PathToCp( zUtf8Name );
24446  rc = DosOpen( (PSZ)zNameCp,
24447                &h,
24448                &ulAction,
24449                0L,
24450                FILE_NORMAL,
24451                ulOpenFlags,
24452                ulOpenMode,
24453                (PEAOP2)NULL );
24454  free( zNameCp );
24455
24456  if( rc != NO_ERROR ){
24457    OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
24458              rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
24459
24460    if( isReadWrite ){
24461      return os2Open( pVfs, zName, id,
24462                      ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
24463                      pOutFlags );
24464    }else{
24465      return SQLITE_CANTOPEN;
24466    }
24467  }
24468
24469  if( pOutFlags ){
24470    *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
24471  }
24472
24473  os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
24474  pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
24475  pFile->pMethod = &os2IoMethod;
24476  pFile->flags = flags;
24477  pFile->h = h;
24478
24479  OpenCounter(+1);
24480  OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
24481  return SQLITE_OK;
24482}
24483
24484/*
24485** Delete the named file.
24486*/
24487static int os2Delete(
24488  sqlite3_vfs *pVfs,                     /* Not used on os2 */
24489  const char *zFilename,                 /* Name of file to delete */
24490  int syncDir                            /* Not used on os2 */
24491){
24492  APIRET rc;
24493  char *zFilenameCp;
24494  SimulateIOError( return SQLITE_IOERR_DELETE );
24495  zFilenameCp = convertUtf8PathToCp( zFilename );
24496  rc = DosDelete( (PSZ)zFilenameCp );
24497  free( zFilenameCp );
24498  OSTRACE(( "DELETE \"%s\"\n", zFilename ));
24499  return (rc == NO_ERROR ||
24500          rc == ERROR_FILE_NOT_FOUND ||
24501          rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
24502}
24503
24504/*
24505** Check the existance and status of a file.
24506*/
24507static int os2Access(
24508  sqlite3_vfs *pVfs,        /* Not used on os2 */
24509  const char *zFilename,    /* Name of file to check */
24510  int flags,                /* Type of test to make on this file */
24511  int *pOut                 /* Write results here */
24512){
24513  APIRET rc;
24514  FILESTATUS3 fsts3ConfigInfo;
24515  char *zFilenameCp;
24516
24517  UNUSED_PARAMETER(pVfs);
24518  SimulateIOError( return SQLITE_IOERR_ACCESS; );
24519
24520  zFilenameCp = convertUtf8PathToCp( zFilename );
24521  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
24522                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
24523  free( zFilenameCp );
24524  OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
24525            fsts3ConfigInfo.attrFile, flags, rc ));
24526
24527  switch( flags ){
24528    case SQLITE_ACCESS_EXISTS:
24529      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
24530      ** as if it does not exist.
24531      */
24532      if( fsts3ConfigInfo.cbFile == 0 )
24533        rc = ERROR_FILE_NOT_FOUND;
24534      break;
24535    case SQLITE_ACCESS_READ:
24536      break;
24537    case SQLITE_ACCESS_READWRITE:
24538      if( fsts3ConfigInfo.attrFile & FILE_READONLY )
24539        rc = ERROR_ACCESS_DENIED;
24540      break;
24541    default:
24542      rc = ERROR_FILE_NOT_FOUND;
24543      assert( !"Invalid flags argument" );
24544  }
24545
24546  *pOut = (rc == NO_ERROR);
24547  OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
24548
24549  return SQLITE_OK;
24550}
24551
24552
24553#ifndef SQLITE_OMIT_LOAD_EXTENSION
24554/*
24555** Interfaces for opening a shared library, finding entry points
24556** within the shared library, and closing the shared library.
24557*/
24558/*
24559** Interfaces for opening a shared library, finding entry points
24560** within the shared library, and closing the shared library.
24561*/
24562static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
24563  HMODULE hmod;
24564  APIRET rc;
24565  char *zFilenameCp = convertUtf8PathToCp(zFilename);
24566  rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
24567  free(zFilenameCp);
24568  return rc != NO_ERROR ? 0 : (void*)hmod;
24569}
24570/*
24571** A no-op since the error code is returned on the DosLoadModule call.
24572** os2Dlopen returns zero if DosLoadModule is not successful.
24573*/
24574static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
24575/* no-op */
24576}
24577static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
24578  PFN pfn;
24579  APIRET rc;
24580  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
24581  if( rc != NO_ERROR ){
24582    /* if the symbol itself was not found, search again for the same
24583     * symbol with an extra underscore, that might be needed depending
24584     * on the calling convention */
24585    char _zSymbol[256] = "_";
24586    strncat(_zSymbol, zSymbol, 254);
24587    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
24588  }
24589  return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
24590}
24591static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
24592  DosFreeModule((HMODULE)pHandle);
24593}
24594#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
24595  #define os2DlOpen 0
24596  #define os2DlError 0
24597  #define os2DlSym 0
24598  #define os2DlClose 0
24599#endif
24600
24601
24602/*
24603** Write up to nBuf bytes of randomness into zBuf.
24604*/
24605static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
24606  int n = 0;
24607#if defined(SQLITE_TEST)
24608  n = nBuf;
24609  memset(zBuf, 0, nBuf);
24610#else
24611  int i;
24612  PPIB ppib;
24613  PTIB ptib;
24614  DATETIME dt;
24615  static unsigned c = 0;
24616  /* Ordered by variation probability */
24617  static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
24618                            QSV_MAXPRMEM, QSV_MAXSHMEM,
24619                            QSV_TOTAVAILMEM, QSV_TOTRESMEM };
24620
24621  /* 8 bytes; timezone and weekday don't increase the randomness much */
24622  if( (int)sizeof(dt)-3 <= nBuf - n ){
24623    c += 0x0100;
24624    DosGetDateTime(&dt);
24625    dt.year = (USHORT)((dt.year - 1900) | c);
24626    memcpy(&zBuf[n], &dt, sizeof(dt)-3);
24627    n += sizeof(dt)-3;
24628  }
24629
24630  /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
24631  if( (int)sizeof(ULONG) <= nBuf - n ){
24632    DosGetInfoBlocks(&ptib, &ppib);
24633    *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
24634                                 ptib->tib_ptib2->tib2_ultid);
24635    n += sizeof(ULONG);
24636  }
24637
24638  /* Up to 6 * 4 bytes; variables depend on the system state */
24639  for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
24640    DosQuerySysInfo(svIdx[i], svIdx[i],
24641                    (PULONG)&zBuf[n], sizeof(ULONG));
24642    n += sizeof(ULONG);
24643  }
24644#endif
24645
24646  return n;
24647}
24648
24649/*
24650** Sleep for a little while.  Return the amount of time slept.
24651** The argument is the number of microseconds we want to sleep.
24652** The return value is the number of microseconds of sleep actually
24653** requested from the underlying operating system, a number which
24654** might be greater than or equal to the argument, but not less
24655** than the argument.
24656*/
24657static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
24658  DosSleep( (microsec/1000) );
24659  return microsec;
24660}
24661
24662/*
24663** The following variable, if set to a non-zero value, becomes the result
24664** returned from sqlite3OsCurrentTime().  This is used for testing.
24665*/
24666#ifdef SQLITE_TEST
24667SQLITE_API int sqlite3_current_time = 0;
24668#endif
24669
24670/*
24671** Find the current time (in Universal Coordinated Time).  Write into *piNow
24672** the current time and date as a Julian Day number times 86_400_000.  In
24673** other words, write into *piNow the number of milliseconds since the Julian
24674** epoch of noon in Greenwich on November 24, 4714 B.C according to the
24675** proleptic Gregorian calendar.
24676**
24677** On success, return 0.  Return 1 if the time and date cannot be found.
24678*/
24679static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
24680#ifdef SQLITE_TEST
24681  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
24682#endif
24683  int year, month, datepart, timepart;
24684
24685  DATETIME dt;
24686  DosGetDateTime( &dt );
24687
24688  year = dt.year;
24689  month = dt.month;
24690
24691  /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
24692  ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
24693  ** Calculate the Julian days
24694  */
24695  datepart = (int)dt.day - 32076 +
24696    1461*(year + 4800 + (month - 14)/12)/4 +
24697    367*(month - 2 - (month - 14)/12*12)/12 -
24698    3*((year + 4900 + (month - 14)/12)/100)/4;
24699
24700  /* Time in milliseconds, hours to noon added */
24701  timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
24702    ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
24703
24704  *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
24705
24706#ifdef SQLITE_TEST
24707  if( sqlite3_current_time ){
24708    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
24709  }
24710#endif
24711
24712  UNUSED_PARAMETER(pVfs);
24713  return 0;
24714}
24715
24716/*
24717** Find the current time (in Universal Coordinated Time).  Write the
24718** current time and date as a Julian Day number into *prNow and
24719** return 0.  Return 1 if the time and date cannot be found.
24720*/
24721static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
24722  int rc;
24723  sqlite3_int64 i;
24724  rc = os2CurrentTimeInt64(pVfs, &i);
24725  if( !rc ){
24726    *prNow = i/86400000.0;
24727  }
24728  return rc;
24729}
24730
24731/*
24732** The idea is that this function works like a combination of
24733** GetLastError() and FormatMessage() on windows (or errno and
24734** strerror_r() on unix). After an error is returned by an OS
24735** function, SQLite calls this function with zBuf pointing to
24736** a buffer of nBuf bytes. The OS layer should populate the
24737** buffer with a nul-terminated UTF-8 encoded error message
24738** describing the last IO error to have occurred within the calling
24739** thread.
24740**
24741** If the error message is too large for the supplied buffer,
24742** it should be truncated. The return value of xGetLastError
24743** is zero if the error message fits in the buffer, or non-zero
24744** otherwise (if the message was truncated). If non-zero is returned,
24745** then it is not necessary to include the nul-terminator character
24746** in the output buffer.
24747**
24748** Not supplying an error message will have no adverse effect
24749** on SQLite. It is fine to have an implementation that never
24750** returns an error message:
24751**
24752**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24753**     assert(zBuf[0]=='\0');
24754**     return 0;
24755**   }
24756**
24757** However if an error message is supplied, it will be incorporated
24758** by sqlite into the error message available to the user using
24759** sqlite3_errmsg(), possibly making IO errors easier to debug.
24760*/
24761static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24762  assert(zBuf[0]=='\0');
24763  return 0;
24764}
24765
24766/*
24767** Initialize and deinitialize the operating system interface.
24768*/
24769SQLITE_API int sqlite3_os_init(void){
24770  static sqlite3_vfs os2Vfs = {
24771    3,                 /* iVersion */
24772    sizeof(os2File),   /* szOsFile */
24773    CCHMAXPATH,        /* mxPathname */
24774    0,                 /* pNext */
24775    "os2",             /* zName */
24776    0,                 /* pAppData */
24777
24778    os2Open,           /* xOpen */
24779    os2Delete,         /* xDelete */
24780    os2Access,         /* xAccess */
24781    os2FullPathname,   /* xFullPathname */
24782    os2DlOpen,         /* xDlOpen */
24783    os2DlError,        /* xDlError */
24784    os2DlSym,          /* xDlSym */
24785    os2DlClose,        /* xDlClose */
24786    os2Randomness,     /* xRandomness */
24787    os2Sleep,          /* xSleep */
24788    os2CurrentTime,    /* xCurrentTime */
24789    os2GetLastError,   /* xGetLastError */
24790    os2CurrentTimeInt64, /* xCurrentTimeInt64 */
24791    0,                 /* xSetSystemCall */
24792    0,                 /* xGetSystemCall */
24793    0                  /* xNextSystemCall */
24794  };
24795  sqlite3_vfs_register(&os2Vfs, 1);
24796  initUconvObjects();
24797/*  sqlite3OSTrace = 1; */
24798  return SQLITE_OK;
24799}
24800SQLITE_API int sqlite3_os_end(void){
24801  freeUconvObjects();
24802  return SQLITE_OK;
24803}
24804
24805#endif /* SQLITE_OS_OS2 */
24806
24807/************** End of os_os2.c **********************************************/
24808/************** Begin file os_unix.c *****************************************/
24809/*
24810** 2004 May 22
24811**
24812** The author disclaims copyright to this source code.  In place of
24813** a legal notice, here is a blessing:
24814**
24815**    May you do good and not evil.
24816**    May you find forgiveness for yourself and forgive others.
24817**    May you share freely, never taking more than you give.
24818**
24819******************************************************************************
24820**
24821** This file contains the VFS implementation for unix-like operating systems
24822** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
24823**
24824** There are actually several different VFS implementations in this file.
24825** The differences are in the way that file locking is done.  The default
24826** implementation uses Posix Advisory Locks.  Alternative implementations
24827** use flock(), dot-files, various proprietary locking schemas, or simply
24828** skip locking all together.
24829**
24830** This source file is organized into divisions where the logic for various
24831** subfunctions is contained within the appropriate division.  PLEASE
24832** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
24833** in the correct division and should be clearly labeled.
24834**
24835** The layout of divisions is as follows:
24836**
24837**   *  General-purpose declarations and utility functions.
24838**   *  Unique file ID logic used by VxWorks.
24839**   *  Various locking primitive implementations (all except proxy locking):
24840**      + for Posix Advisory Locks
24841**      + for no-op locks
24842**      + for dot-file locks
24843**      + for flock() locking
24844**      + for named semaphore locks (VxWorks only)
24845**      + for AFP filesystem locks (MacOSX only)
24846**   *  sqlite3_file methods not associated with locking.
24847**   *  Definitions of sqlite3_io_methods objects for all locking
24848**      methods plus "finder" functions for each locking method.
24849**   *  sqlite3_vfs method implementations.
24850**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
24851**   *  Definitions of sqlite3_vfs objects for all locking methods
24852**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
24853*/
24854#if SQLITE_OS_UNIX              /* This file is used on unix only */
24855
24856/*
24857** There are various methods for file locking used for concurrency
24858** control:
24859**
24860**   1. POSIX locking (the default),
24861**   2. No locking,
24862**   3. Dot-file locking,
24863**   4. flock() locking,
24864**   5. AFP locking (OSX only),
24865**   6. Named POSIX semaphores (VXWorks only),
24866**   7. proxy locking. (OSX only)
24867**
24868** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24869** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24870** selection of the appropriate locking style based on the filesystem
24871** where the database is located.
24872*/
24873#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24874#  if defined(__APPLE__)
24875#    define SQLITE_ENABLE_LOCKING_STYLE 1
24876#  else
24877#    define SQLITE_ENABLE_LOCKING_STYLE 0
24878#  endif
24879#endif
24880
24881/*
24882** Define the OS_VXWORKS pre-processor macro to 1 if building on
24883** vxworks, or 0 otherwise.
24884*/
24885#ifndef OS_VXWORKS
24886#  if defined(__RTP__) || defined(_WRS_KERNEL)
24887#    define OS_VXWORKS 1
24888#  else
24889#    define OS_VXWORKS 0
24890#  endif
24891#endif
24892
24893/*
24894** These #defines should enable >2GB file support on Posix if the
24895** underlying operating system supports it.  If the OS lacks
24896** large file support, these should be no-ops.
24897**
24898** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
24899** on the compiler command line.  This is necessary if you are compiling
24900** on a recent machine (ex: RedHat 7.2) but you want your code to work
24901** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
24902** without this option, LFS is enable.  But LFS does not exist in the kernel
24903** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
24904** portability you should omit LFS.
24905**
24906** The previous paragraph was written in 2005.  (This paragraph is written
24907** on 2008-11-28.) These days, all Linux kernels support large files, so
24908** you should probably leave LFS enabled.  But some embedded platforms might
24909** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
24910*/
24911#ifndef SQLITE_DISABLE_LFS
24912# define _LARGE_FILE       1
24913# ifndef _FILE_OFFSET_BITS
24914#   define _FILE_OFFSET_BITS 64
24915# endif
24916# define _LARGEFILE_SOURCE 1
24917#endif
24918
24919/*
24920** standard include files.
24921*/
24922#include <sys/types.h>
24923#include <sys/stat.h>
24924#include <fcntl.h>
24925#include <unistd.h>
24926/* #include <time.h> */
24927#include <sys/time.h>
24928#include <errno.h>
24929#ifndef SQLITE_OMIT_WAL
24930#include <sys/mman.h>
24931#endif
24932
24933
24934#if SQLITE_ENABLE_LOCKING_STYLE
24935# include <sys/ioctl.h>
24936# if OS_VXWORKS
24937#  include <semaphore.h>
24938#  include <limits.h>
24939# else
24940#  include <sys/file.h>
24941#  include <sys/param.h>
24942# endif
24943#endif /* SQLITE_ENABLE_LOCKING_STYLE */
24944
24945#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24946# include <sys/mount.h>
24947#endif
24948
24949#ifdef HAVE_UTIME
24950# include <utime.h>
24951#endif
24952
24953/*
24954** Allowed values of unixFile.fsFlags
24955*/
24956#define SQLITE_FSFLAGS_IS_MSDOS     0x1
24957
24958/*
24959** If we are to be thread-safe, include the pthreads header and define
24960** the SQLITE_UNIX_THREADS macro.
24961*/
24962#if SQLITE_THREADSAFE
24963/* # include <pthread.h> */
24964# define SQLITE_UNIX_THREADS 1
24965#endif
24966
24967/*
24968** Default permissions when creating a new file
24969*/
24970#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24971# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24972#endif
24973
24974/*
24975 ** Default permissions when creating auto proxy dir
24976 */
24977#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24978# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24979#endif
24980
24981/*
24982** Maximum supported path-length.
24983*/
24984#define MAX_PATHNAME 512
24985
24986/*
24987** Only set the lastErrno if the error code is a real error and not
24988** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24989*/
24990#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24991
24992/* Forward references */
24993typedef struct unixShm unixShm;               /* Connection shared memory */
24994typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
24995typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
24996typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
24997
24998/*
24999** Sometimes, after a file handle is closed by SQLite, the file descriptor
25000** cannot be closed immediately. In these cases, instances of the following
25001** structure are used to store the file descriptor while waiting for an
25002** opportunity to either close or reuse it.
25003*/
25004struct UnixUnusedFd {
25005  int fd;                   /* File descriptor to close */
25006  int flags;                /* Flags this file descriptor was opened with */
25007  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
25008};
25009
25010/*
25011** The unixFile structure is subclass of sqlite3_file specific to the unix
25012** VFS implementations.
25013*/
25014typedef struct unixFile unixFile;
25015struct unixFile {
25016  sqlite3_io_methods const *pMethod;  /* Always the first entry */
25017  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
25018  unixInodeInfo *pInode;              /* Info about locks on this inode */
25019  int h;                              /* The file descriptor */
25020  unsigned char eFileLock;            /* The type of lock held on this fd */
25021  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
25022  int lastErrno;                      /* The unix errno from last I/O error */
25023  void *lockingContext;               /* Locking style specific state */
25024  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
25025  const char *zPath;                  /* Name of the file */
25026  unixShm *pShm;                      /* Shared memory segment information */
25027  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
25028#if SQLITE_ENABLE_LOCKING_STYLE
25029  int openFlags;                      /* The flags specified at open() */
25030#endif
25031#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
25032  unsigned fsFlags;                   /* cached details from statfs() */
25033#endif
25034#if OS_VXWORKS
25035  struct vxworksFileId *pId;          /* Unique file ID */
25036#endif
25037#ifndef NDEBUG
25038  /* The next group of variables are used to track whether or not the
25039  ** transaction counter in bytes 24-27 of database files are updated
25040  ** whenever any part of the database changes.  An assertion fault will
25041  ** occur if a file is updated without also updating the transaction
25042  ** counter.  This test is made to avoid new problems similar to the
25043  ** one described by ticket #3584.
25044  */
25045  unsigned char transCntrChng;   /* True if the transaction counter changed */
25046  unsigned char dbUpdate;        /* True if any part of database file changed */
25047  unsigned char inNormalWrite;   /* True if in a normal write operation */
25048#endif
25049#ifdef SQLITE_TEST
25050  /* In test mode, increase the size of this structure a bit so that
25051  ** it is larger than the struct CrashFile defined in test6.c.
25052  */
25053  char aPadding[32];
25054#endif
25055};
25056
25057/*
25058** Allowed values for the unixFile.ctrlFlags bitmask:
25059*/
25060#define UNIXFILE_EXCL        0x01     /* Connections from one process only */
25061#define UNIXFILE_RDONLY      0x02     /* Connection is read only */
25062#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
25063#ifndef SQLITE_DISABLE_DIRSYNC
25064# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
25065#else
25066# define UNIXFILE_DIRSYNC    0x00
25067#endif
25068#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
25069#define UNIXFILE_DELETE      0x20     /* Delete on close */
25070#define UNIXFILE_URI         0x40     /* Filename might have query parameters */
25071#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
25072#define UNIXFILE_CHOWN      0x100     /* File ownership was changed */
25073
25074/*
25075** Include code that is common to all os_*.c files
25076*/
25077/************** Include os_common.h in the middle of os_unix.c ***************/
25078/************** Begin file os_common.h ***************************************/
25079/*
25080** 2004 May 22
25081**
25082** The author disclaims copyright to this source code.  In place of
25083** a legal notice, here is a blessing:
25084**
25085**    May you do good and not evil.
25086**    May you find forgiveness for yourself and forgive others.
25087**    May you share freely, never taking more than you give.
25088**
25089******************************************************************************
25090**
25091** This file contains macros and a little bit of code that is common to
25092** all of the platform-specific files (os_*.c) and is #included into those
25093** files.
25094**
25095** This file should be #included by the os_*.c files only.  It is not a
25096** general purpose header file.
25097*/
25098#ifndef _OS_COMMON_H_
25099#define _OS_COMMON_H_
25100
25101/*
25102** At least two bugs have slipped in because we changed the MEMORY_DEBUG
25103** macro to SQLITE_DEBUG and some older makefiles have not yet made the
25104** switch.  The following code should catch this problem at compile-time.
25105*/
25106#ifdef MEMORY_DEBUG
25107# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
25108#endif
25109
25110#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25111# ifndef SQLITE_DEBUG_OS_TRACE
25112#   define SQLITE_DEBUG_OS_TRACE 0
25113# endif
25114  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
25115# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
25116#else
25117# define OSTRACE(X)
25118#endif
25119
25120/*
25121** Macros for performance tracing.  Normally turned off.  Only works
25122** on i486 hardware.
25123*/
25124#ifdef SQLITE_PERFORMANCE_TRACE
25125
25126/*
25127** hwtime.h contains inline assembler code for implementing
25128** high-performance timing routines.
25129*/
25130/************** Include hwtime.h in the middle of os_common.h ****************/
25131/************** Begin file hwtime.h ******************************************/
25132/*
25133** 2008 May 27
25134**
25135** The author disclaims copyright to this source code.  In place of
25136** a legal notice, here is a blessing:
25137**
25138**    May you do good and not evil.
25139**    May you find forgiveness for yourself and forgive others.
25140**    May you share freely, never taking more than you give.
25141**
25142******************************************************************************
25143**
25144** This file contains inline asm code for retrieving "high-performance"
25145** counters for x86 class CPUs.
25146*/
25147#ifndef _HWTIME_H_
25148#define _HWTIME_H_
25149
25150/*
25151** The following routine only works on pentium-class (or newer) processors.
25152** It uses the RDTSC opcode to read the cycle count value out of the
25153** processor and returns that value.  This can be used for high-res
25154** profiling.
25155*/
25156#if (defined(__GNUC__) || defined(_MSC_VER)) && \
25157      (defined(i386) || defined(__i386__) || defined(_M_IX86))
25158
25159  #if defined(__GNUC__)
25160
25161  __inline__ sqlite_uint64 sqlite3Hwtime(void){
25162     unsigned int lo, hi;
25163     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
25164     return (sqlite_uint64)hi << 32 | lo;
25165  }
25166
25167  #elif defined(_MSC_VER)
25168
25169  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
25170     __asm {
25171        rdtsc
25172        ret       ; return value at EDX:EAX
25173     }
25174  }
25175
25176  #endif
25177
25178#elif (defined(__GNUC__) && defined(__x86_64__))
25179
25180  __inline__ sqlite_uint64 sqlite3Hwtime(void){
25181      unsigned long val;
25182      __asm__ __volatile__ ("rdtsc" : "=A" (val));
25183      return val;
25184  }
25185
25186#elif (defined(__GNUC__) && defined(__ppc__))
25187
25188  __inline__ sqlite_uint64 sqlite3Hwtime(void){
25189      unsigned long long retval;
25190      unsigned long junk;
25191      __asm__ __volatile__ ("\n\
25192          1:      mftbu   %1\n\
25193                  mftb    %L0\n\
25194                  mftbu   %0\n\
25195                  cmpw    %0,%1\n\
25196                  bne     1b"
25197                  : "=r" (retval), "=r" (junk));
25198      return retval;
25199  }
25200
25201#else
25202
25203  #error Need implementation of sqlite3Hwtime() for your platform.
25204
25205  /*
25206  ** To compile without implementing sqlite3Hwtime() for your platform,
25207  ** you can remove the above #error and use the following
25208  ** stub function.  You will lose timing support for many
25209  ** of the debugging and testing utilities, but it should at
25210  ** least compile and run.
25211  */
25212SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
25213
25214#endif
25215
25216#endif /* !defined(_HWTIME_H_) */
25217
25218/************** End of hwtime.h **********************************************/
25219/************** Continuing where we left off in os_common.h ******************/
25220
25221static sqlite_uint64 g_start;
25222static sqlite_uint64 g_elapsed;
25223#define TIMER_START       g_start=sqlite3Hwtime()
25224#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
25225#define TIMER_ELAPSED     g_elapsed
25226#else
25227#define TIMER_START
25228#define TIMER_END
25229#define TIMER_ELAPSED     ((sqlite_uint64)0)
25230#endif
25231
25232/*
25233** If we compile with the SQLITE_TEST macro set, then the following block
25234** of code will give us the ability to simulate a disk I/O error.  This
25235** is used for testing the I/O recovery logic.
25236*/
25237#ifdef SQLITE_TEST
25238SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
25239SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
25240SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
25241SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
25242SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
25243SQLITE_API int sqlite3_diskfull_pending = 0;
25244SQLITE_API int sqlite3_diskfull = 0;
25245#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
25246#define SimulateIOError(CODE)  \
25247  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
25248       || sqlite3_io_error_pending-- == 1 )  \
25249              { local_ioerr(); CODE; }
25250static void local_ioerr(){
25251  IOTRACE(("IOERR\n"));
25252  sqlite3_io_error_hit++;
25253  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
25254}
25255#define SimulateDiskfullError(CODE) \
25256   if( sqlite3_diskfull_pending ){ \
25257     if( sqlite3_diskfull_pending == 1 ){ \
25258       local_ioerr(); \
25259       sqlite3_diskfull = 1; \
25260       sqlite3_io_error_hit = 1; \
25261       CODE; \
25262     }else{ \
25263       sqlite3_diskfull_pending--; \
25264     } \
25265   }
25266#else
25267#define SimulateIOErrorBenign(X)
25268#define SimulateIOError(A)
25269#define SimulateDiskfullError(A)
25270#endif
25271
25272/*
25273** When testing, keep a count of the number of open files.
25274*/
25275#ifdef SQLITE_TEST
25276SQLITE_API int sqlite3_open_file_count = 0;
25277#define OpenCounter(X)  sqlite3_open_file_count+=(X)
25278#else
25279#define OpenCounter(X)
25280#endif
25281
25282#endif /* !defined(_OS_COMMON_H_) */
25283
25284/************** End of os_common.h *******************************************/
25285/************** Continuing where we left off in os_unix.c ********************/
25286
25287/*
25288** Define various macros that are missing from some systems.
25289*/
25290#ifndef O_LARGEFILE
25291# define O_LARGEFILE 0
25292#endif
25293#ifdef SQLITE_DISABLE_LFS
25294# undef O_LARGEFILE
25295# define O_LARGEFILE 0
25296#endif
25297#ifndef O_NOFOLLOW
25298# define O_NOFOLLOW 0
25299#endif
25300#ifndef O_BINARY
25301# define O_BINARY 0
25302#endif
25303
25304/*
25305** The threadid macro resolves to the thread-id or to 0.  Used for
25306** testing and debugging only.
25307*/
25308#if SQLITE_THREADSAFE
25309#define threadid pthread_self()
25310#else
25311#define threadid 0
25312#endif
25313
25314/*
25315** Different Unix systems declare open() in different ways.  Same use
25316** open(const char*,int,mode_t).  Others use open(const char*,int,...).
25317** The difference is important when using a pointer to the function.
25318**
25319** The safest way to deal with the problem is to always use this wrapper
25320** which always has the same well-defined interface.
25321*/
25322static int posixOpen(const char *zFile, int flags, int mode){
25323  return open(zFile, flags, mode);
25324}
25325
25326/* Forward reference */
25327static int openDirectory(const char*, int*);
25328
25329/*
25330** Many system calls are accessed through pointer-to-functions so that
25331** they may be overridden at runtime to facilitate fault injection during
25332** testing and sandboxing.  The following array holds the names and pointers
25333** to all overrideable system calls.
25334*/
25335static struct unix_syscall {
25336  const char *zName;            /* Name of the sytem call */
25337  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
25338  sqlite3_syscall_ptr pDefault; /* Default value */
25339} aSyscall[] = {
25340  { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
25341#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
25342
25343  { "close",        (sqlite3_syscall_ptr)close,      0  },
25344#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
25345
25346  { "access",       (sqlite3_syscall_ptr)access,     0  },
25347#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
25348
25349  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
25350#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
25351
25352  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
25353#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
25354
25355/*
25356** The DJGPP compiler environment looks mostly like Unix, but it
25357** lacks the fcntl() system call.  So redefine fcntl() to be something
25358** that always succeeds.  This means that locking does not occur under
25359** DJGPP.  But it is DOS - what did you expect?
25360*/
25361#ifdef __DJGPP__
25362  { "fstat",        0,                 0  },
25363#define osFstat(a,b,c)    0
25364#else
25365  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
25366#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
25367#endif
25368
25369  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
25370#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
25371
25372  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
25373#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
25374
25375  { "read",         (sqlite3_syscall_ptr)read,       0  },
25376#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
25377
25378#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25379  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
25380#else
25381  { "pread",        (sqlite3_syscall_ptr)0,          0  },
25382#endif
25383#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
25384
25385#if defined(USE_PREAD64)
25386  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
25387#else
25388  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
25389#endif
25390#ifdef ANDROID
25391// Bionic defines pread64 using off64_t rather than off_t.
25392#define osPread64   ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
25393#else
25394#define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
25395#endif
25396
25397  { "write",        (sqlite3_syscall_ptr)write,      0  },
25398#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
25399
25400#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25401  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
25402#else
25403  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
25404#endif
25405#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
25406                    aSyscall[12].pCurrent)
25407
25408#if defined(USE_PREAD64)
25409  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
25410#else
25411  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
25412#endif
25413#ifdef ANDROID
25414// Bionic defines pwrite64 using off64_t rather than off_t.
25415#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
25416                    aSyscall[13].pCurrent)
25417#else
25418#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
25419                    aSyscall[13].pCurrent)
25420#endif
25421
25422#if SQLITE_ENABLE_LOCKING_STYLE
25423  { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
25424#else
25425  { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
25426#endif
25427#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
25428
25429#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25430  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
25431#else
25432  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
25433#endif
25434#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
25435
25436  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
25437#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
25438
25439  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
25440#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
25441
25442  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
25443#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
25444
25445  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
25446#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
25447
25448  { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
25449#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
25450
25451  { "umask",        (sqlite3_syscall_ptr)umask,           0 },
25452#define osUmask     ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
25453
25454}; /* End of the overrideable system calls */
25455
25456/*
25457** This is the xSetSystemCall() method of sqlite3_vfs for all of the
25458** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
25459** system call pointer, or SQLITE_NOTFOUND if there is no configurable
25460** system call named zName.
25461*/
25462static int unixSetSystemCall(
25463  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
25464  const char *zName,            /* Name of system call to override */
25465  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
25466){
25467  unsigned int i;
25468  int rc = SQLITE_NOTFOUND;
25469
25470  UNUSED_PARAMETER(pNotUsed);
25471  if( zName==0 ){
25472    /* If no zName is given, restore all system calls to their default
25473    ** settings and return NULL
25474    */
25475    rc = SQLITE_OK;
25476    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25477      if( aSyscall[i].pDefault ){
25478        aSyscall[i].pCurrent = aSyscall[i].pDefault;
25479      }
25480    }
25481  }else{
25482    /* If zName is specified, operate on only the one system call
25483    ** specified.
25484    */
25485    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25486      if( strcmp(zName, aSyscall[i].zName)==0 ){
25487        if( aSyscall[i].pDefault==0 ){
25488          aSyscall[i].pDefault = aSyscall[i].pCurrent;
25489        }
25490        rc = SQLITE_OK;
25491        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
25492        aSyscall[i].pCurrent = pNewFunc;
25493        break;
25494      }
25495    }
25496  }
25497  return rc;
25498}
25499
25500/*
25501** Return the value of a system call.  Return NULL if zName is not a
25502** recognized system call name.  NULL is also returned if the system call
25503** is currently undefined.
25504*/
25505static sqlite3_syscall_ptr unixGetSystemCall(
25506  sqlite3_vfs *pNotUsed,
25507  const char *zName
25508){
25509  unsigned int i;
25510
25511  UNUSED_PARAMETER(pNotUsed);
25512  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25513    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
25514  }
25515  return 0;
25516}
25517
25518/*
25519** Return the name of the first system call after zName.  If zName==NULL
25520** then return the name of the first system call.  Return NULL if zName
25521** is the last system call or if zName is not the name of a valid
25522** system call.
25523*/
25524static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
25525  int i = -1;
25526
25527  UNUSED_PARAMETER(p);
25528  if( zName ){
25529    for(i=0; i<ArraySize(aSyscall)-1; i++){
25530      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
25531    }
25532  }
25533  for(i++; i<ArraySize(aSyscall); i++){
25534    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
25535  }
25536  return 0;
25537}
25538
25539/*
25540** Invoke open().  Do so multiple times, until it either succeeds or
25541** files for some reason other than EINTR.
25542**
25543** If the file creation mode "m" is 0 then set it to the default for
25544** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
25545** 0644) as modified by the system umask.  If m is not 0, then
25546** make the file creation mode be exactly m ignoring the umask.
25547**
25548** The m parameter will be non-zero only when creating -wal, -journal,
25549** and -shm files.  We want those files to have *exactly* the same
25550** permissions as their original database, unadulterated by the umask.
25551** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
25552** transaction crashes and leaves behind hot journals, then any
25553** process that is able to write to the database will also be able to
25554** recover the hot journals.
25555*/
25556static int robust_open(const char *z, int f, mode_t m){
25557  int rc;
25558  mode_t m2;
25559  mode_t origM = 0;
25560  if( m==0 ){
25561    m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
25562  }else{
25563    m2 = m;
25564    origM = osUmask(0);
25565  }
25566  do{ rc = osOpen(z,f,m2); }while( rc<0 && errno==EINTR );
25567  if( m ){
25568    osUmask(origM);
25569  }
25570  return rc;
25571}
25572
25573/*
25574** Helper functions to obtain and relinquish the global mutex. The
25575** global mutex is used to protect the unixInodeInfo and
25576** vxworksFileId objects used by this file, all of which may be
25577** shared by multiple threads.
25578**
25579** Function unixMutexHeld() is used to assert() that the global mutex
25580** is held when required. This function is only used as part of assert()
25581** statements. e.g.
25582**
25583**   unixEnterMutex()
25584**     assert( unixMutexHeld() );
25585**   unixEnterLeave()
25586*/
25587static void unixEnterMutex(void){
25588  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25589}
25590static void unixLeaveMutex(void){
25591  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25592}
25593#ifdef SQLITE_DEBUG
25594static int unixMutexHeld(void) {
25595  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25596}
25597#endif
25598
25599
25600#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25601/*
25602** Helper function for printing out trace information from debugging
25603** binaries. This returns the string represetation of the supplied
25604** integer lock-type.
25605*/
25606static const char *azFileLock(int eFileLock){
25607  switch( eFileLock ){
25608    case NO_LOCK: return "NONE";
25609    case SHARED_LOCK: return "SHARED";
25610    case RESERVED_LOCK: return "RESERVED";
25611    case PENDING_LOCK: return "PENDING";
25612    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
25613  }
25614  return "ERROR";
25615}
25616#endif
25617
25618#ifdef SQLITE_LOCK_TRACE
25619/*
25620** Print out information about all locking operations.
25621**
25622** This routine is used for troubleshooting locks on multithreaded
25623** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
25624** command-line option on the compiler.  This code is normally
25625** turned off.
25626*/
25627static int lockTrace(int fd, int op, struct flock *p){
25628  char *zOpName, *zType;
25629  int s;
25630  int savedErrno;
25631  if( op==F_GETLK ){
25632    zOpName = "GETLK";
25633  }else if( op==F_SETLK ){
25634    zOpName = "SETLK";
25635  }else{
25636    s = osFcntl(fd, op, p);
25637    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
25638    return s;
25639  }
25640  if( p->l_type==F_RDLCK ){
25641    zType = "RDLCK";
25642  }else if( p->l_type==F_WRLCK ){
25643    zType = "WRLCK";
25644  }else if( p->l_type==F_UNLCK ){
25645    zType = "UNLCK";
25646  }else{
25647    assert( 0 );
25648  }
25649  assert( p->l_whence==SEEK_SET );
25650  s = osFcntl(fd, op, p);
25651  savedErrno = errno;
25652  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
25653     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
25654     (int)p->l_pid, s);
25655  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
25656    struct flock l2;
25657    l2 = *p;
25658    osFcntl(fd, F_GETLK, &l2);
25659    if( l2.l_type==F_RDLCK ){
25660      zType = "RDLCK";
25661    }else if( l2.l_type==F_WRLCK ){
25662      zType = "WRLCK";
25663    }else if( l2.l_type==F_UNLCK ){
25664      zType = "UNLCK";
25665    }else{
25666      assert( 0 );
25667    }
25668    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
25669       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
25670  }
25671  errno = savedErrno;
25672  return s;
25673}
25674#undef osFcntl
25675#define osFcntl lockTrace
25676#endif /* SQLITE_LOCK_TRACE */
25677
25678/*
25679** Retry ftruncate() calls that fail due to EINTR
25680*/
25681static int robust_ftruncate(int h, sqlite3_int64 sz){
25682  int rc;
25683  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
25684  return rc;
25685}
25686
25687/*
25688** This routine translates a standard POSIX errno code into something
25689** useful to the clients of the sqlite3 functions.  Specifically, it is
25690** intended to translate a variety of "try again" errors into SQLITE_BUSY
25691** and a variety of "please close the file descriptor NOW" errors into
25692** SQLITE_IOERR
25693**
25694** Errors during initialization of locks, or file system support for locks,
25695** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
25696*/
25697static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
25698  switch (posixError) {
25699#if 0
25700  /* At one point this code was not commented out. In theory, this branch
25701  ** should never be hit, as this function should only be called after
25702  ** a locking-related function (i.e. fcntl()) has returned non-zero with
25703  ** the value of errno as the first argument. Since a system call has failed,
25704  ** errno should be non-zero.
25705  **
25706  ** Despite this, if errno really is zero, we still don't want to return
25707  ** SQLITE_OK. The system call failed, and *some* SQLite error should be
25708  ** propagated back to the caller. Commenting this branch out means errno==0
25709  ** will be handled by the "default:" case below.
25710  */
25711  case 0:
25712    return SQLITE_OK;
25713#endif
25714
25715  case EAGAIN:
25716  case ETIMEDOUT:
25717  case EBUSY:
25718  case EINTR:
25719  case ENOLCK:
25720    /* random NFS retry error, unless during file system support
25721     * introspection, in which it actually means what it says */
25722    return SQLITE_BUSY;
25723
25724  case EACCES:
25725    /* EACCES is like EAGAIN during locking operations, but not any other time*/
25726    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
25727	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
25728	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
25729	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
25730      return SQLITE_BUSY;
25731    }
25732    /* else fall through */
25733  case EPERM:
25734    return SQLITE_PERM;
25735
25736  /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
25737  ** this module never makes such a call. And the code in SQLite itself
25738  ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
25739  ** this case is also commented out. If the system does set errno to EDEADLK,
25740  ** the default SQLITE_IOERR_XXX code will be returned. */
25741#if 0
25742  case EDEADLK:
25743    return SQLITE_IOERR_BLOCKED;
25744#endif
25745
25746#if EOPNOTSUPP!=ENOTSUP
25747  case EOPNOTSUPP:
25748    /* something went terribly awry, unless during file system support
25749     * introspection, in which it actually means what it says */
25750#endif
25751#ifdef ENOTSUP
25752  case ENOTSUP:
25753    /* invalid fd, unless during file system support introspection, in which
25754     * it actually means what it says */
25755#endif
25756  case EIO:
25757  case EBADF:
25758  case EINVAL:
25759  case ENOTCONN:
25760  case ENODEV:
25761  case ENXIO:
25762  case ENOENT:
25763#ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
25764  case ESTALE:
25765#endif
25766  case ENOSYS:
25767    /* these should force the client to close the file and reconnect */
25768
25769  default:
25770    return sqliteIOErr;
25771  }
25772}
25773
25774
25775
25776/******************************************************************************
25777****************** Begin Unique File ID Utility Used By VxWorks ***************
25778**
25779** On most versions of unix, we can get a unique ID for a file by concatenating
25780** the device number and the inode number.  But this does not work on VxWorks.
25781** On VxWorks, a unique file id must be based on the canonical filename.
25782**
25783** A pointer to an instance of the following structure can be used as a
25784** unique file ID in VxWorks.  Each instance of this structure contains
25785** a copy of the canonical filename.  There is also a reference count.
25786** The structure is reclaimed when the number of pointers to it drops to
25787** zero.
25788**
25789** There are never very many files open at one time and lookups are not
25790** a performance-critical path, so it is sufficient to put these
25791** structures on a linked list.
25792*/
25793struct vxworksFileId {
25794  struct vxworksFileId *pNext;  /* Next in a list of them all */
25795  int nRef;                     /* Number of references to this one */
25796  int nName;                    /* Length of the zCanonicalName[] string */
25797  char *zCanonicalName;         /* Canonical filename */
25798};
25799
25800#if OS_VXWORKS
25801/*
25802** All unique filenames are held on a linked list headed by this
25803** variable:
25804*/
25805static struct vxworksFileId *vxworksFileList = 0;
25806
25807/*
25808** Simplify a filename into its canonical form
25809** by making the following changes:
25810**
25811**  * removing any trailing and duplicate /
25812**  * convert /./ into just /
25813**  * convert /A/../ where A is any simple name into just /
25814**
25815** Changes are made in-place.  Return the new name length.
25816**
25817** The original filename is in z[0..n-1].  Return the number of
25818** characters in the simplified name.
25819*/
25820static int vxworksSimplifyName(char *z, int n){
25821  int i, j;
25822  while( n>1 && z[n-1]=='/' ){ n--; }
25823  for(i=j=0; i<n; i++){
25824    if( z[i]=='/' ){
25825      if( z[i+1]=='/' ) continue;
25826      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
25827        i += 1;
25828        continue;
25829      }
25830      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
25831        while( j>0 && z[j-1]!='/' ){ j--; }
25832        if( j>0 ){ j--; }
25833        i += 2;
25834        continue;
25835      }
25836    }
25837    z[j++] = z[i];
25838  }
25839  z[j] = 0;
25840  return j;
25841}
25842
25843/*
25844** Find a unique file ID for the given absolute pathname.  Return
25845** a pointer to the vxworksFileId object.  This pointer is the unique
25846** file ID.
25847**
25848** The nRef field of the vxworksFileId object is incremented before
25849** the object is returned.  A new vxworksFileId object is created
25850** and added to the global list if necessary.
25851**
25852** If a memory allocation error occurs, return NULL.
25853*/
25854static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
25855  struct vxworksFileId *pNew;         /* search key and new file ID */
25856  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
25857  int n;                              /* Length of zAbsoluteName string */
25858
25859  assert( zAbsoluteName[0]=='/' );
25860  n = (int)strlen(zAbsoluteName);
25861  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
25862  if( pNew==0 ) return 0;
25863  pNew->zCanonicalName = (char*)&pNew[1];
25864  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
25865  n = vxworksSimplifyName(pNew->zCanonicalName, n);
25866
25867  /* Search for an existing entry that matching the canonical name.
25868  ** If found, increment the reference count and return a pointer to
25869  ** the existing file ID.
25870  */
25871  unixEnterMutex();
25872  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
25873    if( pCandidate->nName==n
25874     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
25875    ){
25876       sqlite3_free(pNew);
25877       pCandidate->nRef++;
25878       unixLeaveMutex();
25879       return pCandidate;
25880    }
25881  }
25882
25883  /* No match was found.  We will make a new file ID */
25884  pNew->nRef = 1;
25885  pNew->nName = n;
25886  pNew->pNext = vxworksFileList;
25887  vxworksFileList = pNew;
25888  unixLeaveMutex();
25889  return pNew;
25890}
25891
25892/*
25893** Decrement the reference count on a vxworksFileId object.  Free
25894** the object when the reference count reaches zero.
25895*/
25896static void vxworksReleaseFileId(struct vxworksFileId *pId){
25897  unixEnterMutex();
25898  assert( pId->nRef>0 );
25899  pId->nRef--;
25900  if( pId->nRef==0 ){
25901    struct vxworksFileId **pp;
25902    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
25903    assert( *pp==pId );
25904    *pp = pId->pNext;
25905    sqlite3_free(pId);
25906  }
25907  unixLeaveMutex();
25908}
25909#endif /* OS_VXWORKS */
25910/*************** End of Unique File ID Utility Used By VxWorks ****************
25911******************************************************************************/
25912
25913
25914/******************************************************************************
25915*************************** Posix Advisory Locking ****************************
25916**
25917** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
25918** section 6.5.2.2 lines 483 through 490 specify that when a process
25919** sets or clears a lock, that operation overrides any prior locks set
25920** by the same process.  It does not explicitly say so, but this implies
25921** that it overrides locks set by the same process using a different
25922** file descriptor.  Consider this test case:
25923**
25924**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
25925**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
25926**
25927** Suppose ./file1 and ./file2 are really the same file (because
25928** one is a hard or symbolic link to the other) then if you set
25929** an exclusive lock on fd1, then try to get an exclusive lock
25930** on fd2, it works.  I would have expected the second lock to
25931** fail since there was already a lock on the file due to fd1.
25932** But not so.  Since both locks came from the same process, the
25933** second overrides the first, even though they were on different
25934** file descriptors opened on different file names.
25935**
25936** This means that we cannot use POSIX locks to synchronize file access
25937** among competing threads of the same process.  POSIX locks will work fine
25938** to synchronize access for threads in separate processes, but not
25939** threads within the same process.
25940**
25941** To work around the problem, SQLite has to manage file locks internally
25942** on its own.  Whenever a new database is opened, we have to find the
25943** specific inode of the database file (the inode is determined by the
25944** st_dev and st_ino fields of the stat structure that fstat() fills in)
25945** and check for locks already existing on that inode.  When locks are
25946** created or removed, we have to look at our own internal record of the
25947** locks to see if another thread has previously set a lock on that same
25948** inode.
25949**
25950** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
25951** For VxWorks, we have to use the alternative unique ID system based on
25952** canonical filename and implemented in the previous division.)
25953**
25954** The sqlite3_file structure for POSIX is no longer just an integer file
25955** descriptor.  It is now a structure that holds the integer file
25956** descriptor and a pointer to a structure that describes the internal
25957** locks on the corresponding inode.  There is one locking structure
25958** per inode, so if the same inode is opened twice, both unixFile structures
25959** point to the same locking structure.  The locking structure keeps
25960** a reference count (so we will know when to delete it) and a "cnt"
25961** field that tells us its internal lock status.  cnt==0 means the
25962** file is unlocked.  cnt==-1 means the file has an exclusive lock.
25963** cnt>0 means there are cnt shared locks on the file.
25964**
25965** Any attempt to lock or unlock a file first checks the locking
25966** structure.  The fcntl() system call is only invoked to set a
25967** POSIX lock if the internal lock structure transitions between
25968** a locked and an unlocked state.
25969**
25970** But wait:  there are yet more problems with POSIX advisory locks.
25971**
25972** If you close a file descriptor that points to a file that has locks,
25973** all locks on that file that are owned by the current process are
25974** released.  To work around this problem, each unixInodeInfo object
25975** maintains a count of the number of pending locks on tha inode.
25976** When an attempt is made to close an unixFile, if there are
25977** other unixFile open on the same inode that are holding locks, the call
25978** to close() the file descriptor is deferred until all of the locks clear.
25979** The unixInodeInfo structure keeps a list of file descriptors that need to
25980** be closed and that list is walked (and cleared) when the last lock
25981** clears.
25982**
25983** Yet another problem:  LinuxThreads do not play well with posix locks.
25984**
25985** Many older versions of linux use the LinuxThreads library which is
25986** not posix compliant.  Under LinuxThreads, a lock created by thread
25987** A cannot be modified or overridden by a different thread B.
25988** Only thread A can modify the lock.  Locking behavior is correct
25989** if the appliation uses the newer Native Posix Thread Library (NPTL)
25990** on linux - with NPTL a lock created by thread A can override locks
25991** in thread B.  But there is no way to know at compile-time which
25992** threading library is being used.  So there is no way to know at
25993** compile-time whether or not thread A can override locks on thread B.
25994** One has to do a run-time check to discover the behavior of the
25995** current process.
25996**
25997** SQLite used to support LinuxThreads.  But support for LinuxThreads
25998** was dropped beginning with version 3.7.0.  SQLite will still work with
25999** LinuxThreads provided that (1) there is no more than one connection
26000** per database file in the same process and (2) database connections
26001** do not move across threads.
26002*/
26003
26004/*
26005** An instance of the following structure serves as the key used
26006** to locate a particular unixInodeInfo object.
26007*/
26008struct unixFileId {
26009  dev_t dev;                  /* Device number */
26010#if OS_VXWORKS
26011  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
26012#else
26013  ino_t ino;                  /* Inode number */
26014#endif
26015};
26016
26017/*
26018** An instance of the following structure is allocated for each open
26019** inode.  Or, on LinuxThreads, there is one of these structures for
26020** each inode opened by each thread.
26021**
26022** A single inode can have multiple file descriptors, so each unixFile
26023** structure contains a pointer to an instance of this object and this
26024** object keeps a count of the number of unixFile pointing to it.
26025*/
26026struct unixInodeInfo {
26027  struct unixFileId fileId;       /* The lookup key */
26028  int nShared;                    /* Number of SHARED locks held */
26029  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
26030  unsigned char bProcessLock;     /* An exclusive process lock is held */
26031  int nRef;                       /* Number of pointers to this structure */
26032  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
26033  int nLock;                      /* Number of outstanding file locks */
26034  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
26035  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
26036  unixInodeInfo *pPrev;           /*    .... doubly linked */
26037#if SQLITE_ENABLE_LOCKING_STYLE
26038  unsigned long long sharedByte;  /* for AFP simulated shared lock */
26039#endif
26040#if OS_VXWORKS
26041  sem_t *pSem;                    /* Named POSIX semaphore */
26042  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
26043#endif
26044};
26045
26046/*
26047** A lists of all unixInodeInfo objects.
26048*/
26049static unixInodeInfo *inodeList = 0;
26050
26051/*
26052**
26053** This function - unixLogError_x(), is only ever called via the macro
26054** unixLogError().
26055**
26056** It is invoked after an error occurs in an OS function and errno has been
26057** set. It logs a message using sqlite3_log() containing the current value of
26058** errno and, if possible, the human-readable equivalent from strerror() or
26059** strerror_r().
26060**
26061** The first argument passed to the macro should be the error code that
26062** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
26063** The two subsequent arguments should be the name of the OS function that
26064** failed (e.g. "unlink", "open") and the the associated file-system path,
26065** if any.
26066*/
26067#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
26068static int unixLogErrorAtLine(
26069  int errcode,                    /* SQLite error code */
26070  const char *zFunc,              /* Name of OS function that failed */
26071  const char *zPath,              /* File path associated with error */
26072  int iLine                       /* Source line number where error occurred */
26073){
26074  char *zErr;                     /* Message from strerror() or equivalent */
26075  int iErrno = errno;             /* Saved syscall error number */
26076
26077  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
26078  ** the strerror() function to obtain the human-readable error message
26079  ** equivalent to errno. Otherwise, use strerror_r().
26080  */
26081#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
26082  char aErr[80];
26083  memset(aErr, 0, sizeof(aErr));
26084  zErr = aErr;
26085
26086  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
26087  ** assume that the system provides the the GNU version of strerror_r() that
26088  ** returns a pointer to a buffer containing the error message. That pointer
26089  ** may point to aErr[], or it may point to some static storage somewhere.
26090  ** Otherwise, assume that the system provides the POSIX version of
26091  ** strerror_r(), which always writes an error message into aErr[].
26092  **
26093  ** If the code incorrectly assumes that it is the POSIX version that is
26094  ** available, the error message will often be an empty string. Not a
26095  ** huge problem. Incorrectly concluding that the GNU version is available
26096  ** could lead to a segfault though.
26097  */
26098#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
26099  zErr =
26100# endif
26101  strerror_r(iErrno, aErr, sizeof(aErr)-1);
26102
26103#elif SQLITE_THREADSAFE
26104  /* This is a threadsafe build, but strerror_r() is not available. */
26105  zErr = "";
26106#else
26107  /* Non-threadsafe build, use strerror(). */
26108  zErr = strerror(iErrno);
26109#endif
26110
26111  assert( errcode!=SQLITE_OK );
26112  if( zPath==0 ) zPath = "";
26113  sqlite3_log(errcode,
26114      "os_unix.c:%d: (%d) %s(%s) - %s",
26115      iLine, iErrno, zFunc, zPath, zErr
26116  );
26117
26118  return errcode;
26119}
26120
26121/*
26122** Close a file descriptor.
26123**
26124** We assume that close() almost always works, since it is only in a
26125** very sick application or on a very sick platform that it might fail.
26126** If it does fail, simply leak the file descriptor, but do log the
26127** error.
26128**
26129** Note that it is not safe to retry close() after EINTR since the
26130** file descriptor might have already been reused by another thread.
26131** So we don't even try to recover from an EINTR.  Just log the error
26132** and move on.
26133*/
26134static void robust_close(unixFile *pFile, int h, int lineno){
26135  if( osClose(h) ){
26136    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
26137                       pFile ? pFile->zPath : 0, lineno);
26138  }
26139}
26140
26141/*
26142** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
26143*/
26144static void closePendingFds(unixFile *pFile){
26145  unixInodeInfo *pInode = pFile->pInode;
26146  UnixUnusedFd *p;
26147  UnixUnusedFd *pNext;
26148  for(p=pInode->pUnused; p; p=pNext){
26149    pNext = p->pNext;
26150    robust_close(pFile, p->fd, __LINE__);
26151    sqlite3_free(p);
26152  }
26153  pInode->pUnused = 0;
26154}
26155
26156/*
26157** Release a unixInodeInfo structure previously allocated by findInodeInfo().
26158**
26159** The mutex entered using the unixEnterMutex() function must be held
26160** when this function is called.
26161*/
26162static void releaseInodeInfo(unixFile *pFile){
26163  unixInodeInfo *pInode = pFile->pInode;
26164  assert( unixMutexHeld() );
26165  if( ALWAYS(pInode) ){
26166    pInode->nRef--;
26167    if( pInode->nRef==0 ){
26168      assert( pInode->pShmNode==0 );
26169      closePendingFds(pFile);
26170      if( pInode->pPrev ){
26171        assert( pInode->pPrev->pNext==pInode );
26172        pInode->pPrev->pNext = pInode->pNext;
26173      }else{
26174        assert( inodeList==pInode );
26175        inodeList = pInode->pNext;
26176      }
26177      if( pInode->pNext ){
26178        assert( pInode->pNext->pPrev==pInode );
26179        pInode->pNext->pPrev = pInode->pPrev;
26180      }
26181      sqlite3_free(pInode);
26182    }
26183  }
26184}
26185
26186/*
26187** Given a file descriptor, locate the unixInodeInfo object that
26188** describes that file descriptor.  Create a new one if necessary.  The
26189** return value might be uninitialized if an error occurs.
26190**
26191** The mutex entered using the unixEnterMutex() function must be held
26192** when this function is called.
26193**
26194** Return an appropriate error code.
26195*/
26196static int findInodeInfo(
26197  unixFile *pFile,               /* Unix file with file desc used in the key */
26198  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
26199){
26200  int rc;                        /* System call return code */
26201  int fd;                        /* The file descriptor for pFile */
26202  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
26203  struct stat statbuf;           /* Low-level file information */
26204  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
26205
26206  assert( unixMutexHeld() );
26207
26208  /* Get low-level information about the file that we can used to
26209  ** create a unique name for the file.
26210  */
26211  fd = pFile->h;
26212  rc = osFstat(fd, &statbuf);
26213  if( rc!=0 ){
26214    pFile->lastErrno = errno;
26215#ifdef EOVERFLOW
26216    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
26217#endif
26218    return SQLITE_IOERR;
26219  }
26220
26221#ifdef __APPLE__
26222  /* On OS X on an msdos filesystem, the inode number is reported
26223  ** incorrectly for zero-size files.  See ticket #3260.  To work
26224  ** around this problem (we consider it a bug in OS X, not SQLite)
26225  ** we always increase the file size to 1 by writing a single byte
26226  ** prior to accessing the inode number.  The one byte written is
26227  ** an ASCII 'S' character which also happens to be the first byte
26228  ** in the header of every SQLite database.  In this way, if there
26229  ** is a race condition such that another thread has already populated
26230  ** the first page of the database, no damage is done.
26231  */
26232  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
26233    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
26234    if( rc!=1 ){
26235      pFile->lastErrno = errno;
26236      return SQLITE_IOERR;
26237    }
26238    rc = osFstat(fd, &statbuf);
26239    if( rc!=0 ){
26240      pFile->lastErrno = errno;
26241      return SQLITE_IOERR;
26242    }
26243  }
26244#endif
26245
26246  memset(&fileId, 0, sizeof(fileId));
26247  fileId.dev = statbuf.st_dev;
26248#if OS_VXWORKS
26249  fileId.pId = pFile->pId;
26250#else
26251  fileId.ino = statbuf.st_ino;
26252#endif
26253  pInode = inodeList;
26254  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
26255    pInode = pInode->pNext;
26256  }
26257  if( pInode==0 ){
26258    pInode = sqlite3_malloc( sizeof(*pInode) );
26259    if( pInode==0 ){
26260      return SQLITE_NOMEM;
26261    }
26262    memset(pInode, 0, sizeof(*pInode));
26263    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
26264    pInode->nRef = 1;
26265    pInode->pNext = inodeList;
26266    pInode->pPrev = 0;
26267    if( inodeList ) inodeList->pPrev = pInode;
26268    inodeList = pInode;
26269  }else{
26270    pInode->nRef++;
26271  }
26272  *ppInode = pInode;
26273  return SQLITE_OK;
26274}
26275
26276
26277/*
26278** This routine checks if there is a RESERVED lock held on the specified
26279** file by this or any other process. If such a lock is held, set *pResOut
26280** to a non-zero value otherwise *pResOut is set to zero.  The return value
26281** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26282*/
26283static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
26284  int rc = SQLITE_OK;
26285  int reserved = 0;
26286  unixFile *pFile = (unixFile*)id;
26287
26288  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26289
26290  assert( pFile );
26291  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26292
26293  /* Check if a thread in this process holds such a lock */
26294  if( pFile->pInode->eFileLock>SHARED_LOCK ){
26295    reserved = 1;
26296  }
26297
26298  /* Otherwise see if some other process holds it.
26299  */
26300#ifndef __DJGPP__
26301  if( !reserved && !pFile->pInode->bProcessLock ){
26302    struct flock lock;
26303    lock.l_whence = SEEK_SET;
26304    lock.l_start = RESERVED_BYTE;
26305    lock.l_len = 1;
26306    lock.l_type = F_WRLCK;
26307    if( osFcntl(pFile->h, F_GETLK, &lock) ){
26308      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
26309      pFile->lastErrno = errno;
26310    } else if( lock.l_type!=F_UNLCK ){
26311      reserved = 1;
26312    }
26313  }
26314#endif
26315
26316  unixLeaveMutex();
26317  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
26318
26319  *pResOut = reserved;
26320  return rc;
26321}
26322
26323/*
26324** Attempt to set a system-lock on the file pFile.  The lock is
26325** described by pLock.
26326**
26327** If the pFile was opened read/write from unix-excl, then the only lock
26328** ever obtained is an exclusive lock, and it is obtained exactly once
26329** the first time any lock is attempted.  All subsequent system locking
26330** operations become no-ops.  Locking operations still happen internally,
26331** in order to coordinate access between separate database connections
26332** within this process, but all of that is handled in memory and the
26333** operating system does not participate.
26334**
26335** This function is a pass-through to fcntl(F_SETLK) if pFile is using
26336** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
26337** and is read-only.
26338**
26339** Zero is returned if the call completes successfully, or -1 if a call
26340** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
26341*/
26342static int unixFileLock(unixFile *pFile, struct flock *pLock){
26343  int rc;
26344  unixInodeInfo *pInode = pFile->pInode;
26345  assert( unixMutexHeld() );
26346  assert( pInode!=0 );
26347  if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
26348   && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
26349  ){
26350    if( pInode->bProcessLock==0 ){
26351      struct flock lock;
26352      assert( pInode->nLock==0 );
26353      lock.l_whence = SEEK_SET;
26354      lock.l_start = SHARED_FIRST;
26355      lock.l_len = SHARED_SIZE;
26356      lock.l_type = F_WRLCK;
26357      rc = osFcntl(pFile->h, F_SETLK, &lock);
26358      if( rc<0 ) return rc;
26359      pInode->bProcessLock = 1;
26360      pInode->nLock++;
26361    }else{
26362      rc = 0;
26363    }
26364  }else{
26365    rc = osFcntl(pFile->h, F_SETLK, pLock);
26366  }
26367  return rc;
26368}
26369
26370/*
26371** Lock the file with the lock specified by parameter eFileLock - one
26372** of the following:
26373**
26374**     (1) SHARED_LOCK
26375**     (2) RESERVED_LOCK
26376**     (3) PENDING_LOCK
26377**     (4) EXCLUSIVE_LOCK
26378**
26379** Sometimes when requesting one lock state, additional lock states
26380** are inserted in between.  The locking might fail on one of the later
26381** transitions leaving the lock state different from what it started but
26382** still short of its goal.  The following chart shows the allowed
26383** transitions and the inserted intermediate states:
26384**
26385**    UNLOCKED -> SHARED
26386**    SHARED -> RESERVED
26387**    SHARED -> (PENDING) -> EXCLUSIVE
26388**    RESERVED -> (PENDING) -> EXCLUSIVE
26389**    PENDING -> EXCLUSIVE
26390**
26391** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26392** routine to lower a locking level.
26393*/
26394static int unixLock(sqlite3_file *id, int eFileLock){
26395  /* The following describes the implementation of the various locks and
26396  ** lock transitions in terms of the POSIX advisory shared and exclusive
26397  ** lock primitives (called read-locks and write-locks below, to avoid
26398  ** confusion with SQLite lock names). The algorithms are complicated
26399  ** slightly in order to be compatible with windows systems simultaneously
26400  ** accessing the same database file, in case that is ever required.
26401  **
26402  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
26403  ** byte', each single bytes at well known offsets, and the 'shared byte
26404  ** range', a range of 510 bytes at a well known offset.
26405  **
26406  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
26407  ** byte'.  If this is successful, a random byte from the 'shared byte
26408  ** range' is read-locked and the lock on the 'pending byte' released.
26409  **
26410  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
26411  ** A RESERVED lock is implemented by grabbing a write-lock on the
26412  ** 'reserved byte'.
26413  **
26414  ** A process may only obtain a PENDING lock after it has obtained a
26415  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
26416  ** on the 'pending byte'. This ensures that no new SHARED locks can be
26417  ** obtained, but existing SHARED locks are allowed to persist. A process
26418  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
26419  ** This property is used by the algorithm for rolling back a journal file
26420  ** after a crash.
26421  **
26422  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
26423  ** implemented by obtaining a write-lock on the entire 'shared byte
26424  ** range'. Since all other locks require a read-lock on one of the bytes
26425  ** within this range, this ensures that no other locks are held on the
26426  ** database.
26427  **
26428  ** The reason a single byte cannot be used instead of the 'shared byte
26429  ** range' is that some versions of windows do not support read-locks. By
26430  ** locking a random byte from a range, concurrent SHARED locks may exist
26431  ** even if the locking primitive used is always a write-lock.
26432  */
26433  int rc = SQLITE_OK;
26434  unixFile *pFile = (unixFile*)id;
26435  unixInodeInfo *pInode;
26436  struct flock lock;
26437  int tErrno = 0;
26438
26439  assert( pFile );
26440  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
26441      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26442      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
26443
26444  /* If there is already a lock of this type or more restrictive on the
26445  ** unixFile, do nothing. Don't use the end_lock: exit path, as
26446  ** unixEnterMutex() hasn't been called yet.
26447  */
26448  if( pFile->eFileLock>=eFileLock ){
26449    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
26450            azFileLock(eFileLock)));
26451    return SQLITE_OK;
26452  }
26453
26454  /* Make sure the locking sequence is correct.
26455  **  (1) We never move from unlocked to anything higher than shared lock.
26456  **  (2) SQLite never explicitly requests a pendig lock.
26457  **  (3) A shared lock is always held when a reserve lock is requested.
26458  */
26459  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26460  assert( eFileLock!=PENDING_LOCK );
26461  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26462
26463  /* This mutex is needed because pFile->pInode is shared across threads
26464  */
26465  unixEnterMutex();
26466  pInode = pFile->pInode;
26467
26468  /* If some thread using this PID has a lock via a different unixFile*
26469  ** handle that precludes the requested lock, return BUSY.
26470  */
26471  if( (pFile->eFileLock!=pInode->eFileLock &&
26472          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26473  ){
26474    rc = SQLITE_BUSY;
26475    goto end_lock;
26476  }
26477
26478  /* If a SHARED lock is requested, and some thread using this PID already
26479  ** has a SHARED or RESERVED lock, then increment reference counts and
26480  ** return SQLITE_OK.
26481  */
26482  if( eFileLock==SHARED_LOCK &&
26483      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26484    assert( eFileLock==SHARED_LOCK );
26485    assert( pFile->eFileLock==0 );
26486    assert( pInode->nShared>0 );
26487    pFile->eFileLock = SHARED_LOCK;
26488    pInode->nShared++;
26489    pInode->nLock++;
26490    goto end_lock;
26491  }
26492
26493
26494  /* A PENDING lock is needed before acquiring a SHARED lock and before
26495  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26496  ** be released.
26497  */
26498  lock.l_len = 1L;
26499  lock.l_whence = SEEK_SET;
26500  if( eFileLock==SHARED_LOCK
26501      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26502  ){
26503    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
26504    lock.l_start = PENDING_BYTE;
26505    if( unixFileLock(pFile, &lock) ){
26506      tErrno = errno;
26507      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26508      if( rc!=SQLITE_BUSY ){
26509        pFile->lastErrno = tErrno;
26510      }
26511      goto end_lock;
26512    }
26513  }
26514
26515
26516  /* If control gets to this point, then actually go ahead and make
26517  ** operating system calls for the specified lock.
26518  */
26519  if( eFileLock==SHARED_LOCK ){
26520    assert( pInode->nShared==0 );
26521    assert( pInode->eFileLock==0 );
26522    assert( rc==SQLITE_OK );
26523
26524    /* Now get the read-lock */
26525    lock.l_start = SHARED_FIRST;
26526    lock.l_len = SHARED_SIZE;
26527    if( unixFileLock(pFile, &lock) ){
26528      tErrno = errno;
26529      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26530    }
26531
26532    /* Drop the temporary PENDING lock */
26533    lock.l_start = PENDING_BYTE;
26534    lock.l_len = 1L;
26535    lock.l_type = F_UNLCK;
26536    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
26537      /* This could happen with a network mount */
26538      tErrno = errno;
26539      rc = SQLITE_IOERR_UNLOCK;
26540    }
26541
26542    if( rc ){
26543      if( rc!=SQLITE_BUSY ){
26544        pFile->lastErrno = tErrno;
26545      }
26546      goto end_lock;
26547    }else{
26548      pFile->eFileLock = SHARED_LOCK;
26549      pInode->nLock++;
26550      pInode->nShared = 1;
26551    }
26552  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26553    /* We are trying for an exclusive lock but another thread in this
26554    ** same process is still holding a shared lock. */
26555    rc = SQLITE_BUSY;
26556  }else{
26557    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
26558    ** assumed that there is a SHARED or greater lock on the file
26559    ** already.
26560    */
26561    assert( 0!=pFile->eFileLock );
26562    lock.l_type = F_WRLCK;
26563
26564    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
26565    if( eFileLock==RESERVED_LOCK ){
26566      lock.l_start = RESERVED_BYTE;
26567      lock.l_len = 1L;
26568    }else{
26569      lock.l_start = SHARED_FIRST;
26570      lock.l_len = SHARED_SIZE;
26571    }
26572
26573    if( unixFileLock(pFile, &lock) ){
26574      tErrno = errno;
26575      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26576      if( rc!=SQLITE_BUSY ){
26577        pFile->lastErrno = tErrno;
26578      }
26579    }
26580  }
26581
26582
26583#ifndef NDEBUG
26584  /* Set up the transaction-counter change checking flags when
26585  ** transitioning from a SHARED to a RESERVED lock.  The change
26586  ** from SHARED to RESERVED marks the beginning of a normal
26587  ** write operation (not a hot journal rollback).
26588  */
26589  if( rc==SQLITE_OK
26590   && pFile->eFileLock<=SHARED_LOCK
26591   && eFileLock==RESERVED_LOCK
26592  ){
26593    pFile->transCntrChng = 0;
26594    pFile->dbUpdate = 0;
26595    pFile->inNormalWrite = 1;
26596  }
26597#endif
26598
26599
26600  if( rc==SQLITE_OK ){
26601    pFile->eFileLock = eFileLock;
26602    pInode->eFileLock = eFileLock;
26603  }else if( eFileLock==EXCLUSIVE_LOCK ){
26604    pFile->eFileLock = PENDING_LOCK;
26605    pInode->eFileLock = PENDING_LOCK;
26606  }
26607
26608end_lock:
26609  unixLeaveMutex();
26610  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
26611      rc==SQLITE_OK ? "ok" : "failed"));
26612  return rc;
26613}
26614
26615/*
26616** Add the file descriptor used by file handle pFile to the corresponding
26617** pUnused list.
26618*/
26619static void setPendingFd(unixFile *pFile){
26620  unixInodeInfo *pInode = pFile->pInode;
26621  UnixUnusedFd *p = pFile->pUnused;
26622  p->pNext = pInode->pUnused;
26623  pInode->pUnused = p;
26624  pFile->h = -1;
26625  pFile->pUnused = 0;
26626}
26627
26628/*
26629** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26630** must be either NO_LOCK or SHARED_LOCK.
26631**
26632** If the locking level of the file descriptor is already at or below
26633** the requested locking level, this routine is a no-op.
26634**
26635** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
26636** the byte range is divided into 2 parts and the first part is unlocked then
26637** set to a read lock, then the other part is simply unlocked.  This works
26638** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
26639** remove the write lock on a region when a read lock is set.
26640*/
26641static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
26642  unixFile *pFile = (unixFile*)id;
26643  unixInodeInfo *pInode;
26644  struct flock lock;
26645  int rc = SQLITE_OK;
26646
26647  assert( pFile );
26648  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
26649      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26650      getpid()));
26651
26652  assert( eFileLock<=SHARED_LOCK );
26653  if( pFile->eFileLock<=eFileLock ){
26654    return SQLITE_OK;
26655  }
26656  unixEnterMutex();
26657  pInode = pFile->pInode;
26658  assert( pInode->nShared!=0 );
26659  if( pFile->eFileLock>SHARED_LOCK ){
26660    assert( pInode->eFileLock==pFile->eFileLock );
26661
26662#ifndef NDEBUG
26663    /* When reducing a lock such that other processes can start
26664    ** reading the database file again, make sure that the
26665    ** transaction counter was updated if any part of the database
26666    ** file changed.  If the transaction counter is not updated,
26667    ** other connections to the same file might not realize that
26668    ** the file has changed and hence might not know to flush their
26669    ** cache.  The use of a stale cache can lead to database corruption.
26670    */
26671    pFile->inNormalWrite = 0;
26672#endif
26673
26674    /* downgrading to a shared lock on NFS involves clearing the write lock
26675    ** before establishing the readlock - to avoid a race condition we downgrade
26676    ** the lock in 2 blocks, so that part of the range will be covered by a
26677    ** write lock until the rest is covered by a read lock:
26678    **  1:   [WWWWW]
26679    **  2:   [....W]
26680    **  3:   [RRRRW]
26681    **  4:   [RRRR.]
26682    */
26683    if( eFileLock==SHARED_LOCK ){
26684
26685#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
26686      (void)handleNFSUnlock;
26687      assert( handleNFSUnlock==0 );
26688#endif
26689#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26690      if( handleNFSUnlock ){
26691        int tErrno;               /* Error code from system call errors */
26692        off_t divSize = SHARED_SIZE - 1;
26693
26694        lock.l_type = F_UNLCK;
26695        lock.l_whence = SEEK_SET;
26696        lock.l_start = SHARED_FIRST;
26697        lock.l_len = divSize;
26698        if( unixFileLock(pFile, &lock)==(-1) ){
26699          tErrno = errno;
26700          rc = SQLITE_IOERR_UNLOCK;
26701          if( IS_LOCK_ERROR(rc) ){
26702            pFile->lastErrno = tErrno;
26703          }
26704          goto end_unlock;
26705        }
26706        lock.l_type = F_RDLCK;
26707        lock.l_whence = SEEK_SET;
26708        lock.l_start = SHARED_FIRST;
26709        lock.l_len = divSize;
26710        if( unixFileLock(pFile, &lock)==(-1) ){
26711          tErrno = errno;
26712          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
26713          if( IS_LOCK_ERROR(rc) ){
26714            pFile->lastErrno = tErrno;
26715          }
26716          goto end_unlock;
26717        }
26718        lock.l_type = F_UNLCK;
26719        lock.l_whence = SEEK_SET;
26720        lock.l_start = SHARED_FIRST+divSize;
26721        lock.l_len = SHARED_SIZE-divSize;
26722        if( unixFileLock(pFile, &lock)==(-1) ){
26723          tErrno = errno;
26724          rc = SQLITE_IOERR_UNLOCK;
26725          if( IS_LOCK_ERROR(rc) ){
26726            pFile->lastErrno = tErrno;
26727          }
26728          goto end_unlock;
26729        }
26730      }else
26731#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26732      {
26733        lock.l_type = F_RDLCK;
26734        lock.l_whence = SEEK_SET;
26735        lock.l_start = SHARED_FIRST;
26736        lock.l_len = SHARED_SIZE;
26737        if( unixFileLock(pFile, &lock) ){
26738          /* In theory, the call to unixFileLock() cannot fail because another
26739          ** process is holding an incompatible lock. If it does, this
26740          ** indicates that the other process is not following the locking
26741          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
26742          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
26743          ** an assert to fail). */
26744          rc = SQLITE_IOERR_RDLOCK;
26745          pFile->lastErrno = errno;
26746          goto end_unlock;
26747        }
26748      }
26749    }
26750    lock.l_type = F_UNLCK;
26751    lock.l_whence = SEEK_SET;
26752    lock.l_start = PENDING_BYTE;
26753    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
26754    if( unixFileLock(pFile, &lock)==0 ){
26755      pInode->eFileLock = SHARED_LOCK;
26756    }else{
26757      rc = SQLITE_IOERR_UNLOCK;
26758      pFile->lastErrno = errno;
26759      goto end_unlock;
26760    }
26761  }
26762  if( eFileLock==NO_LOCK ){
26763    /* Decrement the shared lock counter.  Release the lock using an
26764    ** OS call only when all threads in this same process have released
26765    ** the lock.
26766    */
26767    pInode->nShared--;
26768    if( pInode->nShared==0 ){
26769      lock.l_type = F_UNLCK;
26770      lock.l_whence = SEEK_SET;
26771      lock.l_start = lock.l_len = 0L;
26772      if( unixFileLock(pFile, &lock)==0 ){
26773        pInode->eFileLock = NO_LOCK;
26774      }else{
26775        rc = SQLITE_IOERR_UNLOCK;
26776	pFile->lastErrno = errno;
26777        pInode->eFileLock = NO_LOCK;
26778        pFile->eFileLock = NO_LOCK;
26779      }
26780    }
26781
26782    /* Decrement the count of locks against this same file.  When the
26783    ** count reaches zero, close any other file descriptors whose close
26784    ** was deferred because of outstanding locks.
26785    */
26786    pInode->nLock--;
26787    assert( pInode->nLock>=0 );
26788    if( pInode->nLock==0 ){
26789      closePendingFds(pFile);
26790    }
26791  }
26792
26793end_unlock:
26794  unixLeaveMutex();
26795  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26796  return rc;
26797}
26798
26799/*
26800** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26801** must be either NO_LOCK or SHARED_LOCK.
26802**
26803** If the locking level of the file descriptor is already at or below
26804** the requested locking level, this routine is a no-op.
26805*/
26806static int unixUnlock(sqlite3_file *id, int eFileLock){
26807  return posixUnlock(id, eFileLock, 0);
26808}
26809
26810/*
26811** This function performs the parts of the "close file" operation
26812** common to all locking schemes. It closes the directory and file
26813** handles, if they are valid, and sets all fields of the unixFile
26814** structure to 0.
26815**
26816** It is *not* necessary to hold the mutex when this routine is called,
26817** even on VxWorks.  A mutex will be acquired on VxWorks by the
26818** vxworksReleaseFileId() routine.
26819*/
26820static int closeUnixFile(sqlite3_file *id){
26821  unixFile *pFile = (unixFile*)id;
26822  if( pFile->h>=0 ){
26823    robust_close(pFile, pFile->h, __LINE__);
26824    pFile->h = -1;
26825  }
26826#if OS_VXWORKS
26827  if( pFile->pId ){
26828    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
26829      osUnlink(pFile->pId->zCanonicalName);
26830    }
26831    vxworksReleaseFileId(pFile->pId);
26832    pFile->pId = 0;
26833  }
26834#endif
26835  OSTRACE(("CLOSE   %-3d\n", pFile->h));
26836  OpenCounter(-1);
26837  sqlite3_free(pFile->pUnused);
26838  memset(pFile, 0, sizeof(unixFile));
26839  return SQLITE_OK;
26840}
26841
26842/*
26843** Close a file.
26844*/
26845static int unixClose(sqlite3_file *id){
26846  int rc = SQLITE_OK;
26847  unixFile *pFile = (unixFile *)id;
26848  unixUnlock(id, NO_LOCK);
26849  unixEnterMutex();
26850
26851  /* unixFile.pInode is always valid here. Otherwise, a different close
26852  ** routine (e.g. nolockClose()) would be called instead.
26853  */
26854  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
26855  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
26856    /* If there are outstanding locks, do not actually close the file just
26857    ** yet because that would clear those locks.  Instead, add the file
26858    ** descriptor to pInode->pUnused list.  It will be automatically closed
26859    ** when the last lock is cleared.
26860    */
26861    setPendingFd(pFile);
26862  }
26863  releaseInodeInfo(pFile);
26864  rc = closeUnixFile(id);
26865  unixLeaveMutex();
26866  return rc;
26867}
26868
26869/************** End of the posix advisory lock implementation *****************
26870******************************************************************************/
26871
26872/******************************************************************************
26873****************************** No-op Locking **********************************
26874**
26875** Of the various locking implementations available, this is by far the
26876** simplest:  locking is ignored.  No attempt is made to lock the database
26877** file for reading or writing.
26878**
26879** This locking mode is appropriate for use on read-only databases
26880** (ex: databases that are burned into CD-ROM, for example.)  It can
26881** also be used if the application employs some external mechanism to
26882** prevent simultaneous access of the same database by two or more
26883** database connections.  But there is a serious risk of database
26884** corruption if this locking mode is used in situations where multiple
26885** database connections are accessing the same database file at the same
26886** time and one or more of those connections are writing.
26887*/
26888
26889static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
26890  UNUSED_PARAMETER(NotUsed);
26891  *pResOut = 0;
26892  return SQLITE_OK;
26893}
26894static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
26895  UNUSED_PARAMETER2(NotUsed, NotUsed2);
26896  return SQLITE_OK;
26897}
26898static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
26899  UNUSED_PARAMETER2(NotUsed, NotUsed2);
26900  return SQLITE_OK;
26901}
26902
26903/*
26904** Close the file.
26905*/
26906static int nolockClose(sqlite3_file *id) {
26907  return closeUnixFile(id);
26908}
26909
26910/******************* End of the no-op lock implementation *********************
26911******************************************************************************/
26912
26913/******************************************************************************
26914************************* Begin dot-file Locking ******************************
26915**
26916** The dotfile locking implementation uses the existance of separate lock
26917** files (really a directory) to control access to the database.  This works
26918** on just about every filesystem imaginable.  But there are serious downsides:
26919**
26920**    (1)  There is zero concurrency.  A single reader blocks all other
26921**         connections from reading or writing the database.
26922**
26923**    (2)  An application crash or power loss can leave stale lock files
26924**         sitting around that need to be cleared manually.
26925**
26926** Nevertheless, a dotlock is an appropriate locking mode for use if no
26927** other locking strategy is available.
26928**
26929** Dotfile locking works by creating a subdirectory in the same directory as
26930** the database and with the same name but with a ".lock" extension added.
26931** The existance of a lock directory implies an EXCLUSIVE lock.  All other
26932** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
26933*/
26934
26935/*
26936** The file suffix added to the data base filename in order to create the
26937** lock directory.
26938*/
26939#define DOTLOCK_SUFFIX ".lock"
26940
26941/*
26942** This routine checks if there is a RESERVED lock held on the specified
26943** file by this or any other process. If such a lock is held, set *pResOut
26944** to a non-zero value otherwise *pResOut is set to zero.  The return value
26945** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26946**
26947** In dotfile locking, either a lock exists or it does not.  So in this
26948** variation of CheckReservedLock(), *pResOut is set to true if any lock
26949** is held on the file and false if the file is unlocked.
26950*/
26951static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
26952  int rc = SQLITE_OK;
26953  int reserved = 0;
26954  unixFile *pFile = (unixFile*)id;
26955
26956  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26957
26958  assert( pFile );
26959
26960  /* Check if a thread in this process holds such a lock */
26961  if( pFile->eFileLock>SHARED_LOCK ){
26962    /* Either this connection or some other connection in the same process
26963    ** holds a lock on the file.  No need to check further. */
26964    reserved = 1;
26965  }else{
26966    /* The lock is held if and only if the lockfile exists */
26967    const char *zLockFile = (const char*)pFile->lockingContext;
26968    reserved = osAccess(zLockFile, 0)==0;
26969  }
26970  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26971  *pResOut = reserved;
26972  return rc;
26973}
26974
26975/*
26976** Lock the file with the lock specified by parameter eFileLock - one
26977** of the following:
26978**
26979**     (1) SHARED_LOCK
26980**     (2) RESERVED_LOCK
26981**     (3) PENDING_LOCK
26982**     (4) EXCLUSIVE_LOCK
26983**
26984** Sometimes when requesting one lock state, additional lock states
26985** are inserted in between.  The locking might fail on one of the later
26986** transitions leaving the lock state different from what it started but
26987** still short of its goal.  The following chart shows the allowed
26988** transitions and the inserted intermediate states:
26989**
26990**    UNLOCKED -> SHARED
26991**    SHARED -> RESERVED
26992**    SHARED -> (PENDING) -> EXCLUSIVE
26993**    RESERVED -> (PENDING) -> EXCLUSIVE
26994**    PENDING -> EXCLUSIVE
26995**
26996** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26997** routine to lower a locking level.
26998**
26999** With dotfile locking, we really only support state (4): EXCLUSIVE.
27000** But we track the other locking levels internally.
27001*/
27002static int dotlockLock(sqlite3_file *id, int eFileLock) {
27003  unixFile *pFile = (unixFile*)id;
27004  char *zLockFile = (char *)pFile->lockingContext;
27005  int rc = SQLITE_OK;
27006
27007
27008  /* If we have any lock, then the lock file already exists.  All we have
27009  ** to do is adjust our internal record of the lock level.
27010  */
27011  if( pFile->eFileLock > NO_LOCK ){
27012    pFile->eFileLock = eFileLock;
27013    /* Always update the timestamp on the old file */
27014#ifdef HAVE_UTIME
27015    utime(zLockFile, NULL);
27016#else
27017    utimes(zLockFile, NULL);
27018#endif
27019    return SQLITE_OK;
27020  }
27021
27022  /* grab an exclusive lock */
27023  rc = osMkdir(zLockFile, 0777);
27024  if( rc<0 ){
27025    /* failed to open/create the lock directory */
27026    int tErrno = errno;
27027    if( EEXIST == tErrno ){
27028      rc = SQLITE_BUSY;
27029    } else {
27030      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27031      if( IS_LOCK_ERROR(rc) ){
27032        pFile->lastErrno = tErrno;
27033      }
27034    }
27035    return rc;
27036  }
27037
27038  /* got it, set the type and return ok */
27039  pFile->eFileLock = eFileLock;
27040  return rc;
27041}
27042
27043/*
27044** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27045** must be either NO_LOCK or SHARED_LOCK.
27046**
27047** If the locking level of the file descriptor is already at or below
27048** the requested locking level, this routine is a no-op.
27049**
27050** When the locking level reaches NO_LOCK, delete the lock file.
27051*/
27052static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
27053  unixFile *pFile = (unixFile*)id;
27054  char *zLockFile = (char *)pFile->lockingContext;
27055  int rc;
27056
27057  assert( pFile );
27058  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
27059	   pFile->eFileLock, getpid()));
27060  assert( eFileLock<=SHARED_LOCK );
27061
27062  /* no-op if possible */
27063  if( pFile->eFileLock==eFileLock ){
27064    return SQLITE_OK;
27065  }
27066
27067  /* To downgrade to shared, simply update our internal notion of the
27068  ** lock state.  No need to mess with the file on disk.
27069  */
27070  if( eFileLock==SHARED_LOCK ){
27071    pFile->eFileLock = SHARED_LOCK;
27072    return SQLITE_OK;
27073  }
27074
27075  /* To fully unlock the database, delete the lock file */
27076  assert( eFileLock==NO_LOCK );
27077  rc = osRmdir(zLockFile);
27078  if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
27079  if( rc<0 ){
27080    int tErrno = errno;
27081    rc = 0;
27082    if( ENOENT != tErrno ){
27083      rc = SQLITE_IOERR_UNLOCK;
27084    }
27085    if( IS_LOCK_ERROR(rc) ){
27086      pFile->lastErrno = tErrno;
27087    }
27088    return rc;
27089  }
27090  pFile->eFileLock = NO_LOCK;
27091  return SQLITE_OK;
27092}
27093
27094/*
27095** Close a file.  Make sure the lock has been released before closing.
27096*/
27097static int dotlockClose(sqlite3_file *id) {
27098  int rc;
27099  if( id ){
27100    unixFile *pFile = (unixFile*)id;
27101    dotlockUnlock(id, NO_LOCK);
27102    sqlite3_free(pFile->lockingContext);
27103  }
27104  rc = closeUnixFile(id);
27105  return rc;
27106}
27107/****************** End of the dot-file lock implementation *******************
27108******************************************************************************/
27109
27110/******************************************************************************
27111************************** Begin flock Locking ********************************
27112**
27113** Use the flock() system call to do file locking.
27114**
27115** flock() locking is like dot-file locking in that the various
27116** fine-grain locking levels supported by SQLite are collapsed into
27117** a single exclusive lock.  In other words, SHARED, RESERVED, and
27118** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
27119** still works when you do this, but concurrency is reduced since
27120** only a single process can be reading the database at a time.
27121**
27122** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
27123** compiling for VXWORKS.
27124*/
27125#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27126
27127/*
27128** Retry flock() calls that fail with EINTR
27129*/
27130#ifdef EINTR
27131static int robust_flock(int fd, int op){
27132  int rc;
27133  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
27134  return rc;
27135}
27136#else
27137# define robust_flock(a,b) flock(a,b)
27138#endif
27139
27140
27141/*
27142** This routine checks if there is a RESERVED lock held on the specified
27143** file by this or any other process. If such a lock is held, set *pResOut
27144** to a non-zero value otherwise *pResOut is set to zero.  The return value
27145** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27146*/
27147static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
27148  int rc = SQLITE_OK;
27149  int reserved = 0;
27150  unixFile *pFile = (unixFile*)id;
27151
27152  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27153
27154  assert( pFile );
27155
27156  /* Check if a thread in this process holds such a lock */
27157  if( pFile->eFileLock>SHARED_LOCK ){
27158    reserved = 1;
27159  }
27160
27161  /* Otherwise see if some other process holds it. */
27162  if( !reserved ){
27163    /* attempt to get the lock */
27164    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
27165    if( !lrc ){
27166      /* got the lock, unlock it */
27167      lrc = robust_flock(pFile->h, LOCK_UN);
27168      if ( lrc ) {
27169        int tErrno = errno;
27170        /* unlock failed with an error */
27171        lrc = SQLITE_IOERR_UNLOCK;
27172        if( IS_LOCK_ERROR(lrc) ){
27173          pFile->lastErrno = tErrno;
27174          rc = lrc;
27175        }
27176      }
27177    } else {
27178      int tErrno = errno;
27179      reserved = 1;
27180      /* someone else might have it reserved */
27181      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27182      if( IS_LOCK_ERROR(lrc) ){
27183        pFile->lastErrno = tErrno;
27184        rc = lrc;
27185      }
27186    }
27187  }
27188  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
27189
27190#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27191  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27192    rc = SQLITE_OK;
27193    reserved=1;
27194  }
27195#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27196  *pResOut = reserved;
27197  return rc;
27198}
27199
27200/*
27201** Lock the file with the lock specified by parameter eFileLock - one
27202** of the following:
27203**
27204**     (1) SHARED_LOCK
27205**     (2) RESERVED_LOCK
27206**     (3) PENDING_LOCK
27207**     (4) EXCLUSIVE_LOCK
27208**
27209** Sometimes when requesting one lock state, additional lock states
27210** are inserted in between.  The locking might fail on one of the later
27211** transitions leaving the lock state different from what it started but
27212** still short of its goal.  The following chart shows the allowed
27213** transitions and the inserted intermediate states:
27214**
27215**    UNLOCKED -> SHARED
27216**    SHARED -> RESERVED
27217**    SHARED -> (PENDING) -> EXCLUSIVE
27218**    RESERVED -> (PENDING) -> EXCLUSIVE
27219**    PENDING -> EXCLUSIVE
27220**
27221** flock() only really support EXCLUSIVE locks.  We track intermediate
27222** lock states in the sqlite3_file structure, but all locks SHARED or
27223** above are really EXCLUSIVE locks and exclude all other processes from
27224** access the file.
27225**
27226** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27227** routine to lower a locking level.
27228*/
27229static int flockLock(sqlite3_file *id, int eFileLock) {
27230  int rc = SQLITE_OK;
27231  unixFile *pFile = (unixFile*)id;
27232
27233  assert( pFile );
27234
27235  /* if we already have a lock, it is exclusive.
27236  ** Just adjust level and punt on outta here. */
27237  if (pFile->eFileLock > NO_LOCK) {
27238    pFile->eFileLock = eFileLock;
27239    return SQLITE_OK;
27240  }
27241
27242  /* grab an exclusive lock */
27243
27244  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
27245    int tErrno = errno;
27246    /* didn't get, must be busy */
27247    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27248    if( IS_LOCK_ERROR(rc) ){
27249      pFile->lastErrno = tErrno;
27250    }
27251  } else {
27252    /* got it, set the type and return ok */
27253    pFile->eFileLock = eFileLock;
27254  }
27255  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
27256           rc==SQLITE_OK ? "ok" : "failed"));
27257#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27258  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27259    rc = SQLITE_BUSY;
27260  }
27261#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27262  return rc;
27263}
27264
27265
27266/*
27267** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27268** must be either NO_LOCK or SHARED_LOCK.
27269**
27270** If the locking level of the file descriptor is already at or below
27271** the requested locking level, this routine is a no-op.
27272*/
27273static int flockUnlock(sqlite3_file *id, int eFileLock) {
27274  unixFile *pFile = (unixFile*)id;
27275
27276  assert( pFile );
27277  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
27278           pFile->eFileLock, getpid()));
27279  assert( eFileLock<=SHARED_LOCK );
27280
27281  /* no-op if possible */
27282  if( pFile->eFileLock==eFileLock ){
27283    return SQLITE_OK;
27284  }
27285
27286  /* shared can just be set because we always have an exclusive */
27287  if (eFileLock==SHARED_LOCK) {
27288    pFile->eFileLock = eFileLock;
27289    return SQLITE_OK;
27290  }
27291
27292  /* no, really, unlock. */
27293  if( robust_flock(pFile->h, LOCK_UN) ){
27294#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27295    return SQLITE_OK;
27296#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27297    return SQLITE_IOERR_UNLOCK;
27298  }else{
27299    pFile->eFileLock = NO_LOCK;
27300    return SQLITE_OK;
27301  }
27302}
27303
27304/*
27305** Close a file.
27306*/
27307static int flockClose(sqlite3_file *id) {
27308  if( id ){
27309    flockUnlock(id, NO_LOCK);
27310  }
27311  return closeUnixFile(id);
27312}
27313
27314#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
27315
27316/******************* End of the flock lock implementation *********************
27317******************************************************************************/
27318
27319/******************************************************************************
27320************************ Begin Named Semaphore Locking ************************
27321**
27322** Named semaphore locking is only supported on VxWorks.
27323**
27324** Semaphore locking is like dot-lock and flock in that it really only
27325** supports EXCLUSIVE locking.  Only a single process can read or write
27326** the database file at a time.  This reduces potential concurrency, but
27327** makes the lock implementation much easier.
27328*/
27329#if OS_VXWORKS
27330
27331/*
27332** This routine checks if there is a RESERVED lock held on the specified
27333** file by this or any other process. If such a lock is held, set *pResOut
27334** to a non-zero value otherwise *pResOut is set to zero.  The return value
27335** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27336*/
27337static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
27338  int rc = SQLITE_OK;
27339  int reserved = 0;
27340  unixFile *pFile = (unixFile*)id;
27341
27342  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27343
27344  assert( pFile );
27345
27346  /* Check if a thread in this process holds such a lock */
27347  if( pFile->eFileLock>SHARED_LOCK ){
27348    reserved = 1;
27349  }
27350
27351  /* Otherwise see if some other process holds it. */
27352  if( !reserved ){
27353    sem_t *pSem = pFile->pInode->pSem;
27354    struct stat statBuf;
27355
27356    if( sem_trywait(pSem)==-1 ){
27357      int tErrno = errno;
27358      if( EAGAIN != tErrno ){
27359        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
27360        pFile->lastErrno = tErrno;
27361      } else {
27362        /* someone else has the lock when we are in NO_LOCK */
27363        reserved = (pFile->eFileLock < SHARED_LOCK);
27364      }
27365    }else{
27366      /* we could have it if we want it */
27367      sem_post(pSem);
27368    }
27369  }
27370  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
27371
27372  *pResOut = reserved;
27373  return rc;
27374}
27375
27376/*
27377** Lock the file with the lock specified by parameter eFileLock - one
27378** of the following:
27379**
27380**     (1) SHARED_LOCK
27381**     (2) RESERVED_LOCK
27382**     (3) PENDING_LOCK
27383**     (4) EXCLUSIVE_LOCK
27384**
27385** Sometimes when requesting one lock state, additional lock states
27386** are inserted in between.  The locking might fail on one of the later
27387** transitions leaving the lock state different from what it started but
27388** still short of its goal.  The following chart shows the allowed
27389** transitions and the inserted intermediate states:
27390**
27391**    UNLOCKED -> SHARED
27392**    SHARED -> RESERVED
27393**    SHARED -> (PENDING) -> EXCLUSIVE
27394**    RESERVED -> (PENDING) -> EXCLUSIVE
27395**    PENDING -> EXCLUSIVE
27396**
27397** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
27398** lock states in the sqlite3_file structure, but all locks SHARED or
27399** above are really EXCLUSIVE locks and exclude all other processes from
27400** access the file.
27401**
27402** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27403** routine to lower a locking level.
27404*/
27405static int semLock(sqlite3_file *id, int eFileLock) {
27406  unixFile *pFile = (unixFile*)id;
27407  int fd;
27408  sem_t *pSem = pFile->pInode->pSem;
27409  int rc = SQLITE_OK;
27410
27411  /* if we already have a lock, it is exclusive.
27412  ** Just adjust level and punt on outta here. */
27413  if (pFile->eFileLock > NO_LOCK) {
27414    pFile->eFileLock = eFileLock;
27415    rc = SQLITE_OK;
27416    goto sem_end_lock;
27417  }
27418
27419  /* lock semaphore now but bail out when already locked. */
27420  if( sem_trywait(pSem)==-1 ){
27421    rc = SQLITE_BUSY;
27422    goto sem_end_lock;
27423  }
27424
27425  /* got it, set the type and return ok */
27426  pFile->eFileLock = eFileLock;
27427
27428 sem_end_lock:
27429  return rc;
27430}
27431
27432/*
27433** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27434** must be either NO_LOCK or SHARED_LOCK.
27435**
27436** If the locking level of the file descriptor is already at or below
27437** the requested locking level, this routine is a no-op.
27438*/
27439static int semUnlock(sqlite3_file *id, int eFileLock) {
27440  unixFile *pFile = (unixFile*)id;
27441  sem_t *pSem = pFile->pInode->pSem;
27442
27443  assert( pFile );
27444  assert( pSem );
27445  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
27446	   pFile->eFileLock, getpid()));
27447  assert( eFileLock<=SHARED_LOCK );
27448
27449  /* no-op if possible */
27450  if( pFile->eFileLock==eFileLock ){
27451    return SQLITE_OK;
27452  }
27453
27454  /* shared can just be set because we always have an exclusive */
27455  if (eFileLock==SHARED_LOCK) {
27456    pFile->eFileLock = eFileLock;
27457    return SQLITE_OK;
27458  }
27459
27460  /* no, really unlock. */
27461  if ( sem_post(pSem)==-1 ) {
27462    int rc, tErrno = errno;
27463    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
27464    if( IS_LOCK_ERROR(rc) ){
27465      pFile->lastErrno = tErrno;
27466    }
27467    return rc;
27468  }
27469  pFile->eFileLock = NO_LOCK;
27470  return SQLITE_OK;
27471}
27472
27473/*
27474 ** Close a file.
27475 */
27476static int semClose(sqlite3_file *id) {
27477  if( id ){
27478    unixFile *pFile = (unixFile*)id;
27479    semUnlock(id, NO_LOCK);
27480    assert( pFile );
27481    unixEnterMutex();
27482    releaseInodeInfo(pFile);
27483    unixLeaveMutex();
27484    closeUnixFile(id);
27485  }
27486  return SQLITE_OK;
27487}
27488
27489#endif /* OS_VXWORKS */
27490/*
27491** Named semaphore locking is only available on VxWorks.
27492**
27493*************** End of the named semaphore lock implementation ****************
27494******************************************************************************/
27495
27496
27497/******************************************************************************
27498*************************** Begin AFP Locking *********************************
27499**
27500** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
27501** on Apple Macintosh computers - both OS9 and OSX.
27502**
27503** Third-party implementations of AFP are available.  But this code here
27504** only works on OSX.
27505*/
27506
27507#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27508/*
27509** The afpLockingContext structure contains all afp lock specific state
27510*/
27511typedef struct afpLockingContext afpLockingContext;
27512struct afpLockingContext {
27513  int reserved;
27514  const char *dbPath;             /* Name of the open file */
27515};
27516
27517struct ByteRangeLockPB2
27518{
27519  unsigned long long offset;        /* offset to first byte to lock */
27520  unsigned long long length;        /* nbr of bytes to lock */
27521  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
27522  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
27523  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
27524  int fd;                           /* file desc to assoc this lock with */
27525};
27526
27527#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
27528
27529/*
27530** This is a utility for setting or clearing a bit-range lock on an
27531** AFP filesystem.
27532**
27533** Return SQLITE_OK on success, SQLITE_BUSY on failure.
27534*/
27535static int afpSetLock(
27536  const char *path,              /* Name of the file to be locked or unlocked */
27537  unixFile *pFile,               /* Open file descriptor on path */
27538  unsigned long long offset,     /* First byte to be locked */
27539  unsigned long long length,     /* Number of bytes to lock */
27540  int setLockFlag                /* True to set lock.  False to clear lock */
27541){
27542  struct ByteRangeLockPB2 pb;
27543  int err;
27544
27545  pb.unLockFlag = setLockFlag ? 0 : 1;
27546  pb.startEndFlag = 0;
27547  pb.offset = offset;
27548  pb.length = length;
27549  pb.fd = pFile->h;
27550
27551  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
27552    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
27553    offset, length));
27554  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
27555  if ( err==-1 ) {
27556    int rc;
27557    int tErrno = errno;
27558    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
27559             path, tErrno, strerror(tErrno)));
27560#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
27561    rc = SQLITE_BUSY;
27562#else
27563    rc = sqliteErrorFromPosixError(tErrno,
27564                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
27565#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
27566    if( IS_LOCK_ERROR(rc) ){
27567      pFile->lastErrno = tErrno;
27568    }
27569    return rc;
27570  } else {
27571    return SQLITE_OK;
27572  }
27573}
27574
27575/*
27576** This routine checks if there is a RESERVED lock held on the specified
27577** file by this or any other process. If such a lock is held, set *pResOut
27578** to a non-zero value otherwise *pResOut is set to zero.  The return value
27579** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27580*/
27581static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
27582  int rc = SQLITE_OK;
27583  int reserved = 0;
27584  unixFile *pFile = (unixFile*)id;
27585  afpLockingContext *context;
27586
27587  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27588
27589  assert( pFile );
27590  context = (afpLockingContext *) pFile->lockingContext;
27591  if( context->reserved ){
27592    *pResOut = 1;
27593    return SQLITE_OK;
27594  }
27595  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
27596
27597  /* Check if a thread in this process holds such a lock */
27598  if( pFile->pInode->eFileLock>SHARED_LOCK ){
27599    reserved = 1;
27600  }
27601
27602  /* Otherwise see if some other process holds it.
27603   */
27604  if( !reserved ){
27605    /* lock the RESERVED byte */
27606    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27607    if( SQLITE_OK==lrc ){
27608      /* if we succeeded in taking the reserved lock, unlock it to restore
27609      ** the original state */
27610      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27611    } else {
27612      /* if we failed to get the lock then someone else must have it */
27613      reserved = 1;
27614    }
27615    if( IS_LOCK_ERROR(lrc) ){
27616      rc=lrc;
27617    }
27618  }
27619
27620  unixLeaveMutex();
27621  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
27622
27623  *pResOut = reserved;
27624  return rc;
27625}
27626
27627/*
27628** Lock the file with the lock specified by parameter eFileLock - one
27629** of the following:
27630**
27631**     (1) SHARED_LOCK
27632**     (2) RESERVED_LOCK
27633**     (3) PENDING_LOCK
27634**     (4) EXCLUSIVE_LOCK
27635**
27636** Sometimes when requesting one lock state, additional lock states
27637** are inserted in between.  The locking might fail on one of the later
27638** transitions leaving the lock state different from what it started but
27639** still short of its goal.  The following chart shows the allowed
27640** transitions and the inserted intermediate states:
27641**
27642**    UNLOCKED -> SHARED
27643**    SHARED -> RESERVED
27644**    SHARED -> (PENDING) -> EXCLUSIVE
27645**    RESERVED -> (PENDING) -> EXCLUSIVE
27646**    PENDING -> EXCLUSIVE
27647**
27648** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27649** routine to lower a locking level.
27650*/
27651static int afpLock(sqlite3_file *id, int eFileLock){
27652  int rc = SQLITE_OK;
27653  unixFile *pFile = (unixFile*)id;
27654  unixInodeInfo *pInode = pFile->pInode;
27655  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27656
27657  assert( pFile );
27658  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
27659           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
27660           azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
27661
27662  /* If there is already a lock of this type or more restrictive on the
27663  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
27664  ** unixEnterMutex() hasn't been called yet.
27665  */
27666  if( pFile->eFileLock>=eFileLock ){
27667    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
27668           azFileLock(eFileLock)));
27669    return SQLITE_OK;
27670  }
27671
27672  /* Make sure the locking sequence is correct
27673  **  (1) We never move from unlocked to anything higher than shared lock.
27674  **  (2) SQLite never explicitly requests a pendig lock.
27675  **  (3) A shared lock is always held when a reserve lock is requested.
27676  */
27677  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
27678  assert( eFileLock!=PENDING_LOCK );
27679  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
27680
27681  /* This mutex is needed because pFile->pInode is shared across threads
27682  */
27683  unixEnterMutex();
27684  pInode = pFile->pInode;
27685
27686  /* If some thread using this PID has a lock via a different unixFile*
27687  ** handle that precludes the requested lock, return BUSY.
27688  */
27689  if( (pFile->eFileLock!=pInode->eFileLock &&
27690       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
27691     ){
27692    rc = SQLITE_BUSY;
27693    goto afp_end_lock;
27694  }
27695
27696  /* If a SHARED lock is requested, and some thread using this PID already
27697  ** has a SHARED or RESERVED lock, then increment reference counts and
27698  ** return SQLITE_OK.
27699  */
27700  if( eFileLock==SHARED_LOCK &&
27701     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
27702    assert( eFileLock==SHARED_LOCK );
27703    assert( pFile->eFileLock==0 );
27704    assert( pInode->nShared>0 );
27705    pFile->eFileLock = SHARED_LOCK;
27706    pInode->nShared++;
27707    pInode->nLock++;
27708    goto afp_end_lock;
27709  }
27710
27711  /* A PENDING lock is needed before acquiring a SHARED lock and before
27712  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
27713  ** be released.
27714  */
27715  if( eFileLock==SHARED_LOCK
27716      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
27717  ){
27718    int failed;
27719    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
27720    if (failed) {
27721      rc = failed;
27722      goto afp_end_lock;
27723    }
27724  }
27725
27726  /* If control gets to this point, then actually go ahead and make
27727  ** operating system calls for the specified lock.
27728  */
27729  if( eFileLock==SHARED_LOCK ){
27730    int lrc1, lrc2, lrc1Errno = 0;
27731    long lk, mask;
27732
27733    assert( pInode->nShared==0 );
27734    assert( pInode->eFileLock==0 );
27735
27736    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
27737    /* Now get the read-lock SHARED_LOCK */
27738    /* note that the quality of the randomness doesn't matter that much */
27739    lk = random();
27740    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
27741    lrc1 = afpSetLock(context->dbPath, pFile,
27742          SHARED_FIRST+pInode->sharedByte, 1, 1);
27743    if( IS_LOCK_ERROR(lrc1) ){
27744      lrc1Errno = pFile->lastErrno;
27745    }
27746    /* Drop the temporary PENDING lock */
27747    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27748
27749    if( IS_LOCK_ERROR(lrc1) ) {
27750      pFile->lastErrno = lrc1Errno;
27751      rc = lrc1;
27752      goto afp_end_lock;
27753    } else if( IS_LOCK_ERROR(lrc2) ){
27754      rc = lrc2;
27755      goto afp_end_lock;
27756    } else if( lrc1 != SQLITE_OK ) {
27757      rc = lrc1;
27758    } else {
27759      pFile->eFileLock = SHARED_LOCK;
27760      pInode->nLock++;
27761      pInode->nShared = 1;
27762    }
27763  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27764    /* We are trying for an exclusive lock but another thread in this
27765     ** same process is still holding a shared lock. */
27766    rc = SQLITE_BUSY;
27767  }else{
27768    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
27769    ** assumed that there is a SHARED or greater lock on the file
27770    ** already.
27771    */
27772    int failed = 0;
27773    assert( 0!=pFile->eFileLock );
27774    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
27775        /* Acquire a RESERVED lock */
27776        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27777      if( !failed ){
27778        context->reserved = 1;
27779      }
27780    }
27781    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
27782      /* Acquire an EXCLUSIVE lock */
27783
27784      /* Remove the shared lock before trying the range.  we'll need to
27785      ** reestablish the shared lock if we can't get the  afpUnlock
27786      */
27787      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
27788                         pInode->sharedByte, 1, 0)) ){
27789        int failed2 = SQLITE_OK;
27790        /* now attemmpt to get the exclusive lock range */
27791        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
27792                               SHARED_SIZE, 1);
27793        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
27794                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
27795          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
27796          ** a critical I/O error
27797          */
27798          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
27799               SQLITE_IOERR_LOCK;
27800          goto afp_end_lock;
27801        }
27802      }else{
27803        rc = failed;
27804      }
27805    }
27806    if( failed ){
27807      rc = failed;
27808    }
27809  }
27810
27811  if( rc==SQLITE_OK ){
27812    pFile->eFileLock = eFileLock;
27813    pInode->eFileLock = eFileLock;
27814  }else if( eFileLock==EXCLUSIVE_LOCK ){
27815    pFile->eFileLock = PENDING_LOCK;
27816    pInode->eFileLock = PENDING_LOCK;
27817  }
27818
27819afp_end_lock:
27820  unixLeaveMutex();
27821  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
27822         rc==SQLITE_OK ? "ok" : "failed"));
27823  return rc;
27824}
27825
27826/*
27827** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27828** must be either NO_LOCK or SHARED_LOCK.
27829**
27830** If the locking level of the file descriptor is already at or below
27831** the requested locking level, this routine is a no-op.
27832*/
27833static int afpUnlock(sqlite3_file *id, int eFileLock) {
27834  int rc = SQLITE_OK;
27835  unixFile *pFile = (unixFile*)id;
27836  unixInodeInfo *pInode;
27837  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27838  int skipShared = 0;
27839#ifdef SQLITE_TEST
27840  int h = pFile->h;
27841#endif
27842
27843  assert( pFile );
27844  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
27845           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
27846           getpid()));
27847
27848  assert( eFileLock<=SHARED_LOCK );
27849  if( pFile->eFileLock<=eFileLock ){
27850    return SQLITE_OK;
27851  }
27852  unixEnterMutex();
27853  pInode = pFile->pInode;
27854  assert( pInode->nShared!=0 );
27855  if( pFile->eFileLock>SHARED_LOCK ){
27856    assert( pInode->eFileLock==pFile->eFileLock );
27857    SimulateIOErrorBenign(1);
27858    SimulateIOError( h=(-1) )
27859    SimulateIOErrorBenign(0);
27860
27861#ifndef NDEBUG
27862    /* When reducing a lock such that other processes can start
27863    ** reading the database file again, make sure that the
27864    ** transaction counter was updated if any part of the database
27865    ** file changed.  If the transaction counter is not updated,
27866    ** other connections to the same file might not realize that
27867    ** the file has changed and hence might not know to flush their
27868    ** cache.  The use of a stale cache can lead to database corruption.
27869    */
27870    assert( pFile->inNormalWrite==0
27871           || pFile->dbUpdate==0
27872           || pFile->transCntrChng==1 );
27873    pFile->inNormalWrite = 0;
27874#endif
27875
27876    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
27877      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
27878      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
27879        /* only re-establish the shared lock if necessary */
27880        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27881        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
27882      } else {
27883        skipShared = 1;
27884      }
27885    }
27886    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
27887      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27888    }
27889    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
27890      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27891      if( !rc ){
27892        context->reserved = 0;
27893      }
27894    }
27895    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
27896      pInode->eFileLock = SHARED_LOCK;
27897    }
27898  }
27899  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
27900
27901    /* Decrement the shared lock counter.  Release the lock using an
27902    ** OS call only when all threads in this same process have released
27903    ** the lock.
27904    */
27905    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27906    pInode->nShared--;
27907    if( pInode->nShared==0 ){
27908      SimulateIOErrorBenign(1);
27909      SimulateIOError( h=(-1) )
27910      SimulateIOErrorBenign(0);
27911      if( !skipShared ){
27912        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
27913      }
27914      if( !rc ){
27915        pInode->eFileLock = NO_LOCK;
27916        pFile->eFileLock = NO_LOCK;
27917      }
27918    }
27919    if( rc==SQLITE_OK ){
27920      pInode->nLock--;
27921      assert( pInode->nLock>=0 );
27922      if( pInode->nLock==0 ){
27923        closePendingFds(pFile);
27924      }
27925    }
27926  }
27927
27928  unixLeaveMutex();
27929  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
27930  return rc;
27931}
27932
27933/*
27934** Close a file & cleanup AFP specific locking context
27935*/
27936static int afpClose(sqlite3_file *id) {
27937  int rc = SQLITE_OK;
27938  if( id ){
27939    unixFile *pFile = (unixFile*)id;
27940    afpUnlock(id, NO_LOCK);
27941    unixEnterMutex();
27942    if( pFile->pInode && pFile->pInode->nLock ){
27943      /* If there are outstanding locks, do not actually close the file just
27944      ** yet because that would clear those locks.  Instead, add the file
27945      ** descriptor to pInode->aPending.  It will be automatically closed when
27946      ** the last lock is cleared.
27947      */
27948      setPendingFd(pFile);
27949    }
27950    releaseInodeInfo(pFile);
27951    sqlite3_free(pFile->lockingContext);
27952    rc = closeUnixFile(id);
27953    unixLeaveMutex();
27954  }
27955  return rc;
27956}
27957
27958#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27959/*
27960** The code above is the AFP lock implementation.  The code is specific
27961** to MacOSX and does not work on other unix platforms.  No alternative
27962** is available.  If you don't compile for a mac, then the "unix-afp"
27963** VFS is not available.
27964**
27965********************* End of the AFP lock implementation **********************
27966******************************************************************************/
27967
27968/******************************************************************************
27969*************************** Begin NFS Locking ********************************/
27970
27971#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27972/*
27973 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27974 ** must be either NO_LOCK or SHARED_LOCK.
27975 **
27976 ** If the locking level of the file descriptor is already at or below
27977 ** the requested locking level, this routine is a no-op.
27978 */
27979static int nfsUnlock(sqlite3_file *id, int eFileLock){
27980  return posixUnlock(id, eFileLock, 1);
27981}
27982
27983#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27984/*
27985** The code above is the NFS lock implementation.  The code is specific
27986** to MacOSX and does not work on other unix platforms.  No alternative
27987** is available.
27988**
27989********************* End of the NFS lock implementation **********************
27990******************************************************************************/
27991
27992/******************************************************************************
27993**************** Non-locking sqlite3_file methods *****************************
27994**
27995** The next division contains implementations for all methods of the
27996** sqlite3_file object other than the locking methods.  The locking
27997** methods were defined in divisions above (one locking method per
27998** division).  Those methods that are common to all locking modes
27999** are gather together into this division.
28000*/
28001
28002/*
28003** Seek to the offset passed as the second argument, then read cnt
28004** bytes into pBuf. Return the number of bytes actually read.
28005**
28006** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
28007** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
28008** one system to another.  Since SQLite does not define USE_PREAD
28009** any any form by default, we will not attempt to define _XOPEN_SOURCE.
28010** See tickets #2741 and #2681.
28011**
28012** To avoid stomping the errno value on a failed read the lastErrno value
28013** is set before returning.
28014*/
28015static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
28016  int got;
28017  int prior = 0;
28018#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
28019  i64 newOffset;
28020#endif
28021  TIMER_START;
28022  do{
28023#if defined(USE_PREAD)
28024    got = osPread(id->h, pBuf, cnt, offset);
28025    SimulateIOError( got = -1 );
28026#elif defined(USE_PREAD64)
28027    got = osPread64(id->h, pBuf, cnt, offset);
28028    SimulateIOError( got = -1 );
28029#else
28030    newOffset = lseek(id->h, offset, SEEK_SET);
28031    SimulateIOError( newOffset-- );
28032    if( newOffset!=offset ){
28033      if( newOffset == -1 ){
28034        ((unixFile*)id)->lastErrno = errno;
28035      }else{
28036        ((unixFile*)id)->lastErrno = 0;
28037      }
28038      return -1;
28039    }
28040    got = osRead(id->h, pBuf, cnt);
28041#endif
28042    if( got==cnt ) break;
28043    if( got<0 ){
28044      if( errno==EINTR ){ got = 1; continue; }
28045      prior = 0;
28046      ((unixFile*)id)->lastErrno = errno;
28047      break;
28048    }else if( got>0 ){
28049      cnt -= got;
28050      offset += got;
28051      prior += got;
28052      pBuf = (void*)(got + (char*)pBuf);
28053    }
28054  }while( got>0 );
28055  TIMER_END;
28056  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
28057            id->h, got+prior, offset-prior, TIMER_ELAPSED));
28058  return got+prior;
28059}
28060
28061/*
28062** Read data from a file into a buffer.  Return SQLITE_OK if all
28063** bytes were read successfully and SQLITE_IOERR if anything goes
28064** wrong.
28065*/
28066static int unixRead(
28067  sqlite3_file *id,
28068  void *pBuf,
28069  int amt,
28070  sqlite3_int64 offset
28071){
28072  unixFile *pFile = (unixFile *)id;
28073  int got;
28074  assert( id );
28075
28076  /* If this is a database file (not a journal, master-journal or temp
28077  ** file), the bytes in the locking range should never be read or written. */
28078#if 0
28079  assert( pFile->pUnused==0
28080       || offset>=PENDING_BYTE+512
28081       || offset+amt<=PENDING_BYTE
28082  );
28083#endif
28084
28085  got = seekAndRead(pFile, offset, pBuf, amt);
28086  if( got==amt ){
28087    return SQLITE_OK;
28088  }else if( got<0 ){
28089    /* lastErrno set by seekAndRead */
28090    return SQLITE_IOERR_READ;
28091  }else{
28092    pFile->lastErrno = 0; /* not a system error */
28093    /* Unread parts of the buffer must be zero-filled */
28094    memset(&((char*)pBuf)[got], 0, amt-got);
28095    return SQLITE_IOERR_SHORT_READ;
28096  }
28097}
28098
28099/*
28100** Seek to the offset in id->offset then read cnt bytes into pBuf.
28101** Return the number of bytes actually read.  Update the offset.
28102**
28103** To avoid stomping the errno value on a failed write the lastErrno value
28104** is set before returning.
28105*/
28106static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
28107  int got;
28108#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
28109  i64 newOffset;
28110#endif
28111  TIMER_START;
28112#if defined(USE_PREAD)
28113  do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
28114#elif defined(USE_PREAD64)
28115  do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
28116#else
28117  do{
28118    newOffset = lseek(id->h, offset, SEEK_SET);
28119    SimulateIOError( newOffset-- );
28120    if( newOffset!=offset ){
28121      if( newOffset == -1 ){
28122        ((unixFile*)id)->lastErrno = errno;
28123      }else{
28124        ((unixFile*)id)->lastErrno = 0;
28125      }
28126      return -1;
28127    }
28128    got = osWrite(id->h, pBuf, cnt);
28129  }while( got<0 && errno==EINTR );
28130#endif
28131  TIMER_END;
28132  if( got<0 ){
28133    ((unixFile*)id)->lastErrno = errno;
28134  }
28135
28136  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
28137  return got;
28138}
28139
28140
28141/*
28142** Write data from a buffer into a file.  Return SQLITE_OK on success
28143** or some other error code on failure.
28144*/
28145static int unixWrite(
28146  sqlite3_file *id,
28147  const void *pBuf,
28148  int amt,
28149  sqlite3_int64 offset
28150){
28151  unixFile *pFile = (unixFile*)id;
28152  int wrote = 0;
28153  assert( id );
28154  assert( amt>0 );
28155
28156  /* If this is a database file (not a journal, master-journal or temp
28157  ** file), the bytes in the locking range should never be read or written. */
28158#if 0
28159  assert( pFile->pUnused==0
28160       || offset>=PENDING_BYTE+512
28161       || offset+amt<=PENDING_BYTE
28162  );
28163#endif
28164
28165#ifndef NDEBUG
28166  /* If we are doing a normal write to a database file (as opposed to
28167  ** doing a hot-journal rollback or a write to some file other than a
28168  ** normal database file) then record the fact that the database
28169  ** has changed.  If the transaction counter is modified, record that
28170  ** fact too.
28171  */
28172  if( pFile->inNormalWrite ){
28173    pFile->dbUpdate = 1;  /* The database has been modified */
28174    if( offset<=24 && offset+amt>=27 ){
28175      int rc;
28176      char oldCntr[4];
28177      SimulateIOErrorBenign(1);
28178      rc = seekAndRead(pFile, 24, oldCntr, 4);
28179      SimulateIOErrorBenign(0);
28180      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
28181        pFile->transCntrChng = 1;  /* The transaction counter has changed */
28182      }
28183    }
28184  }
28185#endif
28186
28187  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
28188    amt -= wrote;
28189    offset += wrote;
28190    pBuf = &((char*)pBuf)[wrote];
28191  }
28192  SimulateIOError(( wrote=(-1), amt=1 ));
28193  SimulateDiskfullError(( wrote=0, amt=1 ));
28194
28195  if( amt>0 ){
28196    if( wrote<0 && pFile->lastErrno!=ENOSPC ){
28197      /* lastErrno set by seekAndWrite */
28198      return SQLITE_IOERR_WRITE;
28199    }else{
28200      pFile->lastErrno = 0; /* not a system error */
28201      return SQLITE_FULL;
28202    }
28203  }
28204
28205  return SQLITE_OK;
28206}
28207
28208#ifdef SQLITE_TEST
28209/*
28210** Count the number of fullsyncs and normal syncs.  This is used to test
28211** that syncs and fullsyncs are occurring at the right times.
28212*/
28213SQLITE_API int sqlite3_sync_count = 0;
28214SQLITE_API int sqlite3_fullsync_count = 0;
28215#endif
28216
28217/*
28218** We do not trust systems to provide a working fdatasync().  Some do.
28219** Others do no.  To be safe, we will stick with the (slightly slower)
28220** fsync(). If you know that your system does support fdatasync() correctly,
28221** then simply compile with -Dfdatasync=fdatasync
28222*/
28223#if !defined(fdatasync)
28224# define fdatasync fsync
28225#endif
28226
28227/*
28228** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
28229** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
28230** only available on Mac OS X.  But that could change.
28231*/
28232#ifdef F_FULLFSYNC
28233# define HAVE_FULLFSYNC 1
28234#else
28235# define HAVE_FULLFSYNC 0
28236#endif
28237
28238
28239/*
28240** The fsync() system call does not work as advertised on many
28241** unix systems.  The following procedure is an attempt to make
28242** it work better.
28243**
28244** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
28245** for testing when we want to run through the test suite quickly.
28246** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
28247** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
28248** or power failure will likely corrupt the database file.
28249**
28250** SQLite sets the dataOnly flag if the size of the file is unchanged.
28251** The idea behind dataOnly is that it should only write the file content
28252** to disk, not the inode.  We only set dataOnly if the file size is
28253** unchanged since the file size is part of the inode.  However,
28254** Ted Ts'o tells us that fdatasync() will also write the inode if the
28255** file size has changed.  The only real difference between fdatasync()
28256** and fsync(), Ted tells us, is that fdatasync() will not flush the
28257** inode if the mtime or owner or other inode attributes have changed.
28258** We only care about the file size, not the other file attributes, so
28259** as far as SQLite is concerned, an fdatasync() is always adequate.
28260** So, we always use fdatasync() if it is available, regardless of
28261** the value of the dataOnly flag.
28262*/
28263static int full_fsync(int fd, int fullSync, int dataOnly){
28264  int rc;
28265
28266  /* The following "ifdef/elif/else/" block has the same structure as
28267  ** the one below. It is replicated here solely to avoid cluttering
28268  ** up the real code with the UNUSED_PARAMETER() macros.
28269  */
28270#ifdef SQLITE_NO_SYNC
28271  UNUSED_PARAMETER(fd);
28272  UNUSED_PARAMETER(fullSync);
28273  UNUSED_PARAMETER(dataOnly);
28274#elif HAVE_FULLFSYNC
28275  UNUSED_PARAMETER(dataOnly);
28276#else
28277  UNUSED_PARAMETER(fullSync);
28278  UNUSED_PARAMETER(dataOnly);
28279#endif
28280
28281  /* Record the number of times that we do a normal fsync() and
28282  ** FULLSYNC.  This is used during testing to verify that this procedure
28283  ** gets called with the correct arguments.
28284  */
28285#ifdef SQLITE_TEST
28286  if( fullSync ) sqlite3_fullsync_count++;
28287  sqlite3_sync_count++;
28288#endif
28289
28290  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28291  ** no-op
28292  */
28293#ifdef SQLITE_NO_SYNC
28294  rc = SQLITE_OK;
28295#elif HAVE_FULLFSYNC
28296  if( fullSync ){
28297    rc = osFcntl(fd, F_FULLFSYNC, 0);
28298  }else{
28299    rc = 1;
28300  }
28301  /* If the FULLFSYNC failed, fall back to attempting an fsync().
28302  ** It shouldn't be possible for fullfsync to fail on the local
28303  ** file system (on OSX), so failure indicates that FULLFSYNC
28304  ** isn't supported for this file system. So, attempt an fsync
28305  ** and (for now) ignore the overhead of a superfluous fcntl call.
28306  ** It'd be better to detect fullfsync support once and avoid
28307  ** the fcntl call every time sync is called.
28308  */
28309  if( rc ) rc = fsync(fd);
28310
28311#elif defined(__APPLE__)
28312  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
28313  ** so currently we default to the macro that redefines fdatasync to fsync
28314  */
28315  rc = fsync(fd);
28316#else
28317  rc = fdatasync(fd);
28318#if OS_VXWORKS
28319  if( rc==-1 && errno==ENOTSUP ){
28320    rc = fsync(fd);
28321  }
28322#endif /* OS_VXWORKS */
28323#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
28324
28325  if( OS_VXWORKS && rc!= -1 ){
28326    rc = 0;
28327  }
28328  return rc;
28329}
28330
28331/*
28332** Open a file descriptor to the directory containing file zFilename.
28333** If successful, *pFd is set to the opened file descriptor and
28334** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
28335** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
28336** value.
28337**
28338** The directory file descriptor is used for only one thing - to
28339** fsync() a directory to make sure file creation and deletion events
28340** are flushed to disk.  Such fsyncs are not needed on newer
28341** journaling filesystems, but are required on older filesystems.
28342**
28343** This routine can be overridden using the xSetSysCall interface.
28344** The ability to override this routine was added in support of the
28345** chromium sandbox.  Opening a directory is a security risk (we are
28346** told) so making it overrideable allows the chromium sandbox to
28347** replace this routine with a harmless no-op.  To make this routine
28348** a no-op, replace it with a stub that returns SQLITE_OK but leaves
28349** *pFd set to a negative number.
28350**
28351** If SQLITE_OK is returned, the caller is responsible for closing
28352** the file descriptor *pFd using close().
28353*/
28354static int openDirectory(const char *zFilename, int *pFd){
28355  int ii;
28356  int fd = -1;
28357  char zDirname[MAX_PATHNAME+1];
28358
28359  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
28360  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
28361  if( ii>0 ){
28362    zDirname[ii] = '\0';
28363    fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
28364    if( fd>=0 ){
28365#ifdef FD_CLOEXEC
28366      osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
28367#endif
28368      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
28369    }
28370  }
28371  *pFd = fd;
28372  return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
28373}
28374
28375/*
28376** Make sure all writes to a particular file are committed to disk.
28377**
28378** If dataOnly==0 then both the file itself and its metadata (file
28379** size, access time, etc) are synced.  If dataOnly!=0 then only the
28380** file data is synced.
28381**
28382** Under Unix, also make sure that the directory entry for the file
28383** has been created by fsync-ing the directory that contains the file.
28384** If we do not do this and we encounter a power failure, the directory
28385** entry for the journal might not exist after we reboot.  The next
28386** SQLite to access the file will not know that the journal exists (because
28387** the directory entry for the journal was never created) and the transaction
28388** will not roll back - possibly leading to database corruption.
28389*/
28390static int unixSync(sqlite3_file *id, int flags){
28391  int rc;
28392  unixFile *pFile = (unixFile*)id;
28393
28394  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
28395  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
28396
28397  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
28398  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
28399      || (flags&0x0F)==SQLITE_SYNC_FULL
28400  );
28401
28402  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
28403  ** line is to test that doing so does not cause any problems.
28404  */
28405  SimulateDiskfullError( return SQLITE_FULL );
28406
28407  assert( pFile );
28408  OSTRACE(("SYNC    %-3d\n", pFile->h));
28409  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
28410  SimulateIOError( rc=1 );
28411  if( rc ){
28412    pFile->lastErrno = errno;
28413    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
28414  }
28415
28416  /* Also fsync the directory containing the file if the DIRSYNC flag
28417  ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
28418  ** are unable to fsync a directory, so ignore errors on the fsync.
28419  */
28420  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
28421    int dirfd;
28422    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
28423            HAVE_FULLFSYNC, isFullsync));
28424    rc = osOpenDirectory(pFile->zPath, &dirfd);
28425    if( rc==SQLITE_OK && dirfd>=0 ){
28426      full_fsync(dirfd, 0, 0);
28427      robust_close(pFile, dirfd, __LINE__);
28428    }else if( rc==SQLITE_CANTOPEN ){
28429      rc = SQLITE_OK;
28430    }
28431    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
28432  }
28433  return rc;
28434}
28435
28436/*
28437** Truncate an open file to a specified size
28438*/
28439static int unixTruncate(sqlite3_file *id, i64 nByte){
28440  unixFile *pFile = (unixFile *)id;
28441  int rc;
28442  assert( pFile );
28443  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
28444
28445  /* If the user has configured a chunk-size for this file, truncate the
28446  ** file so that it consists of an integer number of chunks (i.e. the
28447  ** actual file size after the operation may be larger than the requested
28448  ** size).
28449  */
28450  if( pFile->szChunk ){
28451    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
28452  }
28453
28454  rc = robust_ftruncate(pFile->h, (off_t)nByte);
28455  if( rc ){
28456    pFile->lastErrno = errno;
28457    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28458  }else{
28459#ifndef NDEBUG
28460    /* If we are doing a normal write to a database file (as opposed to
28461    ** doing a hot-journal rollback or a write to some file other than a
28462    ** normal database file) and we truncate the file to zero length,
28463    ** that effectively updates the change counter.  This might happen
28464    ** when restoring a database using the backup API from a zero-length
28465    ** source.
28466    */
28467    if( pFile->inNormalWrite && nByte==0 ){
28468      pFile->transCntrChng = 1;
28469    }
28470#endif
28471
28472    return SQLITE_OK;
28473  }
28474}
28475
28476/*
28477** Determine the current size of a file in bytes
28478*/
28479static int unixFileSize(sqlite3_file *id, i64 *pSize){
28480  int rc;
28481  struct stat buf;
28482  assert( id );
28483  rc = osFstat(((unixFile*)id)->h, &buf);
28484  SimulateIOError( rc=1 );
28485  if( rc!=0 ){
28486    ((unixFile*)id)->lastErrno = errno;
28487    return unixLogError(SQLITE_IOERR_FSTAT, "fstat", ((unixFile*)id)->zPath);
28488  }
28489  *pSize = buf.st_size;
28490
28491  /* When opening a zero-size database, the findInodeInfo() procedure
28492  ** writes a single byte into that file in order to work around a bug
28493  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
28494  ** layers, we need to report this file size as zero even though it is
28495  ** really 1.   Ticket #3260.
28496  */
28497  if( *pSize==1 ) *pSize = 0;
28498
28499
28500  return SQLITE_OK;
28501}
28502
28503#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28504/*
28505** Handler for proxy-locking file-control verbs.  Defined below in the
28506** proxying locking division.
28507*/
28508static int proxyFileControl(sqlite3_file*,int,void*);
28509#endif
28510
28511/*
28512** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
28513** file-control operation.  Enlarge the database to nBytes in size
28514** (rounded up to the next chunk-size).  If the database is already
28515** nBytes or larger, this routine is a no-op.
28516*/
28517static int fcntlSizeHint(unixFile *pFile, i64 nByte){
28518  if( pFile->szChunk>0 ){
28519    i64 nSize;                    /* Required file size */
28520    struct stat buf;              /* Used to hold return values of fstat() */
28521
28522    if( osFstat(pFile->h, &buf) ) {
28523      return unixLogError(SQLITE_IOERR_FSTAT, "fstat", pFile->zPath);
28524    }
28525
28526    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
28527    if( nSize>(i64)buf.st_size ){
28528
28529#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
28530      /* The code below is handling the return value of osFallocate()
28531      ** correctly. posix_fallocate() is defined to "returns zero on success,
28532      ** or an error number on  failure". See the manpage for details. */
28533      int err;
28534      do{
28535        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
28536      }while( err==EINTR );
28537      if( err ) return SQLITE_IOERR_WRITE;
28538#else
28539      /* If the OS does not have posix_fallocate(), fake it. First use
28540      ** ftruncate() to set the file size, then write a single byte to
28541      ** the last byte in each block within the extended region. This
28542      ** is the same technique used by glibc to implement posix_fallocate()
28543      ** on systems that do not have a real fallocate() system call.
28544      */
28545      int nBlk = buf.st_blksize;  /* File-system block size */
28546      i64 iWrite;                 /* Next offset to write to */
28547
28548      if( robust_ftruncate(pFile->h, nSize) ){
28549        pFile->lastErrno = errno;
28550        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28551      }
28552      iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
28553      while( iWrite<nSize ){
28554        int nWrite = seekAndWrite(pFile, iWrite, "", 1);
28555        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
28556        iWrite += nBlk;
28557      }
28558#endif
28559    }
28560  }
28561
28562  return SQLITE_OK;
28563}
28564
28565/*
28566** If *pArg is inititially negative then this is a query.  Set *pArg to
28567** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
28568**
28569** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
28570*/
28571static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
28572  if( *pArg<0 ){
28573    *pArg = (pFile->ctrlFlags & mask)!=0;
28574  }else if( (*pArg)==0 ){
28575    pFile->ctrlFlags &= ~mask;
28576  }else{
28577    pFile->ctrlFlags |= mask;
28578  }
28579}
28580
28581/*
28582** Information and control of an open file handle.
28583*/
28584static int unixFileControl(sqlite3_file *id, int op, void *pArg){
28585  unixFile *pFile = (unixFile*)id;
28586  switch( op ){
28587    case SQLITE_FCNTL_LOCKSTATE: {
28588      *(int*)pArg = pFile->eFileLock;
28589      return SQLITE_OK;
28590    }
28591    case SQLITE_LAST_ERRNO: {
28592      *(int*)pArg = pFile->lastErrno;
28593      return SQLITE_OK;
28594    }
28595    case SQLITE_FCNTL_CHUNK_SIZE: {
28596      pFile->szChunk = *(int *)pArg;
28597      return SQLITE_OK;
28598    }
28599    case SQLITE_FCNTL_SIZE_HINT: {
28600      int rc;
28601      SimulateIOErrorBenign(1);
28602      rc = fcntlSizeHint(pFile, *(i64 *)pArg);
28603      SimulateIOErrorBenign(0);
28604      return rc;
28605    }
28606    case SQLITE_FCNTL_PERSIST_WAL: {
28607      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
28608      return SQLITE_OK;
28609    }
28610    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
28611      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
28612      return SQLITE_OK;
28613    }
28614    case SQLITE_FCNTL_VFSNAME: {
28615      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
28616      return SQLITE_OK;
28617    }
28618#ifndef NDEBUG
28619    /* The pager calls this method to signal that it has done
28620    ** a rollback and that the database is therefore unchanged and
28621    ** it hence it is OK for the transaction change counter to be
28622    ** unchanged.
28623    */
28624    case SQLITE_FCNTL_DB_UNCHANGED: {
28625      ((unixFile*)id)->dbUpdate = 0;
28626      return SQLITE_OK;
28627    }
28628#endif
28629#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28630    case SQLITE_SET_LOCKPROXYFILE:
28631    case SQLITE_GET_LOCKPROXYFILE: {
28632      return proxyFileControl(id,op,pArg);
28633    }
28634#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
28635  }
28636  return SQLITE_NOTFOUND;
28637}
28638
28639/*
28640** Return the sector size in bytes of the underlying block device for
28641** the specified file. This is almost always 512 bytes, but may be
28642** larger for some devices.
28643**
28644** SQLite code assumes this function cannot fail. It also assumes that
28645** if two files are created in the same file-system directory (i.e.
28646** a database and its journal file) that the sector size will be the
28647** same for both.
28648*/
28649static int unixSectorSize(sqlite3_file *pFile){
28650  (void)pFile;
28651  return SQLITE_DEFAULT_SECTOR_SIZE;
28652}
28653
28654/*
28655** Return the device characteristics for the file.
28656**
28657** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
28658** However, that choice is contraversial since technically the underlying
28659** file system does not always provide powersafe overwrites.  (In other
28660** words, after a power-loss event, parts of the file that were never
28661** written might end up being altered.)  However, non-PSOW behavior is very,
28662** very rare.  And asserting PSOW makes a large reduction in the amount
28663** of required I/O for journaling, since a lot of padding is eliminated.
28664**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
28665** available to turn it off and URI query parameter available to turn it off.
28666*/
28667static int unixDeviceCharacteristics(sqlite3_file *id){
28668  unixFile *p = (unixFile*)id;
28669  if( p->ctrlFlags & UNIXFILE_PSOW ){
28670    return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
28671  }else{
28672    return 0;
28673  }
28674}
28675
28676#ifndef SQLITE_OMIT_WAL
28677
28678
28679/*
28680** Object used to represent an shared memory buffer.
28681**
28682** When multiple threads all reference the same wal-index, each thread
28683** has its own unixShm object, but they all point to a single instance
28684** of this unixShmNode object.  In other words, each wal-index is opened
28685** only once per process.
28686**
28687** Each unixShmNode object is connected to a single unixInodeInfo object.
28688** We could coalesce this object into unixInodeInfo, but that would mean
28689** every open file that does not use shared memory (in other words, most
28690** open files) would have to carry around this extra information.  So
28691** the unixInodeInfo object contains a pointer to this unixShmNode object
28692** and the unixShmNode object is created only when needed.
28693**
28694** unixMutexHeld() must be true when creating or destroying
28695** this object or while reading or writing the following fields:
28696**
28697**      nRef
28698**
28699** The following fields are read-only after the object is created:
28700**
28701**      fid
28702**      zFilename
28703**
28704** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
28705** unixMutexHeld() is true when reading or writing any other field
28706** in this structure.
28707*/
28708struct unixShmNode {
28709  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
28710  sqlite3_mutex *mutex;      /* Mutex to access this object */
28711  char *zFilename;           /* Name of the mmapped file */
28712  int h;                     /* Open file descriptor */
28713  int szRegion;              /* Size of shared-memory regions */
28714  u16 nRegion;               /* Size of array apRegion */
28715  u8 isReadonly;             /* True if read-only */
28716  char **apRegion;           /* Array of mapped shared-memory regions */
28717  int nRef;                  /* Number of unixShm objects pointing to this */
28718  unixShm *pFirst;           /* All unixShm objects pointing to this */
28719#ifdef SQLITE_DEBUG
28720  u8 exclMask;               /* Mask of exclusive locks held */
28721  u8 sharedMask;             /* Mask of shared locks held */
28722  u8 nextShmId;              /* Next available unixShm.id value */
28723#endif
28724};
28725
28726/*
28727** Structure used internally by this VFS to record the state of an
28728** open shared memory connection.
28729**
28730** The following fields are initialized when this object is created and
28731** are read-only thereafter:
28732**
28733**    unixShm.pFile
28734**    unixShm.id
28735**
28736** All other fields are read/write.  The unixShm.pFile->mutex must be held
28737** while accessing any read/write fields.
28738*/
28739struct unixShm {
28740  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
28741  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
28742  u8 hasMutex;               /* True if holding the unixShmNode mutex */
28743  u8 id;                     /* Id of this connection within its unixShmNode */
28744  u16 sharedMask;            /* Mask of shared locks held */
28745  u16 exclMask;              /* Mask of exclusive locks held */
28746};
28747
28748/*
28749** Constants used for locking
28750*/
28751#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
28752#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
28753
28754/*
28755** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
28756**
28757** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
28758** otherwise.
28759*/
28760static int unixShmSystemLock(
28761  unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
28762  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
28763  int ofst,              /* First byte of the locking range */
28764  int n                  /* Number of bytes to lock */
28765){
28766  struct flock f;       /* The posix advisory locking structure */
28767  int rc = SQLITE_OK;   /* Result code form fcntl() */
28768
28769  /* Access to the unixShmNode object is serialized by the caller */
28770  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
28771
28772  /* Shared locks never span more than one byte */
28773  assert( n==1 || lockType!=F_RDLCK );
28774
28775  /* Locks are within range */
28776  assert( n>=1 && n<SQLITE_SHM_NLOCK );
28777
28778  if( pShmNode->h>=0 ){
28779    /* Initialize the locking parameters */
28780    memset(&f, 0, sizeof(f));
28781    f.l_type = lockType;
28782    f.l_whence = SEEK_SET;
28783    f.l_start = ofst;
28784    f.l_len = n;
28785
28786    rc = osFcntl(pShmNode->h, F_SETLK, &f);
28787    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
28788  }
28789
28790  /* Update the global lock state and do debug tracing */
28791#ifdef SQLITE_DEBUG
28792  { u16 mask;
28793  OSTRACE(("SHM-LOCK "));
28794  mask = (1<<(ofst+n)) - (1<<ofst);
28795  if( rc==SQLITE_OK ){
28796    if( lockType==F_UNLCK ){
28797      OSTRACE(("unlock %d ok", ofst));
28798      pShmNode->exclMask &= ~mask;
28799      pShmNode->sharedMask &= ~mask;
28800    }else if( lockType==F_RDLCK ){
28801      OSTRACE(("read-lock %d ok", ofst));
28802      pShmNode->exclMask &= ~mask;
28803      pShmNode->sharedMask |= mask;
28804    }else{
28805      assert( lockType==F_WRLCK );
28806      OSTRACE(("write-lock %d ok", ofst));
28807      pShmNode->exclMask |= mask;
28808      pShmNode->sharedMask &= ~mask;
28809    }
28810  }else{
28811    if( lockType==F_UNLCK ){
28812      OSTRACE(("unlock %d failed", ofst));
28813    }else if( lockType==F_RDLCK ){
28814      OSTRACE(("read-lock failed"));
28815    }else{
28816      assert( lockType==F_WRLCK );
28817      OSTRACE(("write-lock %d failed", ofst));
28818    }
28819  }
28820  OSTRACE((" - afterwards %03x,%03x\n",
28821           pShmNode->sharedMask, pShmNode->exclMask));
28822  }
28823#endif
28824
28825  return rc;
28826}
28827
28828
28829/*
28830** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
28831**
28832** This is not a VFS shared-memory method; it is a utility function called
28833** by VFS shared-memory methods.
28834*/
28835static void unixShmPurge(unixFile *pFd){
28836  unixShmNode *p = pFd->pInode->pShmNode;
28837  assert( unixMutexHeld() );
28838  if( p && p->nRef==0 ){
28839    int i;
28840    assert( p->pInode==pFd->pInode );
28841    sqlite3_mutex_free(p->mutex);
28842    for(i=0; i<p->nRegion; i++){
28843      if( p->h>=0 ){
28844        munmap(p->apRegion[i], p->szRegion);
28845      }else{
28846        sqlite3_free(p->apRegion[i]);
28847      }
28848    }
28849    sqlite3_free(p->apRegion);
28850    if( p->h>=0 ){
28851      robust_close(pFd, p->h, __LINE__);
28852      p->h = -1;
28853    }
28854    p->pInode->pShmNode = 0;
28855    sqlite3_free(p);
28856  }
28857}
28858
28859/*
28860** Open a shared-memory area associated with open database file pDbFd.
28861** This particular implementation uses mmapped files.
28862**
28863** The file used to implement shared-memory is in the same directory
28864** as the open database file and has the same name as the open database
28865** file with the "-shm" suffix added.  For example, if the database file
28866** is "/home/user1/config.db" then the file that is created and mmapped
28867** for shared memory will be called "/home/user1/config.db-shm".
28868**
28869** Another approach to is to use files in /dev/shm or /dev/tmp or an
28870** some other tmpfs mount. But if a file in a different directory
28871** from the database file is used, then differing access permissions
28872** or a chroot() might cause two different processes on the same
28873** database to end up using different files for shared memory -
28874** meaning that their memory would not really be shared - resulting
28875** in database corruption.  Nevertheless, this tmpfs file usage
28876** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
28877** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
28878** option results in an incompatible build of SQLite;  builds of SQLite
28879** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
28880** same database file at the same time, database corruption will likely
28881** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
28882** "unsupported" and may go away in a future SQLite release.
28883**
28884** When opening a new shared-memory file, if no other instances of that
28885** file are currently open, in this process or in other processes, then
28886** the file must be truncated to zero length or have its header cleared.
28887**
28888** If the original database file (pDbFd) is using the "unix-excl" VFS
28889** that means that an exclusive lock is held on the database file and
28890** that no other processes are able to read or write the database.  In
28891** that case, we do not really need shared memory.  No shared memory
28892** file is created.  The shared memory will be simulated with heap memory.
28893*/
28894static int unixOpenSharedMemory(unixFile *pDbFd){
28895  struct unixShm *p = 0;          /* The connection to be opened */
28896  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
28897  int rc;                         /* Result code */
28898  unixInodeInfo *pInode;          /* The inode of fd */
28899  char *zShmFilename;             /* Name of the file used for SHM */
28900  int nShmFilename;               /* Size of the SHM filename in bytes */
28901
28902  /* Allocate space for the new unixShm object. */
28903  p = sqlite3_malloc( sizeof(*p) );
28904  if( p==0 ) return SQLITE_NOMEM;
28905  memset(p, 0, sizeof(*p));
28906  assert( pDbFd->pShm==0 );
28907
28908  /* Check to see if a unixShmNode object already exists. Reuse an existing
28909  ** one if present. Create a new one if necessary.
28910  */
28911  unixEnterMutex();
28912  pInode = pDbFd->pInode;
28913  pShmNode = pInode->pShmNode;
28914  if( pShmNode==0 ){
28915    struct stat sStat;                 /* fstat() info for database file */
28916
28917    /* Call fstat() to figure out the permissions on the database file. If
28918    ** a new *-shm file is created, an attempt will be made to create it
28919    ** with the same permissions.
28920    */
28921    if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
28922      rc = unixLogError(SQLITE_IOERR_FSTAT, "fstat", pDbFd->zPath);
28923      goto shm_open_err;
28924    }
28925
28926#ifdef SQLITE_SHM_DIRECTORY
28927    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
28928#else
28929    nShmFilename = 6 + (int)strlen(pDbFd->zPath);
28930#endif
28931    pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
28932    if( pShmNode==0 ){
28933      rc = SQLITE_NOMEM;
28934      goto shm_open_err;
28935    }
28936    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
28937    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
28938#ifdef SQLITE_SHM_DIRECTORY
28939    sqlite3_snprintf(nShmFilename, zShmFilename,
28940                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
28941                     (u32)sStat.st_ino, (u32)sStat.st_dev);
28942#else
28943    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
28944    sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
28945#endif
28946    pShmNode->h = -1;
28947    pDbFd->pInode->pShmNode = pShmNode;
28948    pShmNode->pInode = pDbFd->pInode;
28949    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
28950    if( pShmNode->mutex==0 ){
28951      rc = SQLITE_NOMEM;
28952      goto shm_open_err;
28953    }
28954
28955    if( pInode->bProcessLock==0 ){
28956      int openFlags = O_RDWR | O_CREAT;
28957      if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
28958        openFlags = O_RDONLY;
28959        pShmNode->isReadonly = 1;
28960      }
28961      pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
28962      if( pShmNode->h<0 ){
28963        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
28964        goto shm_open_err;
28965      }
28966
28967      /* If this process is running as root, make sure that the SHM file
28968      ** is owned by the same user that owns the original database.  Otherwise,
28969      ** the original owner will not be able to connect. If this process is
28970      ** not root, the following fchown() will fail, but we don't care.  The
28971      ** if(){..} and the UNIXFILE_CHOWN flag are purely to silence compiler
28972      ** warnings.
28973      */
28974      if( osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid)==0 ){
28975        pDbFd->ctrlFlags |= UNIXFILE_CHOWN;
28976      }
28977
28978      /* Check to see if another process is holding the dead-man switch.
28979      ** If not, truncate the file to zero length.
28980      */
28981      rc = SQLITE_OK;
28982      if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
28983        if( robust_ftruncate(pShmNode->h, 0) ){
28984          rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
28985        }
28986      }
28987      if( rc==SQLITE_OK ){
28988        rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
28989      }
28990      if( rc ) goto shm_open_err;
28991    }
28992  }
28993
28994  /* Make the new connection a child of the unixShmNode */
28995  p->pShmNode = pShmNode;
28996#ifdef SQLITE_DEBUG
28997  p->id = pShmNode->nextShmId++;
28998#endif
28999  pShmNode->nRef++;
29000  pDbFd->pShm = p;
29001  unixLeaveMutex();
29002
29003  /* The reference count on pShmNode has already been incremented under
29004  ** the cover of the unixEnterMutex() mutex and the pointer from the
29005  ** new (struct unixShm) object to the pShmNode has been set. All that is
29006  ** left to do is to link the new object into the linked list starting
29007  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
29008  ** mutex.
29009  */
29010  sqlite3_mutex_enter(pShmNode->mutex);
29011  p->pNext = pShmNode->pFirst;
29012  pShmNode->pFirst = p;
29013  sqlite3_mutex_leave(pShmNode->mutex);
29014  return SQLITE_OK;
29015
29016  /* Jump here on any error */
29017shm_open_err:
29018  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
29019  sqlite3_free(p);
29020  unixLeaveMutex();
29021  return rc;
29022}
29023
29024/*
29025** This function is called to obtain a pointer to region iRegion of the
29026** shared-memory associated with the database file fd. Shared-memory regions
29027** are numbered starting from zero. Each shared-memory region is szRegion
29028** bytes in size.
29029**
29030** If an error occurs, an error code is returned and *pp is set to NULL.
29031**
29032** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
29033** region has not been allocated (by any client, including one running in a
29034** separate process), then *pp is set to NULL and SQLITE_OK returned. If
29035** bExtend is non-zero and the requested shared-memory region has not yet
29036** been allocated, it is allocated by this function.
29037**
29038** If the shared-memory region has already been allocated or is allocated by
29039** this call as described above, then it is mapped into this processes
29040** address space (if it is not already), *pp is set to point to the mapped
29041** memory and SQLITE_OK returned.
29042*/
29043static int unixShmMap(
29044  sqlite3_file *fd,               /* Handle open on database file */
29045  int iRegion,                    /* Region to retrieve */
29046  int szRegion,                   /* Size of regions */
29047  int bExtend,                    /* True to extend file if necessary */
29048  void volatile **pp              /* OUT: Mapped memory */
29049){
29050  unixFile *pDbFd = (unixFile*)fd;
29051  unixShm *p;
29052  unixShmNode *pShmNode;
29053  int rc = SQLITE_OK;
29054
29055  /* If the shared-memory file has not yet been opened, open it now. */
29056  if( pDbFd->pShm==0 ){
29057    rc = unixOpenSharedMemory(pDbFd);
29058    if( rc!=SQLITE_OK ) return rc;
29059  }
29060
29061  p = pDbFd->pShm;
29062  pShmNode = p->pShmNode;
29063  sqlite3_mutex_enter(pShmNode->mutex);
29064  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
29065  assert( pShmNode->pInode==pDbFd->pInode );
29066  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29067  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29068
29069  if( pShmNode->nRegion<=iRegion ){
29070    char **apNew;                      /* New apRegion[] array */
29071    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
29072    struct stat sStat;                 /* Used by fstat() */
29073
29074    pShmNode->szRegion = szRegion;
29075
29076    if( pShmNode->h>=0 ){
29077      /* The requested region is not mapped into this processes address space.
29078      ** Check to see if it has been allocated (i.e. if the wal-index file is
29079      ** large enough to contain the requested region).
29080      */
29081      if( osFstat(pShmNode->h, &sStat) ){
29082        rc = SQLITE_IOERR_SHMSIZE;
29083        goto shmpage_out;
29084      }
29085
29086      if( sStat.st_size<nByte ){
29087        /* The requested memory region does not exist. If bExtend is set to
29088        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
29089        **
29090        ** Alternatively, if bExtend is true, use ftruncate() to allocate
29091        ** the requested memory region.
29092        */
29093        if( !bExtend ) goto shmpage_out;
29094        if( robust_ftruncate(pShmNode->h, nByte) ){
29095          rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
29096                            pShmNode->zFilename);
29097          goto shmpage_out;
29098        }
29099      }
29100    }
29101
29102    /* Map the requested memory region into this processes address space. */
29103    apNew = (char **)sqlite3_realloc(
29104        pShmNode->apRegion, (iRegion+1)*sizeof(char *)
29105    );
29106    if( !apNew ){
29107      rc = SQLITE_IOERR_NOMEM;
29108      goto shmpage_out;
29109    }
29110    pShmNode->apRegion = apNew;
29111    while(pShmNode->nRegion<=iRegion){
29112      void *pMem;
29113      if( pShmNode->h>=0 ){
29114        pMem = mmap(0, szRegion,
29115            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
29116            MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
29117        );
29118        if( pMem==MAP_FAILED ){
29119          rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
29120          goto shmpage_out;
29121        }
29122      }else{
29123        pMem = sqlite3_malloc(szRegion);
29124        if( pMem==0 ){
29125          rc = SQLITE_NOMEM;
29126          goto shmpage_out;
29127        }
29128        memset(pMem, 0, szRegion);
29129      }
29130      pShmNode->apRegion[pShmNode->nRegion] = pMem;
29131      pShmNode->nRegion++;
29132    }
29133  }
29134
29135shmpage_out:
29136  if( pShmNode->nRegion>iRegion ){
29137    *pp = pShmNode->apRegion[iRegion];
29138  }else{
29139    *pp = 0;
29140  }
29141  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
29142  sqlite3_mutex_leave(pShmNode->mutex);
29143  return rc;
29144}
29145
29146/*
29147** Change the lock state for a shared-memory segment.
29148**
29149** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
29150** different here than in posix.  In xShmLock(), one can go from unlocked
29151** to shared and back or from unlocked to exclusive and back.  But one may
29152** not go from shared to exclusive or from exclusive to shared.
29153*/
29154static int unixShmLock(
29155  sqlite3_file *fd,          /* Database file holding the shared memory */
29156  int ofst,                  /* First lock to acquire or release */
29157  int n,                     /* Number of locks to acquire or release */
29158  int flags                  /* What to do with the lock */
29159){
29160  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
29161  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
29162  unixShm *pX;                          /* For looping over all siblings */
29163  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
29164  int rc = SQLITE_OK;                   /* Result code */
29165  u16 mask;                             /* Mask of locks to take or release */
29166
29167  assert( pShmNode==pDbFd->pInode->pShmNode );
29168  assert( pShmNode->pInode==pDbFd->pInode );
29169  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
29170  assert( n>=1 );
29171  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
29172       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
29173       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
29174       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
29175  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
29176  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29177  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29178
29179  mask = (1<<(ofst+n)) - (1<<ofst);
29180  assert( n>1 || mask==(1<<ofst) );
29181  sqlite3_mutex_enter(pShmNode->mutex);
29182  if( flags & SQLITE_SHM_UNLOCK ){
29183    u16 allMask = 0; /* Mask of locks held by siblings */
29184
29185    /* See if any siblings hold this same lock */
29186    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29187      if( pX==p ) continue;
29188      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
29189      allMask |= pX->sharedMask;
29190    }
29191
29192    /* Unlock the system-level locks */
29193    if( (mask & allMask)==0 ){
29194      rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
29195    }else{
29196      rc = SQLITE_OK;
29197    }
29198
29199    /* Undo the local locks */
29200    if( rc==SQLITE_OK ){
29201      p->exclMask &= ~mask;
29202      p->sharedMask &= ~mask;
29203    }
29204  }else if( flags & SQLITE_SHM_SHARED ){
29205    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
29206
29207    /* Find out which shared locks are already held by sibling connections.
29208    ** If any sibling already holds an exclusive lock, go ahead and return
29209    ** SQLITE_BUSY.
29210    */
29211    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29212      if( (pX->exclMask & mask)!=0 ){
29213        rc = SQLITE_BUSY;
29214        break;
29215      }
29216      allShared |= pX->sharedMask;
29217    }
29218
29219    /* Get shared locks at the system level, if necessary */
29220    if( rc==SQLITE_OK ){
29221      if( (allShared & mask)==0 ){
29222        rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
29223      }else{
29224        rc = SQLITE_OK;
29225      }
29226    }
29227
29228    /* Get the local shared locks */
29229    if( rc==SQLITE_OK ){
29230      p->sharedMask |= mask;
29231    }
29232  }else{
29233    /* Make sure no sibling connections hold locks that will block this
29234    ** lock.  If any do, return SQLITE_BUSY right away.
29235    */
29236    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29237      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
29238        rc = SQLITE_BUSY;
29239        break;
29240      }
29241    }
29242
29243    /* Get the exclusive locks at the system level.  Then if successful
29244    ** also mark the local connection as being locked.
29245    */
29246    if( rc==SQLITE_OK ){
29247      rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
29248      if( rc==SQLITE_OK ){
29249        assert( (p->sharedMask & mask)==0 );
29250        p->exclMask |= mask;
29251      }
29252    }
29253  }
29254  sqlite3_mutex_leave(pShmNode->mutex);
29255  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
29256           p->id, getpid(), p->sharedMask, p->exclMask));
29257  return rc;
29258}
29259
29260/*
29261** Implement a memory barrier or memory fence on shared memory.
29262**
29263** All loads and stores begun before the barrier must complete before
29264** any load or store begun after the barrier.
29265*/
29266static void unixShmBarrier(
29267  sqlite3_file *fd                /* Database file holding the shared memory */
29268){
29269  UNUSED_PARAMETER(fd);
29270  unixEnterMutex();
29271  unixLeaveMutex();
29272}
29273
29274/*
29275** Close a connection to shared-memory.  Delete the underlying
29276** storage if deleteFlag is true.
29277**
29278** If there is no shared memory associated with the connection then this
29279** routine is a harmless no-op.
29280*/
29281static int unixShmUnmap(
29282  sqlite3_file *fd,               /* The underlying database file */
29283  int deleteFlag                  /* Delete shared-memory if true */
29284){
29285  unixShm *p;                     /* The connection to be closed */
29286  unixShmNode *pShmNode;          /* The underlying shared-memory file */
29287  unixShm **pp;                   /* For looping over sibling connections */
29288  unixFile *pDbFd;                /* The underlying database file */
29289
29290  pDbFd = (unixFile*)fd;
29291  p = pDbFd->pShm;
29292  if( p==0 ) return SQLITE_OK;
29293  pShmNode = p->pShmNode;
29294
29295  assert( pShmNode==pDbFd->pInode->pShmNode );
29296  assert( pShmNode->pInode==pDbFd->pInode );
29297
29298  /* Remove connection p from the set of connections associated
29299  ** with pShmNode */
29300  sqlite3_mutex_enter(pShmNode->mutex);
29301  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
29302  *pp = p->pNext;
29303
29304  /* Free the connection p */
29305  sqlite3_free(p);
29306  pDbFd->pShm = 0;
29307  sqlite3_mutex_leave(pShmNode->mutex);
29308
29309  /* If pShmNode->nRef has reached 0, then close the underlying
29310  ** shared-memory file, too */
29311  unixEnterMutex();
29312  assert( pShmNode->nRef>0 );
29313  pShmNode->nRef--;
29314  if( pShmNode->nRef==0 ){
29315    if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
29316    unixShmPurge(pDbFd);
29317  }
29318  unixLeaveMutex();
29319
29320  return SQLITE_OK;
29321}
29322
29323
29324#else
29325# define unixShmMap     0
29326# define unixShmLock    0
29327# define unixShmBarrier 0
29328# define unixShmUnmap   0
29329#endif /* #ifndef SQLITE_OMIT_WAL */
29330
29331/*
29332** Here ends the implementation of all sqlite3_file methods.
29333**
29334********************** End sqlite3_file Methods *******************************
29335******************************************************************************/
29336
29337/*
29338** This division contains definitions of sqlite3_io_methods objects that
29339** implement various file locking strategies.  It also contains definitions
29340** of "finder" functions.  A finder-function is used to locate the appropriate
29341** sqlite3_io_methods object for a particular database file.  The pAppData
29342** field of the sqlite3_vfs VFS objects are initialized to be pointers to
29343** the correct finder-function for that VFS.
29344**
29345** Most finder functions return a pointer to a fixed sqlite3_io_methods
29346** object.  The only interesting finder-function is autolockIoFinder, which
29347** looks at the filesystem type and tries to guess the best locking
29348** strategy from that.
29349**
29350** For finder-funtion F, two objects are created:
29351**
29352**    (1) The real finder-function named "FImpt()".
29353**
29354**    (2) A constant pointer to this function named just "F".
29355**
29356**
29357** A pointer to the F pointer is used as the pAppData value for VFS
29358** objects.  We have to do this instead of letting pAppData point
29359** directly at the finder-function since C90 rules prevent a void*
29360** from be cast into a function pointer.
29361**
29362**
29363** Each instance of this macro generates two objects:
29364**
29365**   *  A constant sqlite3_io_methods object call METHOD that has locking
29366**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
29367**
29368**   *  An I/O method finder function called FINDER that returns a pointer
29369**      to the METHOD object in the previous bullet.
29370*/
29371#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
29372static const sqlite3_io_methods METHOD = {                                   \
29373   VERSION,                    /* iVersion */                                \
29374   CLOSE,                      /* xClose */                                  \
29375   unixRead,                   /* xRead */                                   \
29376   unixWrite,                  /* xWrite */                                  \
29377   unixTruncate,               /* xTruncate */                               \
29378   unixSync,                   /* xSync */                                   \
29379   unixFileSize,               /* xFileSize */                               \
29380   LOCK,                       /* xLock */                                   \
29381   UNLOCK,                     /* xUnlock */                                 \
29382   CKLOCK,                     /* xCheckReservedLock */                      \
29383   unixFileControl,            /* xFileControl */                            \
29384   unixSectorSize,             /* xSectorSize */                             \
29385   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
29386   unixShmMap,                 /* xShmMap */                                 \
29387   unixShmLock,                /* xShmLock */                                \
29388   unixShmBarrier,             /* xShmBarrier */                             \
29389   unixShmUnmap                /* xShmUnmap */                               \
29390};                                                                           \
29391static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
29392  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
29393  return &METHOD;                                                            \
29394}                                                                            \
29395static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
29396    = FINDER##Impl;
29397
29398/*
29399** Here are all of the sqlite3_io_methods objects for each of the
29400** locking strategies.  Functions that return pointers to these methods
29401** are also created.
29402*/
29403IOMETHODS(
29404  posixIoFinder,            /* Finder function name */
29405  posixIoMethods,           /* sqlite3_io_methods object name */
29406  2,                        /* shared memory is enabled */
29407  unixClose,                /* xClose method */
29408  unixLock,                 /* xLock method */
29409  unixUnlock,               /* xUnlock method */
29410  unixCheckReservedLock     /* xCheckReservedLock method */
29411)
29412IOMETHODS(
29413  nolockIoFinder,           /* Finder function name */
29414  nolockIoMethods,          /* sqlite3_io_methods object name */
29415  1,                        /* shared memory is disabled */
29416  nolockClose,              /* xClose method */
29417  nolockLock,               /* xLock method */
29418  nolockUnlock,             /* xUnlock method */
29419  nolockCheckReservedLock   /* xCheckReservedLock method */
29420)
29421IOMETHODS(
29422  dotlockIoFinder,          /* Finder function name */
29423  dotlockIoMethods,         /* sqlite3_io_methods object name */
29424  1,                        /* shared memory is disabled */
29425  dotlockClose,             /* xClose method */
29426  dotlockLock,              /* xLock method */
29427  dotlockUnlock,            /* xUnlock method */
29428  dotlockCheckReservedLock  /* xCheckReservedLock method */
29429)
29430
29431#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
29432IOMETHODS(
29433  flockIoFinder,            /* Finder function name */
29434  flockIoMethods,           /* sqlite3_io_methods object name */
29435  1,                        /* shared memory is disabled */
29436  flockClose,               /* xClose method */
29437  flockLock,                /* xLock method */
29438  flockUnlock,              /* xUnlock method */
29439  flockCheckReservedLock    /* xCheckReservedLock method */
29440)
29441#endif
29442
29443#if OS_VXWORKS
29444IOMETHODS(
29445  semIoFinder,              /* Finder function name */
29446  semIoMethods,             /* sqlite3_io_methods object name */
29447  1,                        /* shared memory is disabled */
29448  semClose,                 /* xClose method */
29449  semLock,                  /* xLock method */
29450  semUnlock,                /* xUnlock method */
29451  semCheckReservedLock      /* xCheckReservedLock method */
29452)
29453#endif
29454
29455#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29456IOMETHODS(
29457  afpIoFinder,              /* Finder function name */
29458  afpIoMethods,             /* sqlite3_io_methods object name */
29459  1,                        /* shared memory is disabled */
29460  afpClose,                 /* xClose method */
29461  afpLock,                  /* xLock method */
29462  afpUnlock,                /* xUnlock method */
29463  afpCheckReservedLock      /* xCheckReservedLock method */
29464)
29465#endif
29466
29467/*
29468** The proxy locking method is a "super-method" in the sense that it
29469** opens secondary file descriptors for the conch and lock files and
29470** it uses proxy, dot-file, AFP, and flock() locking methods on those
29471** secondary files.  For this reason, the division that implements
29472** proxy locking is located much further down in the file.  But we need
29473** to go ahead and define the sqlite3_io_methods and finder function
29474** for proxy locking here.  So we forward declare the I/O methods.
29475*/
29476#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29477static int proxyClose(sqlite3_file*);
29478static int proxyLock(sqlite3_file*, int);
29479static int proxyUnlock(sqlite3_file*, int);
29480static int proxyCheckReservedLock(sqlite3_file*, int*);
29481IOMETHODS(
29482  proxyIoFinder,            /* Finder function name */
29483  proxyIoMethods,           /* sqlite3_io_methods object name */
29484  1,                        /* shared memory is disabled */
29485  proxyClose,               /* xClose method */
29486  proxyLock,                /* xLock method */
29487  proxyUnlock,              /* xUnlock method */
29488  proxyCheckReservedLock    /* xCheckReservedLock method */
29489)
29490#endif
29491
29492/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
29493#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29494IOMETHODS(
29495  nfsIoFinder,               /* Finder function name */
29496  nfsIoMethods,              /* sqlite3_io_methods object name */
29497  1,                         /* shared memory is disabled */
29498  unixClose,                 /* xClose method */
29499  unixLock,                  /* xLock method */
29500  nfsUnlock,                 /* xUnlock method */
29501  unixCheckReservedLock      /* xCheckReservedLock method */
29502)
29503#endif
29504
29505#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29506/*
29507** This "finder" function attempts to determine the best locking strategy
29508** for the database file "filePath".  It then returns the sqlite3_io_methods
29509** object that implements that strategy.
29510**
29511** This is for MacOSX only.
29512*/
29513static const sqlite3_io_methods *autolockIoFinderImpl(
29514  const char *filePath,    /* name of the database file */
29515  unixFile *pNew           /* open file object for the database file */
29516){
29517  static const struct Mapping {
29518    const char *zFilesystem;              /* Filesystem type name */
29519    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
29520  } aMap[] = {
29521    { "hfs",    &posixIoMethods },
29522    { "ufs",    &posixIoMethods },
29523    { "afpfs",  &afpIoMethods },
29524    { "smbfs",  &afpIoMethods },
29525    { "webdav", &nolockIoMethods },
29526    { 0, 0 }
29527  };
29528  int i;
29529  struct statfs fsInfo;
29530  struct flock lockInfo;
29531
29532  if( !filePath ){
29533    /* If filePath==NULL that means we are dealing with a transient file
29534    ** that does not need to be locked. */
29535    return &nolockIoMethods;
29536  }
29537  if( statfs(filePath, &fsInfo) != -1 ){
29538    if( fsInfo.f_flags & MNT_RDONLY ){
29539      return &nolockIoMethods;
29540    }
29541    for(i=0; aMap[i].zFilesystem; i++){
29542      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
29543        return aMap[i].pMethods;
29544      }
29545    }
29546  }
29547
29548  /* Default case. Handles, amongst others, "nfs".
29549  ** Test byte-range lock using fcntl(). If the call succeeds,
29550  ** assume that the file-system supports POSIX style locks.
29551  */
29552  lockInfo.l_len = 1;
29553  lockInfo.l_start = 0;
29554  lockInfo.l_whence = SEEK_SET;
29555  lockInfo.l_type = F_RDLCK;
29556  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29557    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
29558      return &nfsIoMethods;
29559    } else {
29560      return &posixIoMethods;
29561    }
29562  }else{
29563    return &dotlockIoMethods;
29564  }
29565}
29566static const sqlite3_io_methods
29567  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29568
29569#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29570
29571#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
29572/*
29573** This "finder" function attempts to determine the best locking strategy
29574** for the database file "filePath".  It then returns the sqlite3_io_methods
29575** object that implements that strategy.
29576**
29577** This is for VXWorks only.
29578*/
29579static const sqlite3_io_methods *autolockIoFinderImpl(
29580  const char *filePath,    /* name of the database file */
29581  unixFile *pNew           /* the open file object */
29582){
29583  struct flock lockInfo;
29584
29585  if( !filePath ){
29586    /* If filePath==NULL that means we are dealing with a transient file
29587    ** that does not need to be locked. */
29588    return &nolockIoMethods;
29589  }
29590
29591  /* Test if fcntl() is supported and use POSIX style locks.
29592  ** Otherwise fall back to the named semaphore method.
29593  */
29594  lockInfo.l_len = 1;
29595  lockInfo.l_start = 0;
29596  lockInfo.l_whence = SEEK_SET;
29597  lockInfo.l_type = F_RDLCK;
29598  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29599    return &posixIoMethods;
29600  }else{
29601    return &semIoMethods;
29602  }
29603}
29604static const sqlite3_io_methods
29605  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29606
29607#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
29608
29609/*
29610** An abstract type for a pointer to a IO method finder function:
29611*/
29612typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
29613
29614
29615/****************************************************************************
29616**************************** sqlite3_vfs methods ****************************
29617**
29618** This division contains the implementation of methods on the
29619** sqlite3_vfs object.
29620*/
29621
29622/*
29623** Initialize the contents of the unixFile structure pointed to by pId.
29624*/
29625static int fillInUnixFile(
29626  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
29627  int h,                  /* Open file descriptor of file being opened */
29628  sqlite3_file *pId,      /* Write to the unixFile structure here */
29629  const char *zFilename,  /* Name of the file being opened */
29630  int ctrlFlags           /* Zero or more UNIXFILE_* values */
29631){
29632  const sqlite3_io_methods *pLockingStyle;
29633  unixFile *pNew = (unixFile *)pId;
29634  int rc = SQLITE_OK;
29635
29636  assert( pNew->pInode==NULL );
29637
29638  /* Usually the path zFilename should not be a relative pathname. The
29639  ** exception is when opening the proxy "conch" file in builds that
29640  ** include the special Apple locking styles.
29641  */
29642#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29643  assert( zFilename==0 || zFilename[0]=='/'
29644    || pVfs->pAppData==(void*)&autolockIoFinder );
29645#else
29646  assert( zFilename==0 || zFilename[0]=='/' );
29647#endif
29648
29649  /* No locking occurs in temporary files */
29650  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
29651
29652  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
29653  pNew->h = h;
29654  pNew->pVfs = pVfs;
29655  pNew->zPath = zFilename;
29656  pNew->ctrlFlags = (u8)ctrlFlags;
29657  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
29658                           "psow", SQLITE_POWERSAFE_OVERWRITE) ){
29659    pNew->ctrlFlags |= UNIXFILE_PSOW;
29660  }
29661  if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
29662    pNew->ctrlFlags |= UNIXFILE_EXCL;
29663  }
29664
29665#if OS_VXWORKS
29666  pNew->pId = vxworksFindFileId(zFilename);
29667  if( pNew->pId==0 ){
29668    ctrlFlags |= UNIXFILE_NOLOCK;
29669    rc = SQLITE_NOMEM;
29670  }
29671#endif
29672
29673  if( ctrlFlags & UNIXFILE_NOLOCK ){
29674    pLockingStyle = &nolockIoMethods;
29675  }else{
29676    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
29677#if SQLITE_ENABLE_LOCKING_STYLE
29678    /* Cache zFilename in the locking context (AFP and dotlock override) for
29679    ** proxyLock activation is possible (remote proxy is based on db name)
29680    ** zFilename remains valid until file is closed, to support */
29681    pNew->lockingContext = (void*)zFilename;
29682#endif
29683  }
29684
29685  if( pLockingStyle == &posixIoMethods
29686#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29687    || pLockingStyle == &nfsIoMethods
29688#endif
29689  ){
29690    unixEnterMutex();
29691    rc = findInodeInfo(pNew, &pNew->pInode);
29692    if( rc!=SQLITE_OK ){
29693      /* If an error occured in findInodeInfo(), close the file descriptor
29694      ** immediately, before releasing the mutex. findInodeInfo() may fail
29695      ** in two scenarios:
29696      **
29697      **   (a) A call to fstat() failed.
29698      **   (b) A malloc failed.
29699      **
29700      ** Scenario (b) may only occur if the process is holding no other
29701      ** file descriptors open on the same file. If there were other file
29702      ** descriptors on this file, then no malloc would be required by
29703      ** findInodeInfo(). If this is the case, it is quite safe to close
29704      ** handle h - as it is guaranteed that no posix locks will be released
29705      ** by doing so.
29706      **
29707      ** If scenario (a) caused the error then things are not so safe. The
29708      ** implicit assumption here is that if fstat() fails, things are in
29709      ** such bad shape that dropping a lock or two doesn't matter much.
29710      */
29711      robust_close(pNew, h, __LINE__);
29712      h = -1;
29713    }
29714    unixLeaveMutex();
29715  }
29716
29717#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29718  else if( pLockingStyle == &afpIoMethods ){
29719    /* AFP locking uses the file path so it needs to be included in
29720    ** the afpLockingContext.
29721    */
29722    afpLockingContext *pCtx;
29723    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
29724    if( pCtx==0 ){
29725      rc = SQLITE_NOMEM;
29726    }else{
29727      /* NB: zFilename exists and remains valid until the file is closed
29728      ** according to requirement F11141.  So we do not need to make a
29729      ** copy of the filename. */
29730      pCtx->dbPath = zFilename;
29731      pCtx->reserved = 0;
29732      srandomdev();
29733      unixEnterMutex();
29734      rc = findInodeInfo(pNew, &pNew->pInode);
29735      if( rc!=SQLITE_OK ){
29736        sqlite3_free(pNew->lockingContext);
29737        robust_close(pNew, h, __LINE__);
29738        h = -1;
29739      }
29740      unixLeaveMutex();
29741    }
29742  }
29743#endif
29744
29745  else if( pLockingStyle == &dotlockIoMethods ){
29746    /* Dotfile locking uses the file path so it needs to be included in
29747    ** the dotlockLockingContext
29748    */
29749    char *zLockFile;
29750    int nFilename;
29751    assert( zFilename!=0 );
29752    nFilename = (int)strlen(zFilename) + 6;
29753    zLockFile = (char *)sqlite3_malloc(nFilename);
29754    if( zLockFile==0 ){
29755      rc = SQLITE_NOMEM;
29756    }else{
29757      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
29758    }
29759    pNew->lockingContext = zLockFile;
29760  }
29761
29762#if OS_VXWORKS
29763  else if( pLockingStyle == &semIoMethods ){
29764    /* Named semaphore locking uses the file path so it needs to be
29765    ** included in the semLockingContext
29766    */
29767    unixEnterMutex();
29768    rc = findInodeInfo(pNew, &pNew->pInode);
29769    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
29770      char *zSemName = pNew->pInode->aSemName;
29771      int n;
29772      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
29773                       pNew->pId->zCanonicalName);
29774      for( n=1; zSemName[n]; n++ )
29775        if( zSemName[n]=='/' ) zSemName[n] = '_';
29776      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
29777      if( pNew->pInode->pSem == SEM_FAILED ){
29778        rc = SQLITE_NOMEM;
29779        pNew->pInode->aSemName[0] = '\0';
29780      }
29781    }
29782    unixLeaveMutex();
29783  }
29784#endif
29785
29786  pNew->lastErrno = 0;
29787#if OS_VXWORKS
29788  if( rc!=SQLITE_OK ){
29789    if( h>=0 ) robust_close(pNew, h, __LINE__);
29790    h = -1;
29791    osUnlink(zFilename);
29792    isDelete = 0;
29793  }
29794  if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
29795#endif
29796  if( rc!=SQLITE_OK ){
29797    if( h>=0 ) robust_close(pNew, h, __LINE__);
29798  }else{
29799    pNew->pMethod = pLockingStyle;
29800    OpenCounter(+1);
29801  }
29802  return rc;
29803}
29804
29805/*
29806** Return the name of a directory in which to put temporary files.
29807** If no suitable temporary file directory can be found, return NULL.
29808*/
29809static const char *unixTempFileDir(void){
29810  static const char *azDirs[] = {
29811     0,
29812     0,
29813     "/var/tmp",
29814     "/usr/tmp",
29815     "/tmp",
29816     0        /* List terminator */
29817  };
29818  unsigned int i;
29819  struct stat buf;
29820  const char *zDir = 0;
29821
29822  azDirs[0] = sqlite3_temp_directory;
29823  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
29824  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
29825    if( zDir==0 ) continue;
29826    if( osStat(zDir, &buf) ) continue;
29827    if( !S_ISDIR(buf.st_mode) ) continue;
29828    if( osAccess(zDir, 07) ) continue;
29829    break;
29830  }
29831  return zDir;
29832}
29833
29834/*
29835** Create a temporary file name in zBuf.  zBuf must be allocated
29836** by the calling process and must be big enough to hold at least
29837** pVfs->mxPathname bytes.
29838*/
29839static int unixGetTempname(int nBuf, char *zBuf){
29840  static const unsigned char zChars[] =
29841    "abcdefghijklmnopqrstuvwxyz"
29842    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
29843    "0123456789";
29844  unsigned int i, j;
29845  const char *zDir;
29846
29847  /* It's odd to simulate an io-error here, but really this is just
29848  ** using the io-error infrastructure to test that SQLite handles this
29849  ** function failing.
29850  */
29851  SimulateIOError( return SQLITE_IOERR );
29852
29853  zDir = unixTempFileDir();
29854  if( zDir==0 ) zDir = ".";
29855
29856  /* Check that the output buffer is large enough for the temporary file
29857  ** name. If it is not, return SQLITE_ERROR.
29858  */
29859  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
29860    return SQLITE_ERROR;
29861  }
29862
29863  do{
29864    sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
29865    j = (int)strlen(zBuf);
29866    sqlite3_randomness(15, &zBuf[j]);
29867    for(i=0; i<15; i++, j++){
29868      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
29869    }
29870    zBuf[j] = 0;
29871    zBuf[j+1] = 0;
29872  }while( osAccess(zBuf,0)==0 );
29873  return SQLITE_OK;
29874}
29875
29876#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29877/*
29878** Routine to transform a unixFile into a proxy-locking unixFile.
29879** Implementation in the proxy-lock division, but used by unixOpen()
29880** if SQLITE_PREFER_PROXY_LOCKING is defined.
29881*/
29882static int proxyTransformUnixFile(unixFile*, const char*);
29883#endif
29884
29885/*
29886** Search for an unused file descriptor that was opened on the database
29887** file (not a journal or master-journal file) identified by pathname
29888** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
29889** argument to this function.
29890**
29891** Such a file descriptor may exist if a database connection was closed
29892** but the associated file descriptor could not be closed because some
29893** other file descriptor open on the same file is holding a file-lock.
29894** Refer to comments in the unixClose() function and the lengthy comment
29895** describing "Posix Advisory Locking" at the start of this file for
29896** further details. Also, ticket #4018.
29897**
29898** If a suitable file descriptor is found, then it is returned. If no
29899** such file descriptor is located, -1 is returned.
29900*/
29901static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
29902  UnixUnusedFd *pUnused = 0;
29903
29904  /* Do not search for an unused file descriptor on vxworks. Not because
29905  ** vxworks would not benefit from the change (it might, we're not sure),
29906  ** but because no way to test it is currently available. It is better
29907  ** not to risk breaking vxworks support for the sake of such an obscure
29908  ** feature.  */
29909#if !OS_VXWORKS
29910  struct stat sStat;                   /* Results of stat() call */
29911
29912  /* A stat() call may fail for various reasons. If this happens, it is
29913  ** almost certain that an open() call on the same path will also fail.
29914  ** For this reason, if an error occurs in the stat() call here, it is
29915  ** ignored and -1 is returned. The caller will try to open a new file
29916  ** descriptor on the same path, fail, and return an error to SQLite.
29917  **
29918  ** Even if a subsequent open() call does succeed, the consequences of
29919  ** not searching for a resusable file descriptor are not dire.  */
29920  if( 0==osStat(zPath, &sStat) ){
29921    unixInodeInfo *pInode;
29922
29923    unixEnterMutex();
29924    pInode = inodeList;
29925    while( pInode && (pInode->fileId.dev!=sStat.st_dev
29926                     || pInode->fileId.ino!=sStat.st_ino) ){
29927       pInode = pInode->pNext;
29928    }
29929    if( pInode ){
29930      UnixUnusedFd **pp;
29931      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
29932      pUnused = *pp;
29933      if( pUnused ){
29934        *pp = pUnused->pNext;
29935      }
29936    }
29937    unixLeaveMutex();
29938  }
29939#endif    /* if !OS_VXWORKS */
29940  return pUnused;
29941}
29942
29943/*
29944** This function is called by unixOpen() to determine the unix permissions
29945** to create new files with. If no error occurs, then SQLITE_OK is returned
29946** and a value suitable for passing as the third argument to open(2) is
29947** written to *pMode. If an IO error occurs, an SQLite error code is
29948** returned and the value of *pMode is not modified.
29949**
29950** In most cases cases, this routine sets *pMode to 0, which will become
29951** an indication to robust_open() to create the file using
29952** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
29953** But if the file being opened is a WAL or regular journal file, then
29954** this function queries the file-system for the permissions on the
29955** corresponding database file and sets *pMode to this value. Whenever
29956** possible, WAL and journal files are created using the same permissions
29957** as the associated database file.
29958**
29959** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
29960** original filename is unavailable.  But 8_3_NAMES is only used for
29961** FAT filesystems and permissions do not matter there, so just use
29962** the default permissions.
29963*/
29964static int findCreateFileMode(
29965  const char *zPath,              /* Path of file (possibly) being created */
29966  int flags,                      /* Flags passed as 4th argument to xOpen() */
29967  mode_t *pMode,                  /* OUT: Permissions to open file with */
29968  uid_t *pUid,                    /* OUT: uid to set on the file */
29969  gid_t *pGid                     /* OUT: gid to set on the file */
29970){
29971  int rc = SQLITE_OK;             /* Return Code */
29972  *pMode = 0;
29973  *pUid = 0;
29974  *pGid = 0;
29975  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
29976    char zDb[MAX_PATHNAME+1];     /* Database file path */
29977    int nDb;                      /* Number of valid bytes in zDb */
29978    struct stat sStat;            /* Output of stat() on database file */
29979
29980    /* zPath is a path to a WAL or journal file. The following block derives
29981    ** the path to the associated database file from zPath. This block handles
29982    ** the following naming conventions:
29983    **
29984    **   "<path to db>-journal"
29985    **   "<path to db>-wal"
29986    **   "<path to db>-journalNN"
29987    **   "<path to db>-walNN"
29988    **
29989    ** where NN is a decimal number. The NN naming schemes are
29990    ** used by the test_multiplex.c module.
29991    */
29992    nDb = sqlite3Strlen30(zPath) - 1;
29993#ifdef SQLITE_ENABLE_8_3_NAMES
29994    while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
29995    if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
29996#else
29997    while( zPath[nDb]!='-' ){
29998      assert( nDb>0 );
29999      assert( zPath[nDb]!='\n' );
30000      nDb--;
30001    }
30002#endif
30003    memcpy(zDb, zPath, nDb);
30004    zDb[nDb] = '\0';
30005
30006    if( 0==osStat(zDb, &sStat) ){
30007      *pMode = sStat.st_mode & 0777;
30008      *pUid = sStat.st_uid;
30009      *pGid = sStat.st_gid;
30010    }else{
30011      rc = unixLogError(SQLITE_IOERR_FSTAT, "stat", zDb);
30012    }
30013  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
30014    *pMode = 0600;
30015  }
30016  return rc;
30017}
30018
30019/*
30020** Open the file zPath.
30021**
30022** Previously, the SQLite OS layer used three functions in place of this
30023** one:
30024**
30025**     sqlite3OsOpenReadWrite();
30026**     sqlite3OsOpenReadOnly();
30027**     sqlite3OsOpenExclusive();
30028**
30029** These calls correspond to the following combinations of flags:
30030**
30031**     ReadWrite() ->     (READWRITE | CREATE)
30032**     ReadOnly()  ->     (READONLY)
30033**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
30034**
30035** The old OpenExclusive() accepted a boolean argument - "delFlag". If
30036** true, the file was configured to be automatically deleted when the
30037** file handle closed. To achieve the same effect using this new
30038** interface, add the DELETEONCLOSE flag to those specified above for
30039** OpenExclusive().
30040*/
30041static int unixOpen(
30042  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
30043  const char *zPath,           /* Pathname of file to be opened */
30044  sqlite3_file *pFile,         /* The file descriptor to be filled in */
30045  int flags,                   /* Input flags to control the opening */
30046  int *pOutFlags               /* Output flags returned to SQLite core */
30047){
30048  unixFile *p = (unixFile *)pFile;
30049  int fd = -1;                   /* File descriptor returned by open() */
30050  int openFlags = 0;             /* Flags to pass to open() */
30051  int eType = flags&0xFFFFFF00;  /* Type of file to open */
30052  int noLock;                    /* True to omit locking primitives */
30053  int rc = SQLITE_OK;            /* Function Return Code */
30054  int ctrlFlags = 0;             /* UNIXFILE_* flags */
30055
30056  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
30057  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
30058  int isCreate     = (flags & SQLITE_OPEN_CREATE);
30059  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
30060  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
30061#if SQLITE_ENABLE_LOCKING_STYLE
30062  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
30063#endif
30064#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30065  struct statfs fsInfo;
30066#endif
30067
30068  /* If creating a master or main-file journal, this function will open
30069  ** a file-descriptor on the directory too. The first time unixSync()
30070  ** is called the directory file descriptor will be fsync()ed and close()d.
30071  */
30072  int syncDir = (isCreate && (
30073        eType==SQLITE_OPEN_MASTER_JOURNAL
30074     || eType==SQLITE_OPEN_MAIN_JOURNAL
30075     || eType==SQLITE_OPEN_WAL
30076  ));
30077
30078  /* If argument zPath is a NULL pointer, this function is required to open
30079  ** a temporary file. Use this buffer to store the file name in.
30080  */
30081  char zTmpname[MAX_PATHNAME+2];
30082  const char *zName = zPath;
30083
30084  /* Check the following statements are true:
30085  **
30086  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
30087  **   (b) if CREATE is set, then READWRITE must also be set, and
30088  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
30089  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
30090  */
30091  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
30092  assert(isCreate==0 || isReadWrite);
30093  assert(isExclusive==0 || isCreate);
30094  assert(isDelete==0 || isCreate);
30095
30096  /* The main DB, main journal, WAL file and master journal are never
30097  ** automatically deleted. Nor are they ever temporary files.  */
30098  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
30099  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
30100  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
30101  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
30102
30103  /* Assert that the upper layer has set one of the "file-type" flags. */
30104  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
30105       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
30106       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
30107       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
30108  );
30109
30110  memset(p, 0, sizeof(unixFile));
30111
30112  if( eType==SQLITE_OPEN_MAIN_DB ){
30113    UnixUnusedFd *pUnused;
30114    pUnused = findReusableFd(zName, flags);
30115    if( pUnused ){
30116      fd = pUnused->fd;
30117    }else{
30118      pUnused = sqlite3_malloc(sizeof(*pUnused));
30119      if( !pUnused ){
30120        return SQLITE_NOMEM;
30121      }
30122    }
30123    p->pUnused = pUnused;
30124
30125    /* Database filenames are double-zero terminated if they are not
30126    ** URIs with parameters.  Hence, they can always be passed into
30127    ** sqlite3_uri_parameter(). */
30128    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
30129
30130  }else if( !zName ){
30131    /* If zName is NULL, the upper layer is requesting a temp file. */
30132    assert(isDelete && !syncDir);
30133    rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
30134    if( rc!=SQLITE_OK ){
30135      return rc;
30136    }
30137    zName = zTmpname;
30138
30139    /* Generated temporary filenames are always double-zero terminated
30140    ** for use by sqlite3_uri_parameter(). */
30141    assert( zName[strlen(zName)+1]==0 );
30142  }
30143
30144  /* Determine the value of the flags parameter passed to POSIX function
30145  ** open(). These must be calculated even if open() is not called, as
30146  ** they may be stored as part of the file handle and used by the
30147  ** 'conch file' locking functions later on.  */
30148  if( isReadonly )  openFlags |= O_RDONLY;
30149  if( isReadWrite ) openFlags |= O_RDWR;
30150  if( isCreate )    openFlags |= O_CREAT;
30151  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
30152  openFlags |= (O_LARGEFILE|O_BINARY);
30153
30154  if( fd<0 ){
30155    mode_t openMode;              /* Permissions to create file with */
30156    uid_t uid;                    /* Userid for the file */
30157    gid_t gid;                    /* Groupid for the file */
30158    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
30159    if( rc!=SQLITE_OK ){
30160      assert( !p->pUnused );
30161      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
30162      return rc;
30163    }
30164    fd = robust_open(zName, openFlags, openMode);
30165    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
30166    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
30167      /* Failed to open the file for read/write access. Try read-only. */
30168      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
30169      openFlags &= ~(O_RDWR|O_CREAT);
30170      flags |= SQLITE_OPEN_READONLY;
30171      openFlags |= O_RDONLY;
30172      isReadonly = 1;
30173      fd = robust_open(zName, openFlags, openMode);
30174    }
30175    if( fd<0 ){
30176      rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
30177      goto open_finished;
30178    }
30179
30180    /* If this process is running as root and if creating a new rollback
30181    ** journal or WAL file, set the ownership of the journal or WAL to be
30182    ** the same as the original database.  If we are not running as root,
30183    ** then the fchown() call will fail, but that's ok.  The "if(){}" and
30184    ** the setting of the UNIXFILE_CHOWN flag are purely to silence compiler
30185    ** warnings from gcc.
30186    */
30187    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30188      if( osFchown(fd, uid, gid)==0 ){ p->ctrlFlags |= UNIXFILE_CHOWN; }
30189    }
30190  }
30191  assert( fd>=0 );
30192  if( pOutFlags ){
30193    *pOutFlags = flags;
30194  }
30195
30196  if( p->pUnused ){
30197    p->pUnused->fd = fd;
30198    p->pUnused->flags = flags;
30199  }
30200
30201  if( isDelete ){
30202#if OS_VXWORKS
30203    zPath = zName;
30204#else
30205    osUnlink(zName);
30206#endif
30207  }
30208#if SQLITE_ENABLE_LOCKING_STYLE
30209  else{
30210    p->openFlags = openFlags;
30211  }
30212#endif
30213
30214#ifdef FD_CLOEXEC
30215  osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
30216#endif
30217
30218  noLock = eType!=SQLITE_OPEN_MAIN_DB;
30219
30220
30221#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30222  if( fstatfs(fd, &fsInfo) == -1 ){
30223    ((unixFile*)pFile)->lastErrno = errno;
30224    robust_close(p, fd, __LINE__);
30225    return SQLITE_IOERR_ACCESS;
30226  }
30227  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
30228    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
30229  }
30230#endif
30231
30232  /* Set up appropriate ctrlFlags */
30233  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
30234  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
30235  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
30236  if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
30237  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
30238
30239#if SQLITE_ENABLE_LOCKING_STYLE
30240#if SQLITE_PREFER_PROXY_LOCKING
30241  isAutoProxy = 1;
30242#endif
30243  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
30244    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
30245    int useProxy = 0;
30246
30247    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
30248    ** never use proxy, NULL means use proxy for non-local files only.  */
30249    if( envforce!=NULL ){
30250      useProxy = atoi(envforce)>0;
30251    }else{
30252      if( statfs(zPath, &fsInfo) == -1 ){
30253        /* In theory, the close(fd) call is sub-optimal. If the file opened
30254        ** with fd is a database file, and there are other connections open
30255        ** on that file that are currently holding advisory locks on it,
30256        ** then the call to close() will cancel those locks. In practice,
30257        ** we're assuming that statfs() doesn't fail very often. At least
30258        ** not while other file descriptors opened by the same process on
30259        ** the same file are working.  */
30260        p->lastErrno = errno;
30261        robust_close(p, fd, __LINE__);
30262        rc = SQLITE_IOERR_ACCESS;
30263        goto open_finished;
30264      }
30265      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
30266    }
30267    if( useProxy ){
30268      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30269      if( rc==SQLITE_OK ){
30270        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
30271        if( rc!=SQLITE_OK ){
30272          /* Use unixClose to clean up the resources added in fillInUnixFile
30273          ** and clear all the structure's references.  Specifically,
30274          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
30275          */
30276          unixClose(pFile);
30277          return rc;
30278        }
30279      }
30280      goto open_finished;
30281    }
30282  }
30283#endif
30284
30285  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30286
30287open_finished:
30288  if( rc!=SQLITE_OK ){
30289    sqlite3_free(p->pUnused);
30290  }
30291  return rc;
30292}
30293
30294
30295/*
30296** Delete the file at zPath. If the dirSync argument is true, fsync()
30297** the directory after deleting the file.
30298*/
30299static int unixDelete(
30300  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
30301  const char *zPath,        /* Name of file to be deleted */
30302  int dirSync               /* If true, fsync() directory after deleting file */
30303){
30304  int rc = SQLITE_OK;
30305  UNUSED_PARAMETER(NotUsed);
30306  SimulateIOError(return SQLITE_IOERR_DELETE);
30307  if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
30308    return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
30309  }
30310#ifndef SQLITE_DISABLE_DIRSYNC
30311  if( (dirSync & 1)!=0 ){
30312    int fd;
30313    rc = osOpenDirectory(zPath, &fd);
30314    if( rc==SQLITE_OK ){
30315#if OS_VXWORKS
30316      if( fsync(fd)==-1 )
30317#else
30318      if( fsync(fd) )
30319#endif
30320      {
30321        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
30322      }
30323      robust_close(0, fd, __LINE__);
30324    }else if( rc==SQLITE_CANTOPEN ){
30325      rc = SQLITE_OK;
30326    }
30327  }
30328#endif
30329  return rc;
30330}
30331
30332/*
30333** Test the existance of or access permissions of file zPath. The
30334** test performed depends on the value of flags:
30335**
30336**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
30337**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
30338**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
30339**
30340** Otherwise return 0.
30341*/
30342static int unixAccess(
30343  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
30344  const char *zPath,      /* Path of the file to examine */
30345  int flags,              /* What do we want to learn about the zPath file? */
30346  int *pResOut            /* Write result boolean here */
30347){
30348  int amode = 0;
30349  UNUSED_PARAMETER(NotUsed);
30350  SimulateIOError( return SQLITE_IOERR_ACCESS; );
30351  switch( flags ){
30352    case SQLITE_ACCESS_EXISTS:
30353      amode = F_OK;
30354      break;
30355    case SQLITE_ACCESS_READWRITE:
30356      amode = W_OK|R_OK;
30357      break;
30358    case SQLITE_ACCESS_READ:
30359      amode = R_OK;
30360      break;
30361
30362    default:
30363      assert(!"Invalid flags argument");
30364  }
30365  *pResOut = (osAccess(zPath, amode)==0);
30366  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
30367    struct stat buf;
30368    if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
30369      *pResOut = 0;
30370    }
30371  }
30372  return SQLITE_OK;
30373}
30374
30375
30376/*
30377** Turn a relative pathname into a full pathname. The relative path
30378** is stored as a nul-terminated string in the buffer pointed to by
30379** zPath.
30380**
30381** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
30382** (in this case, MAX_PATHNAME bytes). The full-path is written to
30383** this buffer before returning.
30384*/
30385static int unixFullPathname(
30386  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
30387  const char *zPath,            /* Possibly relative input path */
30388  int nOut,                     /* Size of output buffer in bytes */
30389  char *zOut                    /* Output buffer */
30390){
30391
30392  /* It's odd to simulate an io-error here, but really this is just
30393  ** using the io-error infrastructure to test that SQLite handles this
30394  ** function failing. This function could fail if, for example, the
30395  ** current working directory has been unlinked.
30396  */
30397  SimulateIOError( return SQLITE_ERROR );
30398
30399  assert( pVfs->mxPathname==MAX_PATHNAME );
30400  UNUSED_PARAMETER(pVfs);
30401
30402  zOut[nOut-1] = '\0';
30403  if( zPath[0]=='/' ){
30404    sqlite3_snprintf(nOut, zOut, "%s", zPath);
30405  }else{
30406    int nCwd;
30407    if( osGetcwd(zOut, nOut-1)==0 ){
30408      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
30409    }
30410    nCwd = (int)strlen(zOut);
30411    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
30412  }
30413  return SQLITE_OK;
30414}
30415
30416
30417#ifndef SQLITE_OMIT_LOAD_EXTENSION
30418/*
30419** Interfaces for opening a shared library, finding entry points
30420** within the shared library, and closing the shared library.
30421*/
30422#include <dlfcn.h>
30423static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
30424  UNUSED_PARAMETER(NotUsed);
30425  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
30426}
30427
30428/*
30429** SQLite calls this function immediately after a call to unixDlSym() or
30430** unixDlOpen() fails (returns a null pointer). If a more detailed error
30431** message is available, it is written to zBufOut. If no error message
30432** is available, zBufOut is left unmodified and SQLite uses a default
30433** error message.
30434*/
30435static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
30436  const char *zErr;
30437  UNUSED_PARAMETER(NotUsed);
30438  unixEnterMutex();
30439  zErr = dlerror();
30440  if( zErr ){
30441    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
30442  }
30443  unixLeaveMutex();
30444}
30445static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
30446  /*
30447  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
30448  ** cast into a pointer to a function.  And yet the library dlsym() routine
30449  ** returns a void* which is really a pointer to a function.  So how do we
30450  ** use dlsym() with -pedantic-errors?
30451  **
30452  ** Variable x below is defined to be a pointer to a function taking
30453  ** parameters void* and const char* and returning a pointer to a function.
30454  ** We initialize x by assigning it a pointer to the dlsym() function.
30455  ** (That assignment requires a cast.)  Then we call the function that
30456  ** x points to.
30457  **
30458  ** This work-around is unlikely to work correctly on any system where
30459  ** you really cannot cast a function pointer into void*.  But then, on the
30460  ** other hand, dlsym() will not work on such a system either, so we have
30461  ** not really lost anything.
30462  */
30463  void (*(*x)(void*,const char*))(void);
30464  UNUSED_PARAMETER(NotUsed);
30465  x = (void(*(*)(void*,const char*))(void))dlsym;
30466  return (*x)(p, zSym);
30467}
30468static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
30469  UNUSED_PARAMETER(NotUsed);
30470  dlclose(pHandle);
30471}
30472#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
30473  #define unixDlOpen  0
30474  #define unixDlError 0
30475  #define unixDlSym   0
30476  #define unixDlClose 0
30477#endif
30478
30479/*
30480** Write nBuf bytes of random data to the supplied buffer zBuf.
30481*/
30482static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
30483  UNUSED_PARAMETER(NotUsed);
30484  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
30485
30486  /* We have to initialize zBuf to prevent valgrind from reporting
30487  ** errors.  The reports issued by valgrind are incorrect - we would
30488  ** prefer that the randomness be increased by making use of the
30489  ** uninitialized space in zBuf - but valgrind errors tend to worry
30490  ** some users.  Rather than argue, it seems easier just to initialize
30491  ** the whole array and silence valgrind, even if that means less randomness
30492  ** in the random seed.
30493  **
30494  ** When testing, initializing zBuf[] to zero is all we do.  That means
30495  ** that we always use the same random number sequence.  This makes the
30496  ** tests repeatable.
30497  */
30498  memset(zBuf, 0, nBuf);
30499#if !defined(SQLITE_TEST)
30500  {
30501    int pid, fd, got;
30502    fd = robust_open("/dev/urandom", O_RDONLY, 0);
30503    if( fd<0 ){
30504      time_t t;
30505      time(&t);
30506      memcpy(zBuf, &t, sizeof(t));
30507      pid = getpid();
30508      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
30509      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
30510      nBuf = sizeof(t) + sizeof(pid);
30511    }else{
30512      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
30513      robust_close(0, fd, __LINE__);
30514    }
30515  }
30516#endif
30517  return nBuf;
30518}
30519
30520
30521/*
30522** Sleep for a little while.  Return the amount of time slept.
30523** The argument is the number of microseconds we want to sleep.
30524** The return value is the number of microseconds of sleep actually
30525** requested from the underlying operating system, a number which
30526** might be greater than or equal to the argument, but not less
30527** than the argument.
30528*/
30529static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
30530#if OS_VXWORKS
30531  struct timespec sp;
30532
30533  sp.tv_sec = microseconds / 1000000;
30534  sp.tv_nsec = (microseconds % 1000000) * 1000;
30535  nanosleep(&sp, NULL);
30536  UNUSED_PARAMETER(NotUsed);
30537  return microseconds;
30538#elif defined(HAVE_USLEEP) && HAVE_USLEEP
30539  usleep(microseconds);
30540  UNUSED_PARAMETER(NotUsed);
30541  return microseconds;
30542#else
30543  int seconds = (microseconds+999999)/1000000;
30544  sleep(seconds);
30545  UNUSED_PARAMETER(NotUsed);
30546  return seconds*1000000;
30547#endif
30548}
30549
30550/*
30551** The following variable, if set to a non-zero value, is interpreted as
30552** the number of seconds since 1970 and is used to set the result of
30553** sqlite3OsCurrentTime() during testing.
30554*/
30555#ifdef SQLITE_TEST
30556SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
30557#endif
30558
30559/*
30560** Find the current time (in Universal Coordinated Time).  Write into *piNow
30561** the current time and date as a Julian Day number times 86_400_000.  In
30562** other words, write into *piNow the number of milliseconds since the Julian
30563** epoch of noon in Greenwich on November 24, 4714 B.C according to the
30564** proleptic Gregorian calendar.
30565**
30566** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
30567** cannot be found.
30568*/
30569static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
30570  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
30571  int rc = SQLITE_OK;
30572#if defined(NO_GETTOD)
30573  time_t t;
30574  time(&t);
30575  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
30576#elif OS_VXWORKS
30577  struct timespec sNow;
30578  clock_gettime(CLOCK_REALTIME, &sNow);
30579  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
30580#else
30581  struct timeval sNow;
30582  if( gettimeofday(&sNow, 0)==0 ){
30583    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
30584  }else{
30585    rc = SQLITE_ERROR;
30586  }
30587#endif
30588
30589#ifdef SQLITE_TEST
30590  if( sqlite3_current_time ){
30591    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
30592  }
30593#endif
30594  UNUSED_PARAMETER(NotUsed);
30595  return rc;
30596}
30597
30598/*
30599** Find the current time (in Universal Coordinated Time).  Write the
30600** current time and date as a Julian Day number into *prNow and
30601** return 0.  Return 1 if the time and date cannot be found.
30602*/
30603static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
30604  sqlite3_int64 i = 0;
30605  int rc;
30606  UNUSED_PARAMETER(NotUsed);
30607  rc = unixCurrentTimeInt64(0, &i);
30608  *prNow = i/86400000.0;
30609  return rc;
30610}
30611
30612/*
30613** We added the xGetLastError() method with the intention of providing
30614** better low-level error messages when operating-system problems come up
30615** during SQLite operation.  But so far, none of that has been implemented
30616** in the core.  So this routine is never called.  For now, it is merely
30617** a place-holder.
30618*/
30619static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
30620  UNUSED_PARAMETER(NotUsed);
30621  UNUSED_PARAMETER(NotUsed2);
30622  UNUSED_PARAMETER(NotUsed3);
30623  return 0;
30624}
30625
30626
30627/*
30628************************ End of sqlite3_vfs methods ***************************
30629******************************************************************************/
30630
30631/******************************************************************************
30632************************** Begin Proxy Locking ********************************
30633**
30634** Proxy locking is a "uber-locking-method" in this sense:  It uses the
30635** other locking methods on secondary lock files.  Proxy locking is a
30636** meta-layer over top of the primitive locking implemented above.  For
30637** this reason, the division that implements of proxy locking is deferred
30638** until late in the file (here) after all of the other I/O methods have
30639** been defined - so that the primitive locking methods are available
30640** as services to help with the implementation of proxy locking.
30641**
30642****
30643**
30644** The default locking schemes in SQLite use byte-range locks on the
30645** database file to coordinate safe, concurrent access by multiple readers
30646** and writers [http://sqlite.org/lockingv3.html].  The five file locking
30647** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
30648** as POSIX read & write locks over fixed set of locations (via fsctl),
30649** on AFP and SMB only exclusive byte-range locks are available via fsctl
30650** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
30651** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
30652** address in the shared range is taken for a SHARED lock, the entire
30653** shared range is taken for an EXCLUSIVE lock):
30654**
30655**      PENDING_BYTE        0x40000000
30656**      RESERVED_BYTE       0x40000001
30657**      SHARED_RANGE        0x40000002 -> 0x40000200
30658**
30659** This works well on the local file system, but shows a nearly 100x
30660** slowdown in read performance on AFP because the AFP client disables
30661** the read cache when byte-range locks are present.  Enabling the read
30662** cache exposes a cache coherency problem that is present on all OS X
30663** supported network file systems.  NFS and AFP both observe the
30664** close-to-open semantics for ensuring cache coherency
30665** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
30666** address the requirements for concurrent database access by multiple
30667** readers and writers
30668** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
30669**
30670** To address the performance and cache coherency issues, proxy file locking
30671** changes the way database access is controlled by limiting access to a
30672** single host at a time and moving file locks off of the database file
30673** and onto a proxy file on the local file system.
30674**
30675**
30676** Using proxy locks
30677** -----------------
30678**
30679** C APIs
30680**
30681**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
30682**                       <proxy_path> | ":auto:");
30683**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
30684**
30685**
30686** SQL pragmas
30687**
30688**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
30689**  PRAGMA [database.]lock_proxy_file
30690**
30691** Specifying ":auto:" means that if there is a conch file with a matching
30692** host ID in it, the proxy path in the conch file will be used, otherwise
30693** a proxy path based on the user's temp dir
30694** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
30695** actual proxy file name is generated from the name and path of the
30696** database file.  For example:
30697**
30698**       For database path "/Users/me/foo.db"
30699**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
30700**
30701** Once a lock proxy is configured for a database connection, it can not
30702** be removed, however it may be switched to a different proxy path via
30703** the above APIs (assuming the conch file is not being held by another
30704** connection or process).
30705**
30706**
30707** How proxy locking works
30708** -----------------------
30709**
30710** Proxy file locking relies primarily on two new supporting files:
30711**
30712**   *  conch file to limit access to the database file to a single host
30713**      at a time
30714**
30715**   *  proxy file to act as a proxy for the advisory locks normally
30716**      taken on the database
30717**
30718** The conch file - to use a proxy file, sqlite must first "hold the conch"
30719** by taking an sqlite-style shared lock on the conch file, reading the
30720** contents and comparing the host's unique host ID (see below) and lock
30721** proxy path against the values stored in the conch.  The conch file is
30722** stored in the same directory as the database file and the file name
30723** is patterned after the database file name as ".<databasename>-conch".
30724** If the conch file does not exist, or it's contents do not match the
30725** host ID and/or proxy path, then the lock is escalated to an exclusive
30726** lock and the conch file contents is updated with the host ID and proxy
30727** path and the lock is downgraded to a shared lock again.  If the conch
30728** is held by another process (with a shared lock), the exclusive lock
30729** will fail and SQLITE_BUSY is returned.
30730**
30731** The proxy file - a single-byte file used for all advisory file locks
30732** normally taken on the database file.   This allows for safe sharing
30733** of the database file for multiple readers and writers on the same
30734** host (the conch ensures that they all use the same local lock file).
30735**
30736** Requesting the lock proxy does not immediately take the conch, it is
30737** only taken when the first request to lock database file is made.
30738** This matches the semantics of the traditional locking behavior, where
30739** opening a connection to a database file does not take a lock on it.
30740** The shared lock and an open file descriptor are maintained until
30741** the connection to the database is closed.
30742**
30743** The proxy file and the lock file are never deleted so they only need
30744** to be created the first time they are used.
30745**
30746** Configuration options
30747** ---------------------
30748**
30749**  SQLITE_PREFER_PROXY_LOCKING
30750**
30751**       Database files accessed on non-local file systems are
30752**       automatically configured for proxy locking, lock files are
30753**       named automatically using the same logic as
30754**       PRAGMA lock_proxy_file=":auto:"
30755**
30756**  SQLITE_PROXY_DEBUG
30757**
30758**       Enables the logging of error messages during host id file
30759**       retrieval and creation
30760**
30761**  LOCKPROXYDIR
30762**
30763**       Overrides the default directory used for lock proxy files that
30764**       are named automatically via the ":auto:" setting
30765**
30766**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
30767**
30768**       Permissions to use when creating a directory for storing the
30769**       lock proxy files, only used when LOCKPROXYDIR is not set.
30770**
30771**
30772** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
30773** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
30774** force proxy locking to be used for every database file opened, and 0
30775** will force automatic proxy locking to be disabled for all database
30776** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
30777** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
30778*/
30779
30780/*
30781** Proxy locking is only available on MacOSX
30782*/
30783#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30784
30785/*
30786** The proxyLockingContext has the path and file structures for the remote
30787** and local proxy files in it
30788*/
30789typedef struct proxyLockingContext proxyLockingContext;
30790struct proxyLockingContext {
30791  unixFile *conchFile;         /* Open conch file */
30792  char *conchFilePath;         /* Name of the conch file */
30793  unixFile *lockProxy;         /* Open proxy lock file */
30794  char *lockProxyPath;         /* Name of the proxy lock file */
30795  char *dbPath;                /* Name of the open file */
30796  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
30797  void *oldLockingContext;     /* Original lockingcontext to restore on close */
30798  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
30799};
30800
30801/*
30802** The proxy lock file path for the database at dbPath is written into lPath,
30803** which must point to valid, writable memory large enough for a maxLen length
30804** file path.
30805*/
30806static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
30807  int len;
30808  int dbLen;
30809  int i;
30810
30811#ifdef LOCKPROXYDIR
30812  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
30813#else
30814# ifdef _CS_DARWIN_USER_TEMP_DIR
30815  {
30816    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
30817      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
30818               lPath, errno, getpid()));
30819      return SQLITE_IOERR_LOCK;
30820    }
30821    len = strlcat(lPath, "sqliteplocks", maxLen);
30822  }
30823# else
30824  len = strlcpy(lPath, "/tmp/", maxLen);
30825# endif
30826#endif
30827
30828  if( lPath[len-1]!='/' ){
30829    len = strlcat(lPath, "/", maxLen);
30830  }
30831
30832  /* transform the db path to a unique cache name */
30833  dbLen = (int)strlen(dbPath);
30834  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
30835    char c = dbPath[i];
30836    lPath[i+len] = (c=='/')?'_':c;
30837  }
30838  lPath[i+len]='\0';
30839  strlcat(lPath, ":auto:", maxLen);
30840  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
30841  return SQLITE_OK;
30842}
30843
30844/*
30845 ** Creates the lock file and any missing directories in lockPath
30846 */
30847static int proxyCreateLockPath(const char *lockPath){
30848  int i, len;
30849  char buf[MAXPATHLEN];
30850  int start = 0;
30851
30852  assert(lockPath!=NULL);
30853  /* try to create all the intermediate directories */
30854  len = (int)strlen(lockPath);
30855  buf[0] = lockPath[0];
30856  for( i=1; i<len; i++ ){
30857    if( lockPath[i] == '/' && (i - start > 0) ){
30858      /* only mkdir if leaf dir != "." or "/" or ".." */
30859      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
30860         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
30861        buf[i]='\0';
30862        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
30863          int err=errno;
30864          if( err!=EEXIST ) {
30865            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
30866                     "'%s' proxy lock path=%s pid=%d\n",
30867                     buf, strerror(err), lockPath, getpid()));
30868            return err;
30869          }
30870        }
30871      }
30872      start=i+1;
30873    }
30874    buf[i] = lockPath[i];
30875  }
30876  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
30877  return 0;
30878}
30879
30880/*
30881** Create a new VFS file descriptor (stored in memory obtained from
30882** sqlite3_malloc) and open the file named "path" in the file descriptor.
30883**
30884** The caller is responsible not only for closing the file descriptor
30885** but also for freeing the memory associated with the file descriptor.
30886*/
30887static int proxyCreateUnixFile(
30888    const char *path,        /* path for the new unixFile */
30889    unixFile **ppFile,       /* unixFile created and returned by ref */
30890    int islockfile           /* if non zero missing dirs will be created */
30891) {
30892  int fd = -1;
30893  unixFile *pNew;
30894  int rc = SQLITE_OK;
30895  int openFlags = O_RDWR | O_CREAT;
30896  sqlite3_vfs dummyVfs;
30897  int terrno = 0;
30898  UnixUnusedFd *pUnused = NULL;
30899
30900  /* 1. first try to open/create the file
30901  ** 2. if that fails, and this is a lock file (not-conch), try creating
30902  ** the parent directories and then try again.
30903  ** 3. if that fails, try to open the file read-only
30904  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
30905  */
30906  pUnused = findReusableFd(path, openFlags);
30907  if( pUnused ){
30908    fd = pUnused->fd;
30909  }else{
30910    pUnused = sqlite3_malloc(sizeof(*pUnused));
30911    if( !pUnused ){
30912      return SQLITE_NOMEM;
30913    }
30914  }
30915  if( fd<0 ){
30916    fd = robust_open(path, openFlags, 0);
30917    terrno = errno;
30918    if( fd<0 && errno==ENOENT && islockfile ){
30919      if( proxyCreateLockPath(path) == SQLITE_OK ){
30920        fd = robust_open(path, openFlags, 0);
30921      }
30922    }
30923  }
30924  if( fd<0 ){
30925    openFlags = O_RDONLY;
30926    fd = robust_open(path, openFlags, 0);
30927    terrno = errno;
30928  }
30929  if( fd<0 ){
30930    if( islockfile ){
30931      return SQLITE_BUSY;
30932    }
30933    switch (terrno) {
30934      case EACCES:
30935        return SQLITE_PERM;
30936      case EIO:
30937        return SQLITE_IOERR_LOCK; /* even though it is the conch */
30938      default:
30939        return SQLITE_CANTOPEN_BKPT;
30940    }
30941  }
30942
30943  pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
30944  if( pNew==NULL ){
30945    rc = SQLITE_NOMEM;
30946    goto end_create_proxy;
30947  }
30948  memset(pNew, 0, sizeof(unixFile));
30949  pNew->openFlags = openFlags;
30950  memset(&dummyVfs, 0, sizeof(dummyVfs));
30951  dummyVfs.pAppData = (void*)&autolockIoFinder;
30952  dummyVfs.zName = "dummy";
30953  pUnused->fd = fd;
30954  pUnused->flags = openFlags;
30955  pNew->pUnused = pUnused;
30956
30957  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
30958  if( rc==SQLITE_OK ){
30959    *ppFile = pNew;
30960    return SQLITE_OK;
30961  }
30962end_create_proxy:
30963  robust_close(pNew, fd, __LINE__);
30964  sqlite3_free(pNew);
30965  sqlite3_free(pUnused);
30966  return rc;
30967}
30968
30969#ifdef SQLITE_TEST
30970/* simulate multiple hosts by creating unique hostid file paths */
30971SQLITE_API int sqlite3_hostid_num = 0;
30972#endif
30973
30974#define PROXY_HOSTIDLEN    16  /* conch file host id length */
30975
30976/* Not always defined in the headers as it ought to be */
30977extern int gethostuuid(uuid_t id, const struct timespec *wait);
30978
30979/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
30980** bytes of writable memory.
30981*/
30982static int proxyGetHostID(unsigned char *pHostID, int *pError){
30983  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
30984  memset(pHostID, 0, PROXY_HOSTIDLEN);
30985#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
30986               && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
30987  {
30988    static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
30989    if( gethostuuid(pHostID, &timeout) ){
30990      int err = errno;
30991      if( pError ){
30992        *pError = err;
30993      }
30994      return SQLITE_IOERR;
30995    }
30996  }
30997#else
30998  UNUSED_PARAMETER(pError);
30999#endif
31000#ifdef SQLITE_TEST
31001  /* simulate multiple hosts by creating unique hostid file paths */
31002  if( sqlite3_hostid_num != 0){
31003    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
31004  }
31005#endif
31006
31007  return SQLITE_OK;
31008}
31009
31010/* The conch file contains the header, host id and lock file path
31011 */
31012#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
31013#define PROXY_HEADERLEN    1   /* conch file header length */
31014#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
31015#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
31016
31017/*
31018** Takes an open conch file, copies the contents to a new path and then moves
31019** it back.  The newly created file's file descriptor is assigned to the
31020** conch file structure and finally the original conch file descriptor is
31021** closed.  Returns zero if successful.
31022*/
31023static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
31024  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31025  unixFile *conchFile = pCtx->conchFile;
31026  char tPath[MAXPATHLEN];
31027  char buf[PROXY_MAXCONCHLEN];
31028  char *cPath = pCtx->conchFilePath;
31029  size_t readLen = 0;
31030  size_t pathLen = 0;
31031  char errmsg[64] = "";
31032  int fd = -1;
31033  int rc = -1;
31034  UNUSED_PARAMETER(myHostID);
31035
31036  /* create a new path by replace the trailing '-conch' with '-break' */
31037  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
31038  if( pathLen>MAXPATHLEN || pathLen<6 ||
31039     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
31040    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
31041    goto end_breaklock;
31042  }
31043  /* read the conch content */
31044  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
31045  if( readLen<PROXY_PATHINDEX ){
31046    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
31047    goto end_breaklock;
31048  }
31049  /* write it out to the temporary break file */
31050  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
31051  if( fd<0 ){
31052    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
31053    goto end_breaklock;
31054  }
31055  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
31056    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
31057    goto end_breaklock;
31058  }
31059  if( rename(tPath, cPath) ){
31060    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
31061    goto end_breaklock;
31062  }
31063  rc = 0;
31064  fprintf(stderr, "broke stale lock on %s\n", cPath);
31065  robust_close(pFile, conchFile->h, __LINE__);
31066  conchFile->h = fd;
31067  conchFile->openFlags = O_RDWR | O_CREAT;
31068
31069end_breaklock:
31070  if( rc ){
31071    if( fd>=0 ){
31072      osUnlink(tPath);
31073      robust_close(pFile, fd, __LINE__);
31074    }
31075    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
31076  }
31077  return rc;
31078}
31079
31080/* Take the requested lock on the conch file and break a stale lock if the
31081** host id matches.
31082*/
31083static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
31084  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31085  unixFile *conchFile = pCtx->conchFile;
31086  int rc = SQLITE_OK;
31087  int nTries = 0;
31088  struct timespec conchModTime;
31089
31090  memset(&conchModTime, 0, sizeof(conchModTime));
31091  do {
31092    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31093    nTries ++;
31094    if( rc==SQLITE_BUSY ){
31095      /* If the lock failed (busy):
31096       * 1st try: get the mod time of the conch, wait 0.5s and try again.
31097       * 2nd try: fail if the mod time changed or host id is different, wait
31098       *           10 sec and try again
31099       * 3rd try: break the lock unless the mod time has changed.
31100       */
31101      struct stat buf;
31102      if( osFstat(conchFile->h, &buf) ){
31103        pFile->lastErrno = errno;
31104        return SQLITE_IOERR_LOCK;
31105      }
31106
31107      if( nTries==1 ){
31108        conchModTime = buf.st_mtimespec;
31109        usleep(500000); /* wait 0.5 sec and try the lock again*/
31110        continue;
31111      }
31112
31113      assert( nTries>1 );
31114      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
31115         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
31116        return SQLITE_BUSY;
31117      }
31118
31119      if( nTries==2 ){
31120        char tBuf[PROXY_MAXCONCHLEN];
31121        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
31122        if( len<0 ){
31123          pFile->lastErrno = errno;
31124          return SQLITE_IOERR_LOCK;
31125        }
31126        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
31127          /* don't break the lock if the host id doesn't match */
31128          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
31129            return SQLITE_BUSY;
31130          }
31131        }else{
31132          /* don't break the lock on short read or a version mismatch */
31133          return SQLITE_BUSY;
31134        }
31135        usleep(10000000); /* wait 10 sec and try the lock again */
31136        continue;
31137      }
31138
31139      assert( nTries==3 );
31140      if( 0==proxyBreakConchLock(pFile, myHostID) ){
31141        rc = SQLITE_OK;
31142        if( lockType==EXCLUSIVE_LOCK ){
31143          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
31144        }
31145        if( !rc ){
31146          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31147        }
31148      }
31149    }
31150  } while( rc==SQLITE_BUSY && nTries<3 );
31151
31152  return rc;
31153}
31154
31155/* Takes the conch by taking a shared lock and read the contents conch, if
31156** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
31157** lockPath means that the lockPath in the conch file will be used if the
31158** host IDs match, or a new lock path will be generated automatically
31159** and written to the conch file.
31160*/
31161static int proxyTakeConch(unixFile *pFile){
31162  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31163
31164  if( pCtx->conchHeld!=0 ){
31165    return SQLITE_OK;
31166  }else{
31167    unixFile *conchFile = pCtx->conchFile;
31168    uuid_t myHostID;
31169    int pError = 0;
31170    char readBuf[PROXY_MAXCONCHLEN];
31171    char lockPath[MAXPATHLEN];
31172    char *tempLockPath = NULL;
31173    int rc = SQLITE_OK;
31174    int createConch = 0;
31175    int hostIdMatch = 0;
31176    int readLen = 0;
31177    int tryOldLockPath = 0;
31178    int forceNewLockPath = 0;
31179
31180    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
31181             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
31182
31183    rc = proxyGetHostID(myHostID, &pError);
31184    if( (rc&0xff)==SQLITE_IOERR ){
31185      pFile->lastErrno = pError;
31186      goto end_takeconch;
31187    }
31188    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
31189    if( rc!=SQLITE_OK ){
31190      goto end_takeconch;
31191    }
31192    /* read the existing conch file */
31193    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
31194    if( readLen<0 ){
31195      /* I/O error: lastErrno set by seekAndRead */
31196      pFile->lastErrno = conchFile->lastErrno;
31197      rc = SQLITE_IOERR_READ;
31198      goto end_takeconch;
31199    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
31200             readBuf[0]!=(char)PROXY_CONCHVERSION ){
31201      /* a short read or version format mismatch means we need to create a new
31202      ** conch file.
31203      */
31204      createConch = 1;
31205    }
31206    /* if the host id matches and the lock path already exists in the conch
31207    ** we'll try to use the path there, if we can't open that path, we'll
31208    ** retry with a new auto-generated path
31209    */
31210    do { /* in case we need to try again for an :auto: named lock file */
31211
31212      if( !createConch && !forceNewLockPath ){
31213        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
31214                                  PROXY_HOSTIDLEN);
31215        /* if the conch has data compare the contents */
31216        if( !pCtx->lockProxyPath ){
31217          /* for auto-named local lock file, just check the host ID and we'll
31218           ** use the local lock file path that's already in there
31219           */
31220          if( hostIdMatch ){
31221            size_t pathLen = (readLen - PROXY_PATHINDEX);
31222
31223            if( pathLen>=MAXPATHLEN ){
31224              pathLen=MAXPATHLEN-1;
31225            }
31226            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
31227            lockPath[pathLen] = 0;
31228            tempLockPath = lockPath;
31229            tryOldLockPath = 1;
31230            /* create a copy of the lock path if the conch is taken */
31231            goto end_takeconch;
31232          }
31233        }else if( hostIdMatch
31234               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
31235                           readLen-PROXY_PATHINDEX)
31236        ){
31237          /* conch host and lock path match */
31238          goto end_takeconch;
31239        }
31240      }
31241
31242      /* if the conch isn't writable and doesn't match, we can't take it */
31243      if( (conchFile->openFlags&O_RDWR) == 0 ){
31244        rc = SQLITE_BUSY;
31245        goto end_takeconch;
31246      }
31247
31248      /* either the conch didn't match or we need to create a new one */
31249      if( !pCtx->lockProxyPath ){
31250        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
31251        tempLockPath = lockPath;
31252        /* create a copy of the lock path _only_ if the conch is taken */
31253      }
31254
31255      /* update conch with host and path (this will fail if other process
31256      ** has a shared lock already), if the host id matches, use the big
31257      ** stick.
31258      */
31259      futimes(conchFile->h, NULL);
31260      if( hostIdMatch && !createConch ){
31261        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
31262          /* We are trying for an exclusive lock but another thread in this
31263           ** same process is still holding a shared lock. */
31264          rc = SQLITE_BUSY;
31265        } else {
31266          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
31267        }
31268      }else{
31269        rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
31270      }
31271      if( rc==SQLITE_OK ){
31272        char writeBuffer[PROXY_MAXCONCHLEN];
31273        int writeSize = 0;
31274
31275        writeBuffer[0] = (char)PROXY_CONCHVERSION;
31276        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
31277        if( pCtx->lockProxyPath!=NULL ){
31278          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
31279        }else{
31280          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
31281        }
31282        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
31283        robust_ftruncate(conchFile->h, writeSize);
31284        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
31285        fsync(conchFile->h);
31286        /* If we created a new conch file (not just updated the contents of a
31287         ** valid conch file), try to match the permissions of the database
31288         */
31289        if( rc==SQLITE_OK && createConch ){
31290          struct stat buf;
31291          int err = osFstat(pFile->h, &buf);
31292          if( err==0 ){
31293            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
31294                                        S_IROTH|S_IWOTH);
31295            /* try to match the database file R/W permissions, ignore failure */
31296#ifndef SQLITE_PROXY_DEBUG
31297            osFchmod(conchFile->h, cmode);
31298#else
31299            do{
31300              rc = osFchmod(conchFile->h, cmode);
31301            }while( rc==(-1) && errno==EINTR );
31302            if( rc!=0 ){
31303              int code = errno;
31304              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
31305                      cmode, code, strerror(code));
31306            } else {
31307              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
31308            }
31309          }else{
31310            int code = errno;
31311            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
31312                    err, code, strerror(code));
31313#endif
31314          }
31315        }
31316      }
31317      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
31318
31319    end_takeconch:
31320      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
31321      if( rc==SQLITE_OK && pFile->openFlags ){
31322        int fd;
31323        if( pFile->h>=0 ){
31324          robust_close(pFile, pFile->h, __LINE__);
31325        }
31326        pFile->h = -1;
31327        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
31328        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
31329        if( fd>=0 ){
31330          pFile->h = fd;
31331        }else{
31332          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
31333           during locking */
31334        }
31335      }
31336      if( rc==SQLITE_OK && !pCtx->lockProxy ){
31337        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
31338        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
31339        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
31340          /* we couldn't create the proxy lock file with the old lock file path
31341           ** so try again via auto-naming
31342           */
31343          forceNewLockPath = 1;
31344          tryOldLockPath = 0;
31345          continue; /* go back to the do {} while start point, try again */
31346        }
31347      }
31348      if( rc==SQLITE_OK ){
31349        /* Need to make a copy of path if we extracted the value
31350         ** from the conch file or the path was allocated on the stack
31351         */
31352        if( tempLockPath ){
31353          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
31354          if( !pCtx->lockProxyPath ){
31355            rc = SQLITE_NOMEM;
31356          }
31357        }
31358      }
31359      if( rc==SQLITE_OK ){
31360        pCtx->conchHeld = 1;
31361
31362        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
31363          afpLockingContext *afpCtx;
31364          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
31365          afpCtx->dbPath = pCtx->lockProxyPath;
31366        }
31367      } else {
31368        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31369      }
31370      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
31371               rc==SQLITE_OK?"ok":"failed"));
31372      return rc;
31373    } while (1); /* in case we need to retry the :auto: lock file -
31374                 ** we should never get here except via the 'continue' call. */
31375  }
31376}
31377
31378/*
31379** If pFile holds a lock on a conch file, then release that lock.
31380*/
31381static int proxyReleaseConch(unixFile *pFile){
31382  int rc = SQLITE_OK;         /* Subroutine return code */
31383  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
31384  unixFile *conchFile;        /* Name of the conch file */
31385
31386  pCtx = (proxyLockingContext *)pFile->lockingContext;
31387  conchFile = pCtx->conchFile;
31388  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
31389           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
31390           getpid()));
31391  if( pCtx->conchHeld>0 ){
31392    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31393  }
31394  pCtx->conchHeld = 0;
31395  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
31396           (rc==SQLITE_OK ? "ok" : "failed")));
31397  return rc;
31398}
31399
31400/*
31401** Given the name of a database file, compute the name of its conch file.
31402** Store the conch filename in memory obtained from sqlite3_malloc().
31403** Make *pConchPath point to the new name.  Return SQLITE_OK on success
31404** or SQLITE_NOMEM if unable to obtain memory.
31405**
31406** The caller is responsible for ensuring that the allocated memory
31407** space is eventually freed.
31408**
31409** *pConchPath is set to NULL if a memory allocation error occurs.
31410*/
31411static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
31412  int i;                        /* Loop counter */
31413  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
31414  char *conchPath;              /* buffer in which to construct conch name */
31415
31416  /* Allocate space for the conch filename and initialize the name to
31417  ** the name of the original database file. */
31418  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
31419  if( conchPath==0 ){
31420    return SQLITE_NOMEM;
31421  }
31422  memcpy(conchPath, dbPath, len+1);
31423
31424  /* now insert a "." before the last / character */
31425  for( i=(len-1); i>=0; i-- ){
31426    if( conchPath[i]=='/' ){
31427      i++;
31428      break;
31429    }
31430  }
31431  conchPath[i]='.';
31432  while ( i<len ){
31433    conchPath[i+1]=dbPath[i];
31434    i++;
31435  }
31436
31437  /* append the "-conch" suffix to the file */
31438  memcpy(&conchPath[i+1], "-conch", 7);
31439  assert( (int)strlen(conchPath) == len+7 );
31440
31441  return SQLITE_OK;
31442}
31443
31444
31445/* Takes a fully configured proxy locking-style unix file and switches
31446** the local lock file path
31447*/
31448static int switchLockProxyPath(unixFile *pFile, const char *path) {
31449  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31450  char *oldPath = pCtx->lockProxyPath;
31451  int rc = SQLITE_OK;
31452
31453  if( pFile->eFileLock!=NO_LOCK ){
31454    return SQLITE_BUSY;
31455  }
31456
31457  /* nothing to do if the path is NULL, :auto: or matches the existing path */
31458  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
31459    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
31460    return SQLITE_OK;
31461  }else{
31462    unixFile *lockProxy = pCtx->lockProxy;
31463    pCtx->lockProxy=NULL;
31464    pCtx->conchHeld = 0;
31465    if( lockProxy!=NULL ){
31466      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
31467      if( rc ) return rc;
31468      sqlite3_free(lockProxy);
31469    }
31470    sqlite3_free(oldPath);
31471    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
31472  }
31473
31474  return rc;
31475}
31476
31477/*
31478** pFile is a file that has been opened by a prior xOpen call.  dbPath
31479** is a string buffer at least MAXPATHLEN+1 characters in size.
31480**
31481** This routine find the filename associated with pFile and writes it
31482** int dbPath.
31483*/
31484static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
31485#if defined(__APPLE__)
31486  if( pFile->pMethod == &afpIoMethods ){
31487    /* afp style keeps a reference to the db path in the filePath field
31488    ** of the struct */
31489    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31490    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
31491  } else
31492#endif
31493  if( pFile->pMethod == &dotlockIoMethods ){
31494    /* dot lock style uses the locking context to store the dot lock
31495    ** file path */
31496    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
31497    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
31498  }else{
31499    /* all other styles use the locking context to store the db file path */
31500    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31501    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
31502  }
31503  return SQLITE_OK;
31504}
31505
31506/*
31507** Takes an already filled in unix file and alters it so all file locking
31508** will be performed on the local proxy lock file.  The following fields
31509** are preserved in the locking context so that they can be restored and
31510** the unix structure properly cleaned up at close time:
31511**  ->lockingContext
31512**  ->pMethod
31513*/
31514static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
31515  proxyLockingContext *pCtx;
31516  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
31517  char *lockPath=NULL;
31518  int rc = SQLITE_OK;
31519
31520  if( pFile->eFileLock!=NO_LOCK ){
31521    return SQLITE_BUSY;
31522  }
31523  proxyGetDbPathForUnixFile(pFile, dbPath);
31524  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
31525    lockPath=NULL;
31526  }else{
31527    lockPath=(char *)path;
31528  }
31529
31530  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
31531           (lockPath ? lockPath : ":auto:"), getpid()));
31532
31533  pCtx = sqlite3_malloc( sizeof(*pCtx) );
31534  if( pCtx==0 ){
31535    return SQLITE_NOMEM;
31536  }
31537  memset(pCtx, 0, sizeof(*pCtx));
31538
31539  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
31540  if( rc==SQLITE_OK ){
31541    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
31542    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
31543      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
31544      ** (c) the file system is read-only, then enable no-locking access.
31545      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
31546      ** that openFlags will have only one of O_RDONLY or O_RDWR.
31547      */
31548      struct statfs fsInfo;
31549      struct stat conchInfo;
31550      int goLockless = 0;
31551
31552      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
31553        int err = errno;
31554        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
31555          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
31556        }
31557      }
31558      if( goLockless ){
31559        pCtx->conchHeld = -1; /* read only FS/ lockless */
31560        rc = SQLITE_OK;
31561      }
31562    }
31563  }
31564  if( rc==SQLITE_OK && lockPath ){
31565    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
31566  }
31567
31568  if( rc==SQLITE_OK ){
31569    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
31570    if( pCtx->dbPath==NULL ){
31571      rc = SQLITE_NOMEM;
31572    }
31573  }
31574  if( rc==SQLITE_OK ){
31575    /* all memory is allocated, proxys are created and assigned,
31576    ** switch the locking context and pMethod then return.
31577    */
31578    pCtx->oldLockingContext = pFile->lockingContext;
31579    pFile->lockingContext = pCtx;
31580    pCtx->pOldMethod = pFile->pMethod;
31581    pFile->pMethod = &proxyIoMethods;
31582  }else{
31583    if( pCtx->conchFile ){
31584      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
31585      sqlite3_free(pCtx->conchFile);
31586    }
31587    sqlite3DbFree(0, pCtx->lockProxyPath);
31588    sqlite3_free(pCtx->conchFilePath);
31589    sqlite3_free(pCtx);
31590  }
31591  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
31592           (rc==SQLITE_OK ? "ok" : "failed")));
31593  return rc;
31594}
31595
31596
31597/*
31598** This routine handles sqlite3_file_control() calls that are specific
31599** to proxy locking.
31600*/
31601static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
31602  switch( op ){
31603    case SQLITE_GET_LOCKPROXYFILE: {
31604      unixFile *pFile = (unixFile*)id;
31605      if( pFile->pMethod == &proxyIoMethods ){
31606        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31607        proxyTakeConch(pFile);
31608        if( pCtx->lockProxyPath ){
31609          *(const char **)pArg = pCtx->lockProxyPath;
31610        }else{
31611          *(const char **)pArg = ":auto: (not held)";
31612        }
31613      } else {
31614        *(const char **)pArg = NULL;
31615      }
31616      return SQLITE_OK;
31617    }
31618    case SQLITE_SET_LOCKPROXYFILE: {
31619      unixFile *pFile = (unixFile*)id;
31620      int rc = SQLITE_OK;
31621      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
31622      if( pArg==NULL || (const char *)pArg==0 ){
31623        if( isProxyStyle ){
31624          /* turn off proxy locking - not supported */
31625          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
31626        }else{
31627          /* turn off proxy locking - already off - NOOP */
31628          rc = SQLITE_OK;
31629        }
31630      }else{
31631        const char *proxyPath = (const char *)pArg;
31632        if( isProxyStyle ){
31633          proxyLockingContext *pCtx =
31634            (proxyLockingContext*)pFile->lockingContext;
31635          if( !strcmp(pArg, ":auto:")
31636           || (pCtx->lockProxyPath &&
31637               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
31638          ){
31639            rc = SQLITE_OK;
31640          }else{
31641            rc = switchLockProxyPath(pFile, proxyPath);
31642          }
31643        }else{
31644          /* turn on proxy file locking */
31645          rc = proxyTransformUnixFile(pFile, proxyPath);
31646        }
31647      }
31648      return rc;
31649    }
31650    default: {
31651      assert( 0 );  /* The call assures that only valid opcodes are sent */
31652    }
31653  }
31654  /*NOTREACHED*/
31655  return SQLITE_ERROR;
31656}
31657
31658/*
31659** Within this division (the proxying locking implementation) the procedures
31660** above this point are all utilities.  The lock-related methods of the
31661** proxy-locking sqlite3_io_method object follow.
31662*/
31663
31664
31665/*
31666** This routine checks if there is a RESERVED lock held on the specified
31667** file by this or any other process. If such a lock is held, set *pResOut
31668** to a non-zero value otherwise *pResOut is set to zero.  The return value
31669** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31670*/
31671static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
31672  unixFile *pFile = (unixFile*)id;
31673  int rc = proxyTakeConch(pFile);
31674  if( rc==SQLITE_OK ){
31675    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31676    if( pCtx->conchHeld>0 ){
31677      unixFile *proxy = pCtx->lockProxy;
31678      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
31679    }else{ /* conchHeld < 0 is lockless */
31680      pResOut=0;
31681    }
31682  }
31683  return rc;
31684}
31685
31686/*
31687** Lock the file with the lock specified by parameter eFileLock - one
31688** of the following:
31689**
31690**     (1) SHARED_LOCK
31691**     (2) RESERVED_LOCK
31692**     (3) PENDING_LOCK
31693**     (4) EXCLUSIVE_LOCK
31694**
31695** Sometimes when requesting one lock state, additional lock states
31696** are inserted in between.  The locking might fail on one of the later
31697** transitions leaving the lock state different from what it started but
31698** still short of its goal.  The following chart shows the allowed
31699** transitions and the inserted intermediate states:
31700**
31701**    UNLOCKED -> SHARED
31702**    SHARED -> RESERVED
31703**    SHARED -> (PENDING) -> EXCLUSIVE
31704**    RESERVED -> (PENDING) -> EXCLUSIVE
31705**    PENDING -> EXCLUSIVE
31706**
31707** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31708** routine to lower a locking level.
31709*/
31710static int proxyLock(sqlite3_file *id, int eFileLock) {
31711  unixFile *pFile = (unixFile*)id;
31712  int rc = proxyTakeConch(pFile);
31713  if( rc==SQLITE_OK ){
31714    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31715    if( pCtx->conchHeld>0 ){
31716      unixFile *proxy = pCtx->lockProxy;
31717      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
31718      pFile->eFileLock = proxy->eFileLock;
31719    }else{
31720      /* conchHeld < 0 is lockless */
31721    }
31722  }
31723  return rc;
31724}
31725
31726
31727/*
31728** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31729** must be either NO_LOCK or SHARED_LOCK.
31730**
31731** If the locking level of the file descriptor is already at or below
31732** the requested locking level, this routine is a no-op.
31733*/
31734static int proxyUnlock(sqlite3_file *id, int eFileLock) {
31735  unixFile *pFile = (unixFile*)id;
31736  int rc = proxyTakeConch(pFile);
31737  if( rc==SQLITE_OK ){
31738    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31739    if( pCtx->conchHeld>0 ){
31740      unixFile *proxy = pCtx->lockProxy;
31741      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
31742      pFile->eFileLock = proxy->eFileLock;
31743    }else{
31744      /* conchHeld < 0 is lockless */
31745    }
31746  }
31747  return rc;
31748}
31749
31750/*
31751** Close a file that uses proxy locks.
31752*/
31753static int proxyClose(sqlite3_file *id) {
31754  if( id ){
31755    unixFile *pFile = (unixFile*)id;
31756    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31757    unixFile *lockProxy = pCtx->lockProxy;
31758    unixFile *conchFile = pCtx->conchFile;
31759    int rc = SQLITE_OK;
31760
31761    if( lockProxy ){
31762      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
31763      if( rc ) return rc;
31764      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
31765      if( rc ) return rc;
31766      sqlite3_free(lockProxy);
31767      pCtx->lockProxy = 0;
31768    }
31769    if( conchFile ){
31770      if( pCtx->conchHeld ){
31771        rc = proxyReleaseConch(pFile);
31772        if( rc ) return rc;
31773      }
31774      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
31775      if( rc ) return rc;
31776      sqlite3_free(conchFile);
31777    }
31778    sqlite3DbFree(0, pCtx->lockProxyPath);
31779    sqlite3_free(pCtx->conchFilePath);
31780    sqlite3DbFree(0, pCtx->dbPath);
31781    /* restore the original locking context and pMethod then close it */
31782    pFile->lockingContext = pCtx->oldLockingContext;
31783    pFile->pMethod = pCtx->pOldMethod;
31784    sqlite3_free(pCtx);
31785    return pFile->pMethod->xClose(id);
31786  }
31787  return SQLITE_OK;
31788}
31789
31790
31791
31792#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31793/*
31794** The proxy locking style is intended for use with AFP filesystems.
31795** And since AFP is only supported on MacOSX, the proxy locking is also
31796** restricted to MacOSX.
31797**
31798**
31799******************* End of the proxy lock implementation **********************
31800******************************************************************************/
31801
31802/*
31803** Initialize the operating system interface.
31804**
31805** This routine registers all VFS implementations for unix-like operating
31806** systems.  This routine, and the sqlite3_os_end() routine that follows,
31807** should be the only routines in this file that are visible from other
31808** files.
31809**
31810** This routine is called once during SQLite initialization and by a
31811** single thread.  The memory allocation and mutex subsystems have not
31812** necessarily been initialized when this routine is called, and so they
31813** should not be used.
31814*/
31815SQLITE_API int sqlite3_os_init(void){
31816  /*
31817  ** The following macro defines an initializer for an sqlite3_vfs object.
31818  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
31819  ** to the "finder" function.  (pAppData is a pointer to a pointer because
31820  ** silly C90 rules prohibit a void* from being cast to a function pointer
31821  ** and so we have to go through the intermediate pointer to avoid problems
31822  ** when compiling with -pedantic-errors on GCC.)
31823  **
31824  ** The FINDER parameter to this macro is the name of the pointer to the
31825  ** finder-function.  The finder-function returns a pointer to the
31826  ** sqlite_io_methods object that implements the desired locking
31827  ** behaviors.  See the division above that contains the IOMETHODS
31828  ** macro for addition information on finder-functions.
31829  **
31830  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
31831  ** object.  But the "autolockIoFinder" available on MacOSX does a little
31832  ** more than that; it looks at the filesystem type that hosts the
31833  ** database file and tries to choose an locking method appropriate for
31834  ** that filesystem time.
31835  */
31836  #define UNIXVFS(VFSNAME, FINDER) {                        \
31837    3,                    /* iVersion */                    \
31838    sizeof(unixFile),     /* szOsFile */                    \
31839    MAX_PATHNAME,         /* mxPathname */                  \
31840    0,                    /* pNext */                       \
31841    VFSNAME,              /* zName */                       \
31842    (void*)&FINDER,       /* pAppData */                    \
31843    unixOpen,             /* xOpen */                       \
31844    unixDelete,           /* xDelete */                     \
31845    unixAccess,           /* xAccess */                     \
31846    unixFullPathname,     /* xFullPathname */               \
31847    unixDlOpen,           /* xDlOpen */                     \
31848    unixDlError,          /* xDlError */                    \
31849    unixDlSym,            /* xDlSym */                      \
31850    unixDlClose,          /* xDlClose */                    \
31851    unixRandomness,       /* xRandomness */                 \
31852    unixSleep,            /* xSleep */                      \
31853    unixCurrentTime,      /* xCurrentTime */                \
31854    unixGetLastError,     /* xGetLastError */               \
31855    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
31856    unixSetSystemCall,    /* xSetSystemCall */              \
31857    unixGetSystemCall,    /* xGetSystemCall */              \
31858    unixNextSystemCall,   /* xNextSystemCall */             \
31859  }
31860
31861  /*
31862  ** All default VFSes for unix are contained in the following array.
31863  **
31864  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
31865  ** by the SQLite core when the VFS is registered.  So the following
31866  ** array cannot be const.
31867  */
31868  static sqlite3_vfs aVfs[] = {
31869#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
31870    UNIXVFS("unix",          autolockIoFinder ),
31871#else
31872    UNIXVFS("unix",          posixIoFinder ),
31873#endif
31874    UNIXVFS("unix-none",     nolockIoFinder ),
31875    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
31876    UNIXVFS("unix-excl",     posixIoFinder ),
31877#if OS_VXWORKS
31878    UNIXVFS("unix-namedsem", semIoFinder ),
31879#endif
31880#if SQLITE_ENABLE_LOCKING_STYLE
31881    UNIXVFS("unix-posix",    posixIoFinder ),
31882#if !OS_VXWORKS
31883    UNIXVFS("unix-flock",    flockIoFinder ),
31884#endif
31885#endif
31886#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31887    UNIXVFS("unix-afp",      afpIoFinder ),
31888    UNIXVFS("unix-nfs",      nfsIoFinder ),
31889    UNIXVFS("unix-proxy",    proxyIoFinder ),
31890#endif
31891  };
31892  unsigned int i;          /* Loop counter */
31893
31894  /* Double-check that the aSyscall[] array has been constructed
31895  ** correctly.  See ticket [bb3a86e890c8e96ab] */
31896  assert( ArraySize(aSyscall)==22 );
31897
31898  /* Register all VFSes defined in the aVfs[] array */
31899  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
31900    sqlite3_vfs_register(&aVfs[i], i==0);
31901  }
31902  return SQLITE_OK;
31903}
31904
31905/*
31906** Shutdown the operating system interface.
31907**
31908** Some operating systems might need to do some cleanup in this routine,
31909** to release dynamically allocated objects.  But not on unix.
31910** This routine is a no-op for unix.
31911*/
31912SQLITE_API int sqlite3_os_end(void){
31913  return SQLITE_OK;
31914}
31915
31916#endif /* SQLITE_OS_UNIX */
31917
31918/************** End of os_unix.c *********************************************/
31919/************** Begin file os_win.c ******************************************/
31920/*
31921** 2004 May 22
31922**
31923** The author disclaims copyright to this source code.  In place of
31924** a legal notice, here is a blessing:
31925**
31926**    May you do good and not evil.
31927**    May you find forgiveness for yourself and forgive others.
31928**    May you share freely, never taking more than you give.
31929**
31930******************************************************************************
31931**
31932** This file contains code that is specific to Windows.
31933*/
31934#if SQLITE_OS_WIN               /* This file is used for Windows only */
31935
31936#ifdef __CYGWIN__
31937# include <sys/cygwin.h>
31938#endif
31939
31940/*
31941** Include code that is common to all os_*.c files
31942*/
31943/************** Include os_common.h in the middle of os_win.c ****************/
31944/************** Begin file os_common.h ***************************************/
31945/*
31946** 2004 May 22
31947**
31948** The author disclaims copyright to this source code.  In place of
31949** a legal notice, here is a blessing:
31950**
31951**    May you do good and not evil.
31952**    May you find forgiveness for yourself and forgive others.
31953**    May you share freely, never taking more than you give.
31954**
31955******************************************************************************
31956**
31957** This file contains macros and a little bit of code that is common to
31958** all of the platform-specific files (os_*.c) and is #included into those
31959** files.
31960**
31961** This file should be #included by the os_*.c files only.  It is not a
31962** general purpose header file.
31963*/
31964#ifndef _OS_COMMON_H_
31965#define _OS_COMMON_H_
31966
31967/*
31968** At least two bugs have slipped in because we changed the MEMORY_DEBUG
31969** macro to SQLITE_DEBUG and some older makefiles have not yet made the
31970** switch.  The following code should catch this problem at compile-time.
31971*/
31972#ifdef MEMORY_DEBUG
31973# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
31974#endif
31975
31976#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
31977# ifndef SQLITE_DEBUG_OS_TRACE
31978#   define SQLITE_DEBUG_OS_TRACE 0
31979# endif
31980  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
31981# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
31982#else
31983# define OSTRACE(X)
31984#endif
31985
31986/*
31987** Macros for performance tracing.  Normally turned off.  Only works
31988** on i486 hardware.
31989*/
31990#ifdef SQLITE_PERFORMANCE_TRACE
31991
31992/*
31993** hwtime.h contains inline assembler code for implementing
31994** high-performance timing routines.
31995*/
31996/************** Include hwtime.h in the middle of os_common.h ****************/
31997/************** Begin file hwtime.h ******************************************/
31998/*
31999** 2008 May 27
32000**
32001** The author disclaims copyright to this source code.  In place of
32002** a legal notice, here is a blessing:
32003**
32004**    May you do good and not evil.
32005**    May you find forgiveness for yourself and forgive others.
32006**    May you share freely, never taking more than you give.
32007**
32008******************************************************************************
32009**
32010** This file contains inline asm code for retrieving "high-performance"
32011** counters for x86 class CPUs.
32012*/
32013#ifndef _HWTIME_H_
32014#define _HWTIME_H_
32015
32016/*
32017** The following routine only works on pentium-class (or newer) processors.
32018** It uses the RDTSC opcode to read the cycle count value out of the
32019** processor and returns that value.  This can be used for high-res
32020** profiling.
32021*/
32022#if (defined(__GNUC__) || defined(_MSC_VER)) && \
32023      (defined(i386) || defined(__i386__) || defined(_M_IX86))
32024
32025  #if defined(__GNUC__)
32026
32027  __inline__ sqlite_uint64 sqlite3Hwtime(void){
32028     unsigned int lo, hi;
32029     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
32030     return (sqlite_uint64)hi << 32 | lo;
32031  }
32032
32033  #elif defined(_MSC_VER)
32034
32035  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
32036     __asm {
32037        rdtsc
32038        ret       ; return value at EDX:EAX
32039     }
32040  }
32041
32042  #endif
32043
32044#elif (defined(__GNUC__) && defined(__x86_64__))
32045
32046  __inline__ sqlite_uint64 sqlite3Hwtime(void){
32047      unsigned long val;
32048      __asm__ __volatile__ ("rdtsc" : "=A" (val));
32049      return val;
32050  }
32051
32052#elif (defined(__GNUC__) && defined(__ppc__))
32053
32054  __inline__ sqlite_uint64 sqlite3Hwtime(void){
32055      unsigned long long retval;
32056      unsigned long junk;
32057      __asm__ __volatile__ ("\n\
32058          1:      mftbu   %1\n\
32059                  mftb    %L0\n\
32060                  mftbu   %0\n\
32061                  cmpw    %0,%1\n\
32062                  bne     1b"
32063                  : "=r" (retval), "=r" (junk));
32064      return retval;
32065  }
32066
32067#else
32068
32069  #error Need implementation of sqlite3Hwtime() for your platform.
32070
32071  /*
32072  ** To compile without implementing sqlite3Hwtime() for your platform,
32073  ** you can remove the above #error and use the following
32074  ** stub function.  You will lose timing support for many
32075  ** of the debugging and testing utilities, but it should at
32076  ** least compile and run.
32077  */
32078SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
32079
32080#endif
32081
32082#endif /* !defined(_HWTIME_H_) */
32083
32084/************** End of hwtime.h **********************************************/
32085/************** Continuing where we left off in os_common.h ******************/
32086
32087static sqlite_uint64 g_start;
32088static sqlite_uint64 g_elapsed;
32089#define TIMER_START       g_start=sqlite3Hwtime()
32090#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
32091#define TIMER_ELAPSED     g_elapsed
32092#else
32093#define TIMER_START
32094#define TIMER_END
32095#define TIMER_ELAPSED     ((sqlite_uint64)0)
32096#endif
32097
32098/*
32099** If we compile with the SQLITE_TEST macro set, then the following block
32100** of code will give us the ability to simulate a disk I/O error.  This
32101** is used for testing the I/O recovery logic.
32102*/
32103#ifdef SQLITE_TEST
32104SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
32105SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
32106SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
32107SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
32108SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
32109SQLITE_API int sqlite3_diskfull_pending = 0;
32110SQLITE_API int sqlite3_diskfull = 0;
32111#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
32112#define SimulateIOError(CODE)  \
32113  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
32114       || sqlite3_io_error_pending-- == 1 )  \
32115              { local_ioerr(); CODE; }
32116static void local_ioerr(){
32117  IOTRACE(("IOERR\n"));
32118  sqlite3_io_error_hit++;
32119  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
32120}
32121#define SimulateDiskfullError(CODE) \
32122   if( sqlite3_diskfull_pending ){ \
32123     if( sqlite3_diskfull_pending == 1 ){ \
32124       local_ioerr(); \
32125       sqlite3_diskfull = 1; \
32126       sqlite3_io_error_hit = 1; \
32127       CODE; \
32128     }else{ \
32129       sqlite3_diskfull_pending--; \
32130     } \
32131   }
32132#else
32133#define SimulateIOErrorBenign(X)
32134#define SimulateIOError(A)
32135#define SimulateDiskfullError(A)
32136#endif
32137
32138/*
32139** When testing, keep a count of the number of open files.
32140*/
32141#ifdef SQLITE_TEST
32142SQLITE_API int sqlite3_open_file_count = 0;
32143#define OpenCounter(X)  sqlite3_open_file_count+=(X)
32144#else
32145#define OpenCounter(X)
32146#endif
32147
32148#endif /* !defined(_OS_COMMON_H_) */
32149
32150/************** End of os_common.h *******************************************/
32151/************** Continuing where we left off in os_win.c *********************/
32152
32153/*
32154** Some Microsoft compilers lack this definition.
32155*/
32156#ifndef INVALID_FILE_ATTRIBUTES
32157# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
32158#endif
32159
32160/* Forward references */
32161typedef struct winShm winShm;           /* A connection to shared-memory */
32162typedef struct winShmNode winShmNode;   /* A region of shared-memory */
32163
32164/*
32165** WinCE lacks native support for file locking so we have to fake it
32166** with some code of our own.
32167*/
32168#if SQLITE_OS_WINCE
32169typedef struct winceLock {
32170  int nReaders;       /* Number of reader locks obtained */
32171  BOOL bPending;      /* Indicates a pending lock has been obtained */
32172  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
32173  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
32174} winceLock;
32175#endif
32176
32177/*
32178** The winFile structure is a subclass of sqlite3_file* specific to the win32
32179** portability layer.
32180*/
32181typedef struct winFile winFile;
32182struct winFile {
32183  const sqlite3_io_methods *pMethod; /*** Must be first ***/
32184  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
32185  HANDLE h;               /* Handle for accessing the file */
32186  u8 locktype;            /* Type of lock currently held on this file */
32187  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
32188  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
32189  DWORD lastErrno;        /* The Windows errno from the last I/O error */
32190  winShm *pShm;           /* Instance of shared memory on this file */
32191  const char *zPath;      /* Full pathname of this file */
32192  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
32193#if SQLITE_OS_WINCE
32194  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
32195  HANDLE hMutex;          /* Mutex used to control access to shared lock */
32196  HANDLE hShared;         /* Shared memory segment used for locking */
32197  winceLock local;        /* Locks obtained by this instance of winFile */
32198  winceLock *shared;      /* Global shared lock memory for the file  */
32199#endif
32200};
32201
32202/*
32203** Allowed values for winFile.ctrlFlags
32204*/
32205#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
32206#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
32207
32208/*
32209 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
32210 * various Win32 API heap functions instead of our own.
32211 */
32212#ifdef SQLITE_WIN32_MALLOC
32213/*
32214 * The initial size of the Win32-specific heap.  This value may be zero.
32215 */
32216#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
32217#  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
32218                                       (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
32219#endif
32220
32221/*
32222 * The maximum size of the Win32-specific heap.  This value may be zero.
32223 */
32224#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
32225#  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
32226#endif
32227
32228/*
32229 * The extra flags to use in calls to the Win32 heap APIs.  This value may be
32230 * zero for the default behavior.
32231 */
32232#ifndef SQLITE_WIN32_HEAP_FLAGS
32233#  define SQLITE_WIN32_HEAP_FLAGS     (0)
32234#endif
32235
32236/*
32237** The winMemData structure stores information required by the Win32-specific
32238** sqlite3_mem_methods implementation.
32239*/
32240typedef struct winMemData winMemData;
32241struct winMemData {
32242#ifndef NDEBUG
32243  u32 magic;    /* Magic number to detect structure corruption. */
32244#endif
32245  HANDLE hHeap; /* The handle to our heap. */
32246  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
32247};
32248
32249#ifndef NDEBUG
32250#define WINMEM_MAGIC     0x42b2830b
32251#endif
32252
32253static struct winMemData win_mem_data = {
32254#ifndef NDEBUG
32255  WINMEM_MAGIC,
32256#endif
32257  NULL, FALSE
32258};
32259
32260#ifndef NDEBUG
32261#define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
32262#else
32263#define winMemAssertMagic()
32264#endif
32265
32266#define winMemGetHeap() win_mem_data.hHeap
32267
32268static void *winMemMalloc(int nBytes);
32269static void winMemFree(void *pPrior);
32270static void *winMemRealloc(void *pPrior, int nBytes);
32271static int winMemSize(void *p);
32272static int winMemRoundup(int n);
32273static int winMemInit(void *pAppData);
32274static void winMemShutdown(void *pAppData);
32275
32276SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
32277#endif /* SQLITE_WIN32_MALLOC */
32278
32279/*
32280** The following variable is (normally) set once and never changes
32281** thereafter.  It records whether the operating system is Win9x
32282** or WinNT.
32283**
32284** 0:   Operating system unknown.
32285** 1:   Operating system is Win9x.
32286** 2:   Operating system is WinNT.
32287**
32288** In order to facilitate testing on a WinNT system, the test fixture
32289** can manually set this value to 1 to emulate Win98 behavior.
32290*/
32291#ifdef SQLITE_TEST
32292SQLITE_API int sqlite3_os_type = 0;
32293#else
32294static int sqlite3_os_type = 0;
32295#endif
32296
32297/*
32298** Many system calls are accessed through pointer-to-functions so that
32299** they may be overridden at runtime to facilitate fault injection during
32300** testing and sandboxing.  The following array holds the names and pointers
32301** to all overrideable system calls.
32302*/
32303#if !SQLITE_OS_WINCE
32304#  define SQLITE_WIN32_HAS_ANSI
32305#endif
32306
32307#if SQLITE_OS_WINCE || SQLITE_OS_WINNT
32308#  define SQLITE_WIN32_HAS_WIDE
32309#endif
32310
32311#ifndef SYSCALL
32312#  define SYSCALL sqlite3_syscall_ptr
32313#endif
32314
32315#if SQLITE_OS_WINCE
32316/*
32317** These macros are necessary because Windows CE does not natively support the
32318** Win32 APIs LockFile, UnlockFile, and LockFileEx.
32319 */
32320
32321#  define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
32322#  define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
32323#  define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
32324
32325/*
32326** These are the special syscall hacks for Windows CE.  The locking related
32327** defines here refer to the macros defined just above.
32328 */
32329
32330#  define osAreFileApisANSI()       1
32331#  define osLockFile                LockFile
32332#  define osUnlockFile              UnlockFile
32333#  define osLockFileEx              LockFileEx
32334#endif
32335
32336static struct win_syscall {
32337  const char *zName;            /* Name of the sytem call */
32338  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
32339  sqlite3_syscall_ptr pDefault; /* Default value */
32340} aSyscall[] = {
32341#if !SQLITE_OS_WINCE
32342  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
32343
32344#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
32345#else
32346  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
32347#endif
32348
32349#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32350  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
32351#else
32352  { "CharLowerW",              (SYSCALL)0,                       0 },
32353#endif
32354
32355#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
32356
32357#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32358  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
32359#else
32360  { "CharUpperW",              (SYSCALL)0,                       0 },
32361#endif
32362
32363#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
32364
32365  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
32366
32367#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
32368
32369#if defined(SQLITE_WIN32_HAS_ANSI)
32370  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
32371#else
32372  { "CreateFileA",             (SYSCALL)0,                       0 },
32373#endif
32374
32375#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
32376        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
32377
32378#if defined(SQLITE_WIN32_HAS_WIDE)
32379  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
32380#else
32381  { "CreateFileW",             (SYSCALL)0,                       0 },
32382#endif
32383
32384#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
32385        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
32386
32387  { "CreateFileMapping",       (SYSCALL)CreateFileMapping,       0 },
32388
32389#define osCreateFileMapping ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
32390        DWORD,DWORD,DWORD,LPCTSTR))aSyscall[6].pCurrent)
32391
32392#if defined(SQLITE_WIN32_HAS_WIDE)
32393  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
32394#else
32395  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
32396#endif
32397
32398#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
32399        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
32400
32401#if defined(SQLITE_WIN32_HAS_WIDE)
32402  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
32403#else
32404  { "CreateMutexW",            (SYSCALL)0,                       0 },
32405#endif
32406
32407#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
32408        LPCWSTR))aSyscall[8].pCurrent)
32409
32410#if defined(SQLITE_WIN32_HAS_ANSI)
32411  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
32412#else
32413  { "DeleteFileA",             (SYSCALL)0,                       0 },
32414#endif
32415
32416#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
32417
32418#if defined(SQLITE_WIN32_HAS_WIDE)
32419  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
32420#else
32421  { "DeleteFileW",             (SYSCALL)0,                       0 },
32422#endif
32423
32424#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
32425
32426#if SQLITE_OS_WINCE
32427  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
32428#else
32429  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
32430#endif
32431
32432#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
32433        LPFILETIME))aSyscall[11].pCurrent)
32434
32435#if SQLITE_OS_WINCE
32436  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
32437#else
32438  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
32439#endif
32440
32441#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
32442        LPSYSTEMTIME))aSyscall[12].pCurrent)
32443
32444  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
32445
32446#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
32447
32448#if defined(SQLITE_WIN32_HAS_ANSI)
32449  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
32450#else
32451  { "FormatMessageA",          (SYSCALL)0,                       0 },
32452#endif
32453
32454#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
32455        DWORD,va_list*))aSyscall[14].pCurrent)
32456
32457#if defined(SQLITE_WIN32_HAS_WIDE)
32458  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
32459#else
32460  { "FormatMessageW",          (SYSCALL)0,                       0 },
32461#endif
32462
32463#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
32464        DWORD,va_list*))aSyscall[15].pCurrent)
32465
32466  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
32467
32468#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
32469
32470  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
32471
32472#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
32473
32474#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
32475  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
32476#else
32477  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
32478#endif
32479
32480#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
32481        LPDWORD))aSyscall[18].pCurrent)
32482
32483#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32484  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
32485#else
32486  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
32487#endif
32488
32489#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
32490        LPDWORD))aSyscall[19].pCurrent)
32491
32492#if defined(SQLITE_WIN32_HAS_ANSI)
32493  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
32494#else
32495  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
32496#endif
32497
32498#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
32499
32500#if defined(SQLITE_WIN32_HAS_WIDE)
32501  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
32502#else
32503  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
32504#endif
32505
32506#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
32507
32508#if defined(SQLITE_WIN32_HAS_WIDE)
32509  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
32510#else
32511  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
32512#endif
32513
32514#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
32515        LPVOID))aSyscall[22].pCurrent)
32516
32517  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
32518
32519#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
32520
32521#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
32522  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
32523#else
32524  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
32525#endif
32526
32527#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
32528        LPSTR*))aSyscall[24].pCurrent)
32529
32530#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32531  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
32532#else
32533  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
32534#endif
32535
32536#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
32537        LPWSTR*))aSyscall[25].pCurrent)
32538
32539  { "GetLastError",            (SYSCALL)GetLastError,            0 },
32540
32541#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
32542
32543#if SQLITE_OS_WINCE
32544  /* The GetProcAddressA() routine is only available on Windows CE. */
32545  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
32546#else
32547  /* All other Windows platforms expect GetProcAddress() to take
32548  ** an ANSI string regardless of the _UNICODE setting */
32549  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
32550#endif
32551
32552#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
32553        LPCSTR))aSyscall[27].pCurrent)
32554
32555  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
32556
32557#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
32558
32559  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
32560
32561#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
32562
32563#if !SQLITE_OS_WINCE
32564  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
32565#else
32566  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
32567#endif
32568
32569#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
32570        LPFILETIME))aSyscall[30].pCurrent)
32571
32572#if defined(SQLITE_WIN32_HAS_ANSI)
32573  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
32574#else
32575  { "GetTempPathA",            (SYSCALL)0,                       0 },
32576#endif
32577
32578#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
32579
32580#if defined(SQLITE_WIN32_HAS_WIDE)
32581  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
32582#else
32583  { "GetTempPathW",            (SYSCALL)0,                       0 },
32584#endif
32585
32586#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
32587
32588  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
32589
32590#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
32591
32592#if defined(SQLITE_WIN32_HAS_ANSI)
32593  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
32594#else
32595  { "GetVersionExA",           (SYSCALL)0,                       0 },
32596#endif
32597
32598#define osGetVersionExA ((BOOL(WINAPI*)( \
32599        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
32600
32601  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
32602
32603#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
32604        SIZE_T))aSyscall[35].pCurrent)
32605
32606  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
32607
32608#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
32609        SIZE_T))aSyscall[36].pCurrent)
32610
32611  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
32612
32613#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
32614
32615  { "HeapFree",                (SYSCALL)HeapFree,                0 },
32616
32617#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
32618
32619  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
32620
32621#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
32622        SIZE_T))aSyscall[39].pCurrent)
32623
32624  { "HeapSize",                (SYSCALL)HeapSize,                0 },
32625
32626#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
32627        LPCVOID))aSyscall[40].pCurrent)
32628
32629  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
32630
32631#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
32632        LPCVOID))aSyscall[41].pCurrent)
32633
32634#if defined(SQLITE_WIN32_HAS_ANSI)
32635  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
32636#else
32637  { "LoadLibraryA",            (SYSCALL)0,                       0 },
32638#endif
32639
32640#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
32641
32642#if defined(SQLITE_WIN32_HAS_WIDE)
32643  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
32644#else
32645  { "LoadLibraryW",            (SYSCALL)0,                       0 },
32646#endif
32647
32648#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
32649
32650  { "LocalFree",               (SYSCALL)LocalFree,               0 },
32651
32652#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
32653
32654#if !SQLITE_OS_WINCE
32655  { "LockFile",                (SYSCALL)LockFile,                0 },
32656
32657#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32658        DWORD))aSyscall[45].pCurrent)
32659#else
32660  { "LockFile",                (SYSCALL)0,                       0 },
32661#endif
32662
32663#if !SQLITE_OS_WINCE
32664  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
32665
32666#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
32667        LPOVERLAPPED))aSyscall[46].pCurrent)
32668#else
32669  { "LockFileEx",              (SYSCALL)0,                       0 },
32670#endif
32671
32672  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
32673
32674#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32675        SIZE_T))aSyscall[47].pCurrent)
32676
32677  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
32678
32679#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
32680        int))aSyscall[48].pCurrent)
32681
32682  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
32683
32684#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
32685        LARGE_INTEGER*))aSyscall[49].pCurrent)
32686
32687  { "ReadFile",                (SYSCALL)ReadFile,                0 },
32688
32689#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
32690        LPOVERLAPPED))aSyscall[50].pCurrent)
32691
32692  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
32693
32694#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
32695
32696  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
32697
32698#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
32699        DWORD))aSyscall[52].pCurrent)
32700
32701  { "Sleep",                   (SYSCALL)Sleep,                   0 },
32702
32703#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
32704
32705  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
32706
32707#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
32708        LPFILETIME))aSyscall[54].pCurrent)
32709
32710#if !SQLITE_OS_WINCE
32711  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
32712
32713#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32714        DWORD))aSyscall[55].pCurrent)
32715#else
32716  { "UnlockFile",              (SYSCALL)0,                       0 },
32717#endif
32718
32719#if !SQLITE_OS_WINCE
32720  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
32721
32722#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32723        LPOVERLAPPED))aSyscall[56].pCurrent)
32724#else
32725  { "UnlockFileEx",            (SYSCALL)0,                       0 },
32726#endif
32727
32728  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
32729
32730#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
32731
32732  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
32733
32734#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
32735        LPCSTR,LPBOOL))aSyscall[58].pCurrent)
32736
32737  { "WriteFile",               (SYSCALL)WriteFile,               0 },
32738
32739#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
32740        LPOVERLAPPED))aSyscall[59].pCurrent)
32741
32742}; /* End of the overrideable system calls */
32743
32744/*
32745** This is the xSetSystemCall() method of sqlite3_vfs for all of the
32746** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
32747** system call pointer, or SQLITE_NOTFOUND if there is no configurable
32748** system call named zName.
32749*/
32750static int winSetSystemCall(
32751  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
32752  const char *zName,            /* Name of system call to override */
32753  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
32754){
32755  unsigned int i;
32756  int rc = SQLITE_NOTFOUND;
32757
32758  UNUSED_PARAMETER(pNotUsed);
32759  if( zName==0 ){
32760    /* If no zName is given, restore all system calls to their default
32761    ** settings and return NULL
32762    */
32763    rc = SQLITE_OK;
32764    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32765      if( aSyscall[i].pDefault ){
32766        aSyscall[i].pCurrent = aSyscall[i].pDefault;
32767      }
32768    }
32769  }else{
32770    /* If zName is specified, operate on only the one system call
32771    ** specified.
32772    */
32773    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32774      if( strcmp(zName, aSyscall[i].zName)==0 ){
32775        if( aSyscall[i].pDefault==0 ){
32776          aSyscall[i].pDefault = aSyscall[i].pCurrent;
32777        }
32778        rc = SQLITE_OK;
32779        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
32780        aSyscall[i].pCurrent = pNewFunc;
32781        break;
32782      }
32783    }
32784  }
32785  return rc;
32786}
32787
32788/*
32789** Return the value of a system call.  Return NULL if zName is not a
32790** recognized system call name.  NULL is also returned if the system call
32791** is currently undefined.
32792*/
32793static sqlite3_syscall_ptr winGetSystemCall(
32794  sqlite3_vfs *pNotUsed,
32795  const char *zName
32796){
32797  unsigned int i;
32798
32799  UNUSED_PARAMETER(pNotUsed);
32800  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32801    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
32802  }
32803  return 0;
32804}
32805
32806/*
32807** Return the name of the first system call after zName.  If zName==NULL
32808** then return the name of the first system call.  Return NULL if zName
32809** is the last system call or if zName is not the name of a valid
32810** system call.
32811*/
32812static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
32813  int i = -1;
32814
32815  UNUSED_PARAMETER(p);
32816  if( zName ){
32817    for(i=0; i<ArraySize(aSyscall)-1; i++){
32818      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
32819    }
32820  }
32821  for(i++; i<ArraySize(aSyscall); i++){
32822    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
32823  }
32824  return 0;
32825}
32826
32827/*
32828** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
32829** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
32830**
32831** Here is an interesting observation:  Win95, Win98, and WinME lack
32832** the LockFileEx() API.  But we can still statically link against that
32833** API as long as we don't call it when running Win95/98/ME.  A call to
32834** this routine is used to determine if the host is Win95/98/ME or
32835** WinNT/2K/XP so that we will know whether or not we can safely call
32836** the LockFileEx() API.
32837*/
32838#if SQLITE_OS_WINCE
32839# define isNT()  (1)
32840#else
32841  static int isNT(void){
32842    if( sqlite3_os_type==0 ){
32843      OSVERSIONINFOA sInfo;
32844      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
32845      osGetVersionExA(&sInfo);
32846      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
32847    }
32848    return sqlite3_os_type==2;
32849  }
32850#endif /* SQLITE_OS_WINCE */
32851
32852#ifdef SQLITE_WIN32_MALLOC
32853/*
32854** Allocate nBytes of memory.
32855*/
32856static void *winMemMalloc(int nBytes){
32857  HANDLE hHeap;
32858  void *p;
32859
32860  winMemAssertMagic();
32861  hHeap = winMemGetHeap();
32862  assert( hHeap!=0 );
32863  assert( hHeap!=INVALID_HANDLE_VALUE );
32864#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32865  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32866#endif
32867  assert( nBytes>=0 );
32868  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
32869  if( !p ){
32870    sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
32871                nBytes, osGetLastError(), (void*)hHeap);
32872  }
32873  return p;
32874}
32875
32876/*
32877** Free memory.
32878*/
32879static void winMemFree(void *pPrior){
32880  HANDLE hHeap;
32881
32882  winMemAssertMagic();
32883  hHeap = winMemGetHeap();
32884  assert( hHeap!=0 );
32885  assert( hHeap!=INVALID_HANDLE_VALUE );
32886#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32887  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
32888#endif
32889  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
32890  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
32891    sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
32892                pPrior, osGetLastError(), (void*)hHeap);
32893  }
32894}
32895
32896/*
32897** Change the size of an existing memory allocation
32898*/
32899static void *winMemRealloc(void *pPrior, int nBytes){
32900  HANDLE hHeap;
32901  void *p;
32902
32903  winMemAssertMagic();
32904  hHeap = winMemGetHeap();
32905  assert( hHeap!=0 );
32906  assert( hHeap!=INVALID_HANDLE_VALUE );
32907#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32908  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
32909#endif
32910  assert( nBytes>=0 );
32911  if( !pPrior ){
32912    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
32913  }else{
32914    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
32915  }
32916  if( !p ){
32917    sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
32918                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
32919                (void*)hHeap);
32920  }
32921  return p;
32922}
32923
32924/*
32925** Return the size of an outstanding allocation, in bytes.
32926*/
32927static int winMemSize(void *p){
32928  HANDLE hHeap;
32929  SIZE_T n;
32930
32931  winMemAssertMagic();
32932  hHeap = winMemGetHeap();
32933  assert( hHeap!=0 );
32934  assert( hHeap!=INVALID_HANDLE_VALUE );
32935#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32936  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32937#endif
32938  if( !p ) return 0;
32939  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
32940  if( n==(SIZE_T)-1 ){
32941    sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
32942                p, osGetLastError(), (void*)hHeap);
32943    return 0;
32944  }
32945  return (int)n;
32946}
32947
32948/*
32949** Round up a request size to the next valid allocation size.
32950*/
32951static int winMemRoundup(int n){
32952  return n;
32953}
32954
32955/*
32956** Initialize this module.
32957*/
32958static int winMemInit(void *pAppData){
32959  winMemData *pWinMemData = (winMemData *)pAppData;
32960
32961  if( !pWinMemData ) return SQLITE_ERROR;
32962  assert( pWinMemData->magic==WINMEM_MAGIC );
32963  if( !pWinMemData->hHeap ){
32964    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
32965                                      SQLITE_WIN32_HEAP_INIT_SIZE,
32966                                      SQLITE_WIN32_HEAP_MAX_SIZE);
32967    if( !pWinMemData->hHeap ){
32968      sqlite3_log(SQLITE_NOMEM,
32969          "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
32970          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
32971          SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
32972      return SQLITE_NOMEM;
32973    }
32974    pWinMemData->bOwned = TRUE;
32975  }
32976  assert( pWinMemData->hHeap!=0 );
32977  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
32978#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32979  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32980#endif
32981  return SQLITE_OK;
32982}
32983
32984/*
32985** Deinitialize this module.
32986*/
32987static void winMemShutdown(void *pAppData){
32988  winMemData *pWinMemData = (winMemData *)pAppData;
32989
32990  if( !pWinMemData ) return;
32991  if( pWinMemData->hHeap ){
32992    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
32993#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32994    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32995#endif
32996    if( pWinMemData->bOwned ){
32997      if( !osHeapDestroy(pWinMemData->hHeap) ){
32998        sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
32999                    osGetLastError(), (void*)pWinMemData->hHeap);
33000      }
33001      pWinMemData->bOwned = FALSE;
33002    }
33003    pWinMemData->hHeap = NULL;
33004  }
33005}
33006
33007/*
33008** Populate the low-level memory allocation function pointers in
33009** sqlite3GlobalConfig.m with pointers to the routines in this file. The
33010** arguments specify the block of memory to manage.
33011**
33012** This routine is only called by sqlite3_config(), and therefore
33013** is not required to be threadsafe (it is not).
33014*/
33015SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
33016  static const sqlite3_mem_methods winMemMethods = {
33017    winMemMalloc,
33018    winMemFree,
33019    winMemRealloc,
33020    winMemSize,
33021    winMemRoundup,
33022    winMemInit,
33023    winMemShutdown,
33024    &win_mem_data
33025  };
33026  return &winMemMethods;
33027}
33028
33029SQLITE_PRIVATE void sqlite3MemSetDefault(void){
33030  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
33031}
33032#endif /* SQLITE_WIN32_MALLOC */
33033
33034/*
33035** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
33036**
33037** Space to hold the returned string is obtained from malloc.
33038*/
33039static LPWSTR utf8ToUnicode(const char *zFilename){
33040  int nChar;
33041  LPWSTR zWideFilename;
33042
33043  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
33044  if( nChar==0 ){
33045    return 0;
33046  }
33047  zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );
33048  if( zWideFilename==0 ){
33049    return 0;
33050  }
33051  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
33052                                nChar);
33053  if( nChar==0 ){
33054    sqlite3_free(zWideFilename);
33055    zWideFilename = 0;
33056  }
33057  return zWideFilename;
33058}
33059
33060/*
33061** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
33062** obtained from sqlite3_malloc().
33063*/
33064static char *unicodeToUtf8(LPCWSTR zWideFilename){
33065  int nByte;
33066  char *zFilename;
33067
33068  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
33069  if( nByte == 0 ){
33070    return 0;
33071  }
33072  zFilename = sqlite3_malloc( nByte );
33073  if( zFilename==0 ){
33074    return 0;
33075  }
33076  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
33077                                0, 0);
33078  if( nByte == 0 ){
33079    sqlite3_free(zFilename);
33080    zFilename = 0;
33081  }
33082  return zFilename;
33083}
33084
33085/*
33086** Convert an ANSI string to Microsoft Unicode, based on the
33087** current codepage settings for file apis.
33088**
33089** Space to hold the returned string is obtained
33090** from sqlite3_malloc.
33091*/
33092static LPWSTR mbcsToUnicode(const char *zFilename){
33093  int nByte;
33094  LPWSTR zMbcsFilename;
33095  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
33096
33097  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
33098                                0)*sizeof(WCHAR);
33099  if( nByte==0 ){
33100    return 0;
33101  }
33102  zMbcsFilename = sqlite3_malloc( nByte*sizeof(zMbcsFilename[0]) );
33103  if( zMbcsFilename==0 ){
33104    return 0;
33105  }
33106  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
33107                                nByte);
33108  if( nByte==0 ){
33109    sqlite3_free(zMbcsFilename);
33110    zMbcsFilename = 0;
33111  }
33112  return zMbcsFilename;
33113}
33114
33115/*
33116** Convert Microsoft Unicode to multi-byte character string, based on the
33117** user's ANSI codepage.
33118**
33119** Space to hold the returned string is obtained from
33120** sqlite3_malloc().
33121*/
33122static char *unicodeToMbcs(LPCWSTR zWideFilename){
33123  int nByte;
33124  char *zFilename;
33125  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
33126
33127  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
33128  if( nByte == 0 ){
33129    return 0;
33130  }
33131  zFilename = sqlite3_malloc( nByte );
33132  if( zFilename==0 ){
33133    return 0;
33134  }
33135  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
33136                                nByte, 0, 0);
33137  if( nByte == 0 ){
33138    sqlite3_free(zFilename);
33139    zFilename = 0;
33140  }
33141  return zFilename;
33142}
33143
33144/*
33145** Convert multibyte character string to UTF-8.  Space to hold the
33146** returned string is obtained from sqlite3_malloc().
33147*/
33148SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
33149  char *zFilenameUtf8;
33150  LPWSTR zTmpWide;
33151
33152  zTmpWide = mbcsToUnicode(zFilename);
33153  if( zTmpWide==0 ){
33154    return 0;
33155  }
33156  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
33157  sqlite3_free(zTmpWide);
33158  return zFilenameUtf8;
33159}
33160
33161/*
33162** Convert UTF-8 to multibyte character string.  Space to hold the
33163** returned string is obtained from sqlite3_malloc().
33164*/
33165SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
33166  char *zFilenameMbcs;
33167  LPWSTR zTmpWide;
33168
33169  zTmpWide = utf8ToUnicode(zFilename);
33170  if( zTmpWide==0 ){
33171    return 0;
33172  }
33173  zFilenameMbcs = unicodeToMbcs(zTmpWide);
33174  sqlite3_free(zTmpWide);
33175  return zFilenameMbcs;
33176}
33177
33178
33179/*
33180** The return value of getLastErrorMsg
33181** is zero if the error message fits in the buffer, or non-zero
33182** otherwise (if the message was truncated).
33183*/
33184static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
33185  /* FormatMessage returns 0 on failure.  Otherwise it
33186  ** returns the number of TCHARs written to the output
33187  ** buffer, excluding the terminating null char.
33188  */
33189  DWORD dwLen = 0;
33190  char *zOut = 0;
33191
33192  if( isNT() ){
33193    LPWSTR zTempWide = NULL;
33194    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33195                             FORMAT_MESSAGE_FROM_SYSTEM |
33196                             FORMAT_MESSAGE_IGNORE_INSERTS,
33197                             NULL,
33198                             lastErrno,
33199                             0,
33200                             (LPWSTR) &zTempWide,
33201                             0,
33202                             0);
33203    if( dwLen > 0 ){
33204      /* allocate a buffer and convert to UTF8 */
33205      sqlite3BeginBenignMalloc();
33206      zOut = unicodeToUtf8(zTempWide);
33207      sqlite3EndBenignMalloc();
33208      /* free the system buffer allocated by FormatMessage */
33209      osLocalFree(zTempWide);
33210    }
33211/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33212** Since the ANSI version of these Windows API do not exist for WINCE,
33213** it's important to not reference them for WINCE builds.
33214*/
33215#if SQLITE_OS_WINCE==0
33216  }else{
33217    char *zTemp = NULL;
33218    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33219                             FORMAT_MESSAGE_FROM_SYSTEM |
33220                             FORMAT_MESSAGE_IGNORE_INSERTS,
33221                             NULL,
33222                             lastErrno,
33223                             0,
33224                             (LPSTR) &zTemp,
33225                             0,
33226                             0);
33227    if( dwLen > 0 ){
33228      /* allocate a buffer and convert to UTF8 */
33229      sqlite3BeginBenignMalloc();
33230      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33231      sqlite3EndBenignMalloc();
33232      /* free the system buffer allocated by FormatMessage */
33233      osLocalFree(zTemp);
33234    }
33235#endif
33236  }
33237  if( 0 == dwLen ){
33238    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
33239  }else{
33240    /* copy a maximum of nBuf chars to output buffer */
33241    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
33242    /* free the UTF8 buffer */
33243    sqlite3_free(zOut);
33244  }
33245  return 0;
33246}
33247
33248/*
33249**
33250** This function - winLogErrorAtLine() - is only ever called via the macro
33251** winLogError().
33252**
33253** This routine is invoked after an error occurs in an OS function.
33254** It logs a message using sqlite3_log() containing the current value of
33255** error code and, if possible, the human-readable equivalent from
33256** FormatMessage.
33257**
33258** The first argument passed to the macro should be the error code that
33259** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
33260** The two subsequent arguments should be the name of the OS function that
33261** failed and the the associated file-system path, if any.
33262*/
33263#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
33264static int winLogErrorAtLine(
33265  int errcode,                    /* SQLite error code */
33266  DWORD lastErrno,                /* Win32 last error */
33267  const char *zFunc,              /* Name of OS function that failed */
33268  const char *zPath,              /* File path associated with error */
33269  int iLine                       /* Source line number where error occurred */
33270){
33271  char zMsg[500];                 /* Human readable error text */
33272  int i;                          /* Loop counter */
33273
33274  zMsg[0] = 0;
33275  getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
33276  assert( errcode!=SQLITE_OK );
33277  if( zPath==0 ) zPath = "";
33278  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
33279  zMsg[i] = 0;
33280  sqlite3_log(errcode,
33281      "os_win.c:%d: (%d) %s(%s) - %s",
33282      iLine, lastErrno, zFunc, zPath, zMsg
33283  );
33284
33285  return errcode;
33286}
33287
33288/*
33289** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
33290** will be retried following a locking error - probably caused by
33291** antivirus software.  Also the initial delay before the first retry.
33292** The delay increases linearly with each retry.
33293*/
33294#ifndef SQLITE_WIN32_IOERR_RETRY
33295# define SQLITE_WIN32_IOERR_RETRY 10
33296#endif
33297#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
33298# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
33299#endif
33300static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
33301static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
33302
33303/*
33304** If a ReadFile() or WriteFile() error occurs, invoke this routine
33305** to see if it should be retried.  Return TRUE to retry.  Return FALSE
33306** to give up with an error.
33307*/
33308static int retryIoerr(int *pnRetry, DWORD *pError){
33309  DWORD e = osGetLastError();
33310  if( *pnRetry>=win32IoerrRetry ){
33311    if( pError ){
33312      *pError = e;
33313    }
33314    return 0;
33315  }
33316  if( e==ERROR_ACCESS_DENIED ||
33317      e==ERROR_LOCK_VIOLATION ||
33318      e==ERROR_SHARING_VIOLATION ){
33319    osSleep(win32IoerrRetryDelay*(1+*pnRetry));
33320    ++*pnRetry;
33321    return 1;
33322  }
33323  if( pError ){
33324    *pError = e;
33325  }
33326  return 0;
33327}
33328
33329/*
33330** Log a I/O error retry episode.
33331*/
33332static void logIoerr(int nRetry){
33333  if( nRetry ){
33334    sqlite3_log(SQLITE_IOERR,
33335      "delayed %dms for lock/sharing conflict",
33336      win32IoerrRetryDelay*nRetry*(nRetry+1)/2
33337    );
33338  }
33339}
33340
33341#if SQLITE_OS_WINCE
33342/*************************************************************************
33343** This section contains code for WinCE only.
33344*/
33345/*
33346** Windows CE does not have a localtime() function.  So create a
33347** substitute.
33348*/
33349/* #include <time.h> */
33350struct tm *__cdecl localtime(const time_t *t)
33351{
33352  static struct tm y;
33353  FILETIME uTm, lTm;
33354  SYSTEMTIME pTm;
33355  sqlite3_int64 t64;
33356  t64 = *t;
33357  t64 = (t64 + 11644473600)*10000000;
33358  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
33359  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
33360  osFileTimeToLocalFileTime(&uTm,&lTm);
33361  osFileTimeToSystemTime(&lTm,&pTm);
33362  y.tm_year = pTm.wYear - 1900;
33363  y.tm_mon = pTm.wMonth - 1;
33364  y.tm_wday = pTm.wDayOfWeek;
33365  y.tm_mday = pTm.wDay;
33366  y.tm_hour = pTm.wHour;
33367  y.tm_min = pTm.wMinute;
33368  y.tm_sec = pTm.wSecond;
33369  return &y;
33370}
33371
33372#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
33373
33374/*
33375** Acquire a lock on the handle h
33376*/
33377static void winceMutexAcquire(HANDLE h){
33378   DWORD dwErr;
33379   do {
33380     dwErr = WaitForSingleObject(h, INFINITE);
33381   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
33382}
33383/*
33384** Release a lock acquired by winceMutexAcquire()
33385*/
33386#define winceMutexRelease(h) ReleaseMutex(h)
33387
33388/*
33389** Create the mutex and shared memory used for locking in the file
33390** descriptor pFile
33391*/
33392static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
33393  LPWSTR zTok;
33394  LPWSTR zName;
33395  BOOL bInit = TRUE;
33396
33397  zName = utf8ToUnicode(zFilename);
33398  if( zName==0 ){
33399    /* out of memory */
33400    return FALSE;
33401  }
33402
33403  /* Initialize the local lockdata */
33404  memset(&pFile->local, 0, sizeof(pFile->local));
33405
33406  /* Replace the backslashes from the filename and lowercase it
33407  ** to derive a mutex name. */
33408  zTok = osCharLowerW(zName);
33409  for (;*zTok;zTok++){
33410    if (*zTok == '\\') *zTok = '_';
33411  }
33412
33413  /* Create/open the named mutex */
33414  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
33415  if (!pFile->hMutex){
33416    pFile->lastErrno = osGetLastError();
33417    winLogError(SQLITE_ERROR, pFile->lastErrno, "winceCreateLock1", zFilename);
33418    sqlite3_free(zName);
33419    return FALSE;
33420  }
33421
33422  /* Acquire the mutex before continuing */
33423  winceMutexAcquire(pFile->hMutex);
33424
33425  /* Since the names of named mutexes, semaphores, file mappings etc are
33426  ** case-sensitive, take advantage of that by uppercasing the mutex name
33427  ** and using that as the shared filemapping name.
33428  */
33429  osCharUpperW(zName);
33430  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
33431                                        PAGE_READWRITE, 0, sizeof(winceLock),
33432                                        zName);
33433
33434  /* Set a flag that indicates we're the first to create the memory so it
33435  ** must be zero-initialized */
33436  if (osGetLastError() == ERROR_ALREADY_EXISTS){
33437    bInit = FALSE;
33438  }
33439
33440  sqlite3_free(zName);
33441
33442  /* If we succeeded in making the shared memory handle, map it. */
33443  if (pFile->hShared){
33444    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
33445             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
33446    /* If mapping failed, close the shared memory handle and erase it */
33447    if (!pFile->shared){
33448      pFile->lastErrno = osGetLastError();
33449      winLogError(SQLITE_ERROR, pFile->lastErrno,
33450               "winceCreateLock2", zFilename);
33451      osCloseHandle(pFile->hShared);
33452      pFile->hShared = NULL;
33453    }
33454  }
33455
33456  /* If shared memory could not be created, then close the mutex and fail */
33457  if (pFile->hShared == NULL){
33458    winceMutexRelease(pFile->hMutex);
33459    osCloseHandle(pFile->hMutex);
33460    pFile->hMutex = NULL;
33461    return FALSE;
33462  }
33463
33464  /* Initialize the shared memory if we're supposed to */
33465  if (bInit) {
33466    memset(pFile->shared, 0, sizeof(winceLock));
33467  }
33468
33469  winceMutexRelease(pFile->hMutex);
33470  return TRUE;
33471}
33472
33473/*
33474** Destroy the part of winFile that deals with wince locks
33475*/
33476static void winceDestroyLock(winFile *pFile){
33477  if (pFile->hMutex){
33478    /* Acquire the mutex */
33479    winceMutexAcquire(pFile->hMutex);
33480
33481    /* The following blocks should probably assert in debug mode, but they
33482       are to cleanup in case any locks remained open */
33483    if (pFile->local.nReaders){
33484      pFile->shared->nReaders --;
33485    }
33486    if (pFile->local.bReserved){
33487      pFile->shared->bReserved = FALSE;
33488    }
33489    if (pFile->local.bPending){
33490      pFile->shared->bPending = FALSE;
33491    }
33492    if (pFile->local.bExclusive){
33493      pFile->shared->bExclusive = FALSE;
33494    }
33495
33496    /* De-reference and close our copy of the shared memory handle */
33497    osUnmapViewOfFile(pFile->shared);
33498    osCloseHandle(pFile->hShared);
33499
33500    /* Done with the mutex */
33501    winceMutexRelease(pFile->hMutex);
33502    osCloseHandle(pFile->hMutex);
33503    pFile->hMutex = NULL;
33504  }
33505}
33506
33507/*
33508** An implementation of the LockFile() API of Windows for CE
33509*/
33510static BOOL winceLockFile(
33511  HANDLE *phFile,
33512  DWORD dwFileOffsetLow,
33513  DWORD dwFileOffsetHigh,
33514  DWORD nNumberOfBytesToLockLow,
33515  DWORD nNumberOfBytesToLockHigh
33516){
33517  winFile *pFile = HANDLE_TO_WINFILE(phFile);
33518  BOOL bReturn = FALSE;
33519
33520  UNUSED_PARAMETER(dwFileOffsetHigh);
33521  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
33522
33523  if (!pFile->hMutex) return TRUE;
33524  winceMutexAcquire(pFile->hMutex);
33525
33526  /* Wanting an exclusive lock? */
33527  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
33528       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
33529    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
33530       pFile->shared->bExclusive = TRUE;
33531       pFile->local.bExclusive = TRUE;
33532       bReturn = TRUE;
33533    }
33534  }
33535
33536  /* Want a read-only lock? */
33537  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
33538           nNumberOfBytesToLockLow == 1){
33539    if (pFile->shared->bExclusive == 0){
33540      pFile->local.nReaders ++;
33541      if (pFile->local.nReaders == 1){
33542        pFile->shared->nReaders ++;
33543      }
33544      bReturn = TRUE;
33545    }
33546  }
33547
33548  /* Want a pending lock? */
33549  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
33550    /* If no pending lock has been acquired, then acquire it */
33551    if (pFile->shared->bPending == 0) {
33552      pFile->shared->bPending = TRUE;
33553      pFile->local.bPending = TRUE;
33554      bReturn = TRUE;
33555    }
33556  }
33557
33558  /* Want a reserved lock? */
33559  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
33560    if (pFile->shared->bReserved == 0) {
33561      pFile->shared->bReserved = TRUE;
33562      pFile->local.bReserved = TRUE;
33563      bReturn = TRUE;
33564    }
33565  }
33566
33567  winceMutexRelease(pFile->hMutex);
33568  return bReturn;
33569}
33570
33571/*
33572** An implementation of the UnlockFile API of Windows for CE
33573*/
33574static BOOL winceUnlockFile(
33575  HANDLE *phFile,
33576  DWORD dwFileOffsetLow,
33577  DWORD dwFileOffsetHigh,
33578  DWORD nNumberOfBytesToUnlockLow,
33579  DWORD nNumberOfBytesToUnlockHigh
33580){
33581  winFile *pFile = HANDLE_TO_WINFILE(phFile);
33582  BOOL bReturn = FALSE;
33583
33584  UNUSED_PARAMETER(dwFileOffsetHigh);
33585  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
33586
33587  if (!pFile->hMutex) return TRUE;
33588  winceMutexAcquire(pFile->hMutex);
33589
33590  /* Releasing a reader lock or an exclusive lock */
33591  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
33592    /* Did we have an exclusive lock? */
33593    if (pFile->local.bExclusive){
33594      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
33595      pFile->local.bExclusive = FALSE;
33596      pFile->shared->bExclusive = FALSE;
33597      bReturn = TRUE;
33598    }
33599
33600    /* Did we just have a reader lock? */
33601    else if (pFile->local.nReaders){
33602      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
33603      pFile->local.nReaders --;
33604      if (pFile->local.nReaders == 0)
33605      {
33606        pFile->shared->nReaders --;
33607      }
33608      bReturn = TRUE;
33609    }
33610  }
33611
33612  /* Releasing a pending lock */
33613  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
33614    if (pFile->local.bPending){
33615      pFile->local.bPending = FALSE;
33616      pFile->shared->bPending = FALSE;
33617      bReturn = TRUE;
33618    }
33619  }
33620  /* Releasing a reserved lock */
33621  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
33622    if (pFile->local.bReserved) {
33623      pFile->local.bReserved = FALSE;
33624      pFile->shared->bReserved = FALSE;
33625      bReturn = TRUE;
33626    }
33627  }
33628
33629  winceMutexRelease(pFile->hMutex);
33630  return bReturn;
33631}
33632
33633/*
33634** An implementation of the LockFileEx() API of Windows for CE
33635*/
33636static BOOL winceLockFileEx(
33637  HANDLE *phFile,
33638  DWORD dwFlags,
33639  DWORD dwReserved,
33640  DWORD nNumberOfBytesToLockLow,
33641  DWORD nNumberOfBytesToLockHigh,
33642  LPOVERLAPPED lpOverlapped
33643){
33644  UNUSED_PARAMETER(dwReserved);
33645  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
33646
33647  /* If the caller wants a shared read lock, forward this call
33648  ** to winceLockFile */
33649  if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
33650      dwFlags == 1 &&
33651      nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
33652    return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
33653  }
33654  return FALSE;
33655}
33656/*
33657** End of the special code for wince
33658*****************************************************************************/
33659#endif /* SQLITE_OS_WINCE */
33660
33661/*****************************************************************************
33662** The next group of routines implement the I/O methods specified
33663** by the sqlite3_io_methods object.
33664******************************************************************************/
33665
33666/*
33667** Some Microsoft compilers lack this definition.
33668*/
33669#ifndef INVALID_SET_FILE_POINTER
33670# define INVALID_SET_FILE_POINTER ((DWORD)-1)
33671#endif
33672
33673/*
33674** Move the current position of the file handle passed as the first
33675** argument to offset iOffset within the file. If successful, return 0.
33676** Otherwise, set pFile->lastErrno and return non-zero.
33677*/
33678static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
33679  LONG upperBits;                 /* Most sig. 32 bits of new offset */
33680  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
33681  DWORD dwRet;                    /* Value returned by SetFilePointer() */
33682  DWORD lastErrno;                /* Value returned by GetLastError() */
33683
33684  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
33685  lowerBits = (LONG)(iOffset & 0xffffffff);
33686
33687  /* API oddity: If successful, SetFilePointer() returns a dword
33688  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
33689  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
33690  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
33691  ** whether an error has actually occured, it is also necessary to call
33692  ** GetLastError().
33693  */
33694  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
33695
33696  if( (dwRet==INVALID_SET_FILE_POINTER
33697      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
33698    pFile->lastErrno = lastErrno;
33699    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
33700             "seekWinFile", pFile->zPath);
33701    return 1;
33702  }
33703
33704  return 0;
33705}
33706
33707/*
33708** Close a file.
33709**
33710** It is reported that an attempt to close a handle might sometimes
33711** fail.  This is a very unreasonable result, but Windows is notorious
33712** for being unreasonable so I do not doubt that it might happen.  If
33713** the close fails, we pause for 100 milliseconds and try again.  As
33714** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
33715** giving up and returning an error.
33716*/
33717#define MX_CLOSE_ATTEMPT 3
33718static int winClose(sqlite3_file *id){
33719  int rc, cnt = 0;
33720  winFile *pFile = (winFile*)id;
33721
33722  assert( id!=0 );
33723  assert( pFile->pShm==0 );
33724  OSTRACE(("CLOSE %d\n", pFile->h));
33725  do{
33726    rc = osCloseHandle(pFile->h);
33727    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
33728  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (osSleep(100), 1) );
33729#if SQLITE_OS_WINCE
33730#define WINCE_DELETION_ATTEMPTS 3
33731  winceDestroyLock(pFile);
33732  if( pFile->zDeleteOnClose ){
33733    int cnt = 0;
33734    while(
33735           osDeleteFileW(pFile->zDeleteOnClose)==0
33736        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
33737        && cnt++ < WINCE_DELETION_ATTEMPTS
33738    ){
33739       osSleep(100);  /* Wait a little before trying again */
33740    }
33741    sqlite3_free(pFile->zDeleteOnClose);
33742  }
33743#endif
33744  OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
33745  OpenCounter(-1);
33746  return rc ? SQLITE_OK
33747            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
33748                          "winClose", pFile->zPath);
33749}
33750
33751/*
33752** Read data from a file into a buffer.  Return SQLITE_OK if all
33753** bytes were read successfully and SQLITE_IOERR if anything goes
33754** wrong.
33755*/
33756static int winRead(
33757  sqlite3_file *id,          /* File to read from */
33758  void *pBuf,                /* Write content into this buffer */
33759  int amt,                   /* Number of bytes to read */
33760  sqlite3_int64 offset       /* Begin reading at this offset */
33761){
33762  winFile *pFile = (winFile*)id;  /* file handle */
33763  DWORD nRead;                    /* Number of bytes actually read from file */
33764  int nRetry = 0;                 /* Number of retrys */
33765
33766  assert( id!=0 );
33767  SimulateIOError(return SQLITE_IOERR_READ);
33768  OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
33769
33770  if( seekWinFile(pFile, offset) ){
33771    return SQLITE_FULL;
33772  }
33773  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
33774    DWORD lastErrno;
33775    if( retryIoerr(&nRetry, &lastErrno) ) continue;
33776    pFile->lastErrno = lastErrno;
33777    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
33778             "winRead", pFile->zPath);
33779  }
33780  logIoerr(nRetry);
33781  if( nRead<(DWORD)amt ){
33782    /* Unread parts of the buffer must be zero-filled */
33783    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
33784    return SQLITE_IOERR_SHORT_READ;
33785  }
33786
33787  return SQLITE_OK;
33788}
33789
33790/*
33791** Write data from a buffer into a file.  Return SQLITE_OK on success
33792** or some other error code on failure.
33793*/
33794static int winWrite(
33795  sqlite3_file *id,               /* File to write into */
33796  const void *pBuf,               /* The bytes to be written */
33797  int amt,                        /* Number of bytes to write */
33798  sqlite3_int64 offset            /* Offset into the file to begin writing at */
33799){
33800  int rc;                         /* True if error has occured, else false */
33801  winFile *pFile = (winFile*)id;  /* File handle */
33802  int nRetry = 0;                 /* Number of retries */
33803
33804  assert( amt>0 );
33805  assert( pFile );
33806  SimulateIOError(return SQLITE_IOERR_WRITE);
33807  SimulateDiskfullError(return SQLITE_FULL);
33808
33809  OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
33810
33811  rc = seekWinFile(pFile, offset);
33812  if( rc==0 ){
33813    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
33814    int nRem = amt;               /* Number of bytes yet to be written */
33815    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
33816    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
33817
33818    while( nRem>0 ){
33819      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
33820        if( retryIoerr(&nRetry, &lastErrno) ) continue;
33821        break;
33822      }
33823      if( nWrite<=0 ) break;
33824      aRem += nWrite;
33825      nRem -= nWrite;
33826    }
33827    if( nRem>0 ){
33828      pFile->lastErrno = lastErrno;
33829      rc = 1;
33830    }
33831  }
33832
33833  if( rc ){
33834    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
33835       || ( pFile->lastErrno==ERROR_DISK_FULL )){
33836      return SQLITE_FULL;
33837    }
33838    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
33839             "winWrite", pFile->zPath);
33840  }else{
33841    logIoerr(nRetry);
33842  }
33843  return SQLITE_OK;
33844}
33845
33846/*
33847** Truncate an open file to a specified size
33848*/
33849static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
33850  winFile *pFile = (winFile*)id;  /* File handle object */
33851  int rc = SQLITE_OK;             /* Return code for this function */
33852
33853  assert( pFile );
33854
33855  OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
33856  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
33857
33858  /* If the user has configured a chunk-size for this file, truncate the
33859  ** file so that it consists of an integer number of chunks (i.e. the
33860  ** actual file size after the operation may be larger than the requested
33861  ** size).
33862  */
33863  if( pFile->szChunk>0 ){
33864    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
33865  }
33866
33867  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
33868  if( seekWinFile(pFile, nByte) ){
33869    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33870             "winTruncate1", pFile->zPath);
33871  }else if( 0==osSetEndOfFile(pFile->h) ){
33872    pFile->lastErrno = osGetLastError();
33873    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33874             "winTruncate2", pFile->zPath);
33875  }
33876
33877  OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
33878  return rc;
33879}
33880
33881#ifdef SQLITE_TEST
33882/*
33883** Count the number of fullsyncs and normal syncs.  This is used to test
33884** that syncs and fullsyncs are occuring at the right times.
33885*/
33886SQLITE_API int sqlite3_sync_count = 0;
33887SQLITE_API int sqlite3_fullsync_count = 0;
33888#endif
33889
33890/*
33891** Make sure all writes to a particular file are committed to disk.
33892*/
33893static int winSync(sqlite3_file *id, int flags){
33894#ifndef SQLITE_NO_SYNC
33895  /*
33896  ** Used only when SQLITE_NO_SYNC is not defined.
33897   */
33898  BOOL rc;
33899#endif
33900#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
33901    (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
33902  /*
33903  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
33904  ** OSTRACE() macros.
33905   */
33906  winFile *pFile = (winFile*)id;
33907#else
33908  UNUSED_PARAMETER(id);
33909#endif
33910
33911  assert( pFile );
33912  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
33913  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
33914      || (flags&0x0F)==SQLITE_SYNC_FULL
33915  );
33916
33917  OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
33918
33919  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
33920  ** line is to test that doing so does not cause any problems.
33921  */
33922  SimulateDiskfullError( return SQLITE_FULL );
33923
33924#ifndef SQLITE_TEST
33925  UNUSED_PARAMETER(flags);
33926#else
33927  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
33928    sqlite3_fullsync_count++;
33929  }
33930  sqlite3_sync_count++;
33931#endif
33932
33933  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
33934  ** no-op
33935  */
33936#ifdef SQLITE_NO_SYNC
33937  return SQLITE_OK;
33938#else
33939  rc = osFlushFileBuffers(pFile->h);
33940  SimulateIOError( rc=FALSE );
33941  if( rc ){
33942    return SQLITE_OK;
33943  }else{
33944    pFile->lastErrno = osGetLastError();
33945    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
33946             "winSync", pFile->zPath);
33947  }
33948#endif
33949}
33950
33951/*
33952** Determine the current size of a file in bytes
33953*/
33954static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
33955  DWORD upperBits;
33956  DWORD lowerBits;
33957  winFile *pFile = (winFile*)id;
33958  DWORD lastErrno;
33959
33960  assert( id!=0 );
33961  SimulateIOError(return SQLITE_IOERR_FSTAT);
33962  lowerBits = osGetFileSize(pFile->h, &upperBits);
33963  if(   (lowerBits == INVALID_FILE_SIZE)
33964     && ((lastErrno = osGetLastError())!=NO_ERROR) )
33965  {
33966    pFile->lastErrno = lastErrno;
33967    return winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
33968             "winFileSize", pFile->zPath);
33969  }
33970  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
33971  return SQLITE_OK;
33972}
33973
33974/*
33975** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
33976*/
33977#ifndef LOCKFILE_FAIL_IMMEDIATELY
33978# define LOCKFILE_FAIL_IMMEDIATELY 1
33979#endif
33980
33981/*
33982** Acquire a reader lock.
33983** Different API routines are called depending on whether or not this
33984** is Win9x or WinNT.
33985*/
33986static int getReadLock(winFile *pFile){
33987  int res;
33988  if( isNT() ){
33989    OVERLAPPED ovlp;
33990    ovlp.Offset = SHARED_FIRST;
33991    ovlp.OffsetHigh = 0;
33992    ovlp.hEvent = 0;
33993    res = osLockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
33994                       0, SHARED_SIZE, 0, &ovlp);
33995/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33996*/
33997#if SQLITE_OS_WINCE==0
33998  }else{
33999    int lk;
34000    sqlite3_randomness(sizeof(lk), &lk);
34001    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
34002    res = osLockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
34003#endif
34004  }
34005  if( res == 0 ){
34006    pFile->lastErrno = osGetLastError();
34007    /* No need to log a failure to lock */
34008  }
34009  return res;
34010}
34011
34012/*
34013** Undo a readlock
34014*/
34015static int unlockReadLock(winFile *pFile){
34016  int res;
34017  DWORD lastErrno;
34018  if( isNT() ){
34019    res = osUnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34020/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34021*/
34022#if SQLITE_OS_WINCE==0
34023  }else{
34024    res = osUnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
34025#endif
34026  }
34027  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
34028    pFile->lastErrno = lastErrno;
34029    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
34030             "unlockReadLock", pFile->zPath);
34031  }
34032  return res;
34033}
34034
34035/*
34036** Lock the file with the lock specified by parameter locktype - one
34037** of the following:
34038**
34039**     (1) SHARED_LOCK
34040**     (2) RESERVED_LOCK
34041**     (3) PENDING_LOCK
34042**     (4) EXCLUSIVE_LOCK
34043**
34044** Sometimes when requesting one lock state, additional lock states
34045** are inserted in between.  The locking might fail on one of the later
34046** transitions leaving the lock state different from what it started but
34047** still short of its goal.  The following chart shows the allowed
34048** transitions and the inserted intermediate states:
34049**
34050**    UNLOCKED -> SHARED
34051**    SHARED -> RESERVED
34052**    SHARED -> (PENDING) -> EXCLUSIVE
34053**    RESERVED -> (PENDING) -> EXCLUSIVE
34054**    PENDING -> EXCLUSIVE
34055**
34056** This routine will only increase a lock.  The winUnlock() routine
34057** erases all locks at once and returns us immediately to locking level 0.
34058** It is not possible to lower the locking level one step at a time.  You
34059** must go straight to locking level 0.
34060*/
34061static int winLock(sqlite3_file *id, int locktype){
34062  int rc = SQLITE_OK;    /* Return code from subroutines */
34063  int res = 1;           /* Result of a Windows lock call */
34064  int newLocktype;       /* Set pFile->locktype to this value before exiting */
34065  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
34066  winFile *pFile = (winFile*)id;
34067  DWORD lastErrno = NO_ERROR;
34068
34069  assert( id!=0 );
34070  OSTRACE(("LOCK %d %d was %d(%d)\n",
34071           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
34072
34073  /* If there is already a lock of this type or more restrictive on the
34074  ** OsFile, do nothing. Don't use the end_lock: exit path, as
34075  ** sqlite3OsEnterMutex() hasn't been called yet.
34076  */
34077  if( pFile->locktype>=locktype ){
34078    return SQLITE_OK;
34079  }
34080
34081  /* Make sure the locking sequence is correct
34082  */
34083  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
34084  assert( locktype!=PENDING_LOCK );
34085  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
34086
34087  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
34088  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
34089  ** the PENDING_LOCK byte is temporary.
34090  */
34091  newLocktype = pFile->locktype;
34092  if(   (pFile->locktype==NO_LOCK)
34093     || (   (locktype==EXCLUSIVE_LOCK)
34094         && (pFile->locktype==RESERVED_LOCK))
34095  ){
34096    int cnt = 3;
34097    while( cnt-->0 && (res = osLockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
34098      /* Try 3 times to get the pending lock.  This is needed to work
34099      ** around problems caused by indexing and/or anti-virus software on
34100      ** Windows systems.
34101      ** If you are using this code as a model for alternative VFSes, do not
34102      ** copy this retry logic.  It is a hack intended for Windows only.
34103      */
34104      OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
34105      if( cnt ) osSleep(1);
34106    }
34107    gotPendingLock = res;
34108    if( !res ){
34109      lastErrno = osGetLastError();
34110    }
34111  }
34112
34113  /* Acquire a shared lock
34114  */
34115  if( locktype==SHARED_LOCK && res ){
34116    assert( pFile->locktype==NO_LOCK );
34117    res = getReadLock(pFile);
34118    if( res ){
34119      newLocktype = SHARED_LOCK;
34120    }else{
34121      lastErrno = osGetLastError();
34122    }
34123  }
34124
34125  /* Acquire a RESERVED lock
34126  */
34127  if( locktype==RESERVED_LOCK && res ){
34128    assert( pFile->locktype==SHARED_LOCK );
34129    res = osLockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
34130    if( res ){
34131      newLocktype = RESERVED_LOCK;
34132    }else{
34133      lastErrno = osGetLastError();
34134    }
34135  }
34136
34137  /* Acquire a PENDING lock
34138  */
34139  if( locktype==EXCLUSIVE_LOCK && res ){
34140    newLocktype = PENDING_LOCK;
34141    gotPendingLock = 0;
34142  }
34143
34144  /* Acquire an EXCLUSIVE lock
34145  */
34146  if( locktype==EXCLUSIVE_LOCK && res ){
34147    assert( pFile->locktype>=SHARED_LOCK );
34148    res = unlockReadLock(pFile);
34149    OSTRACE(("unreadlock = %d\n", res));
34150    res = osLockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34151    if( res ){
34152      newLocktype = EXCLUSIVE_LOCK;
34153    }else{
34154      lastErrno = osGetLastError();
34155      OSTRACE(("error-code = %d\n", lastErrno));
34156      getReadLock(pFile);
34157    }
34158  }
34159
34160  /* If we are holding a PENDING lock that ought to be released, then
34161  ** release it now.
34162  */
34163  if( gotPendingLock && locktype==SHARED_LOCK ){
34164    osUnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
34165  }
34166
34167  /* Update the state of the lock has held in the file descriptor then
34168  ** return the appropriate result code.
34169  */
34170  if( res ){
34171    rc = SQLITE_OK;
34172  }else{
34173    OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
34174           locktype, newLocktype));
34175    pFile->lastErrno = lastErrno;
34176    rc = SQLITE_BUSY;
34177  }
34178  pFile->locktype = (u8)newLocktype;
34179  return rc;
34180}
34181
34182/*
34183** This routine checks if there is a RESERVED lock held on the specified
34184** file by this or any other process. If such a lock is held, return
34185** non-zero, otherwise zero.
34186*/
34187static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
34188  int rc;
34189  winFile *pFile = (winFile*)id;
34190
34191  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
34192
34193  assert( id!=0 );
34194  if( pFile->locktype>=RESERVED_LOCK ){
34195    rc = 1;
34196    OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
34197  }else{
34198    rc = osLockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
34199    if( rc ){
34200      osUnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
34201    }
34202    rc = !rc;
34203    OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
34204  }
34205  *pResOut = rc;
34206  return SQLITE_OK;
34207}
34208
34209/*
34210** Lower the locking level on file descriptor id to locktype.  locktype
34211** must be either NO_LOCK or SHARED_LOCK.
34212**
34213** If the locking level of the file descriptor is already at or below
34214** the requested locking level, this routine is a no-op.
34215**
34216** It is not possible for this routine to fail if the second argument
34217** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
34218** might return SQLITE_IOERR;
34219*/
34220static int winUnlock(sqlite3_file *id, int locktype){
34221  int type;
34222  winFile *pFile = (winFile*)id;
34223  int rc = SQLITE_OK;
34224  assert( pFile!=0 );
34225  assert( locktype<=SHARED_LOCK );
34226  OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
34227          pFile->locktype, pFile->sharedLockByte));
34228  type = pFile->locktype;
34229  if( type>=EXCLUSIVE_LOCK ){
34230    osUnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34231    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
34232      /* This should never happen.  We should always be able to
34233      ** reacquire the read lock */
34234      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
34235               "winUnlock", pFile->zPath);
34236    }
34237  }
34238  if( type>=RESERVED_LOCK ){
34239    osUnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
34240  }
34241  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
34242    unlockReadLock(pFile);
34243  }
34244  if( type>=PENDING_LOCK ){
34245    osUnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
34246  }
34247  pFile->locktype = (u8)locktype;
34248  return rc;
34249}
34250
34251/*
34252** If *pArg is inititially negative then this is a query.  Set *pArg to
34253** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
34254**
34255** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
34256*/
34257static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
34258  if( *pArg<0 ){
34259    *pArg = (pFile->ctrlFlags & mask)!=0;
34260  }else if( (*pArg)==0 ){
34261    pFile->ctrlFlags &= ~mask;
34262  }else{
34263    pFile->ctrlFlags |= mask;
34264  }
34265}
34266
34267/*
34268** Control and query of the open file handle.
34269*/
34270static int winFileControl(sqlite3_file *id, int op, void *pArg){
34271  winFile *pFile = (winFile*)id;
34272  switch( op ){
34273    case SQLITE_FCNTL_LOCKSTATE: {
34274      *(int*)pArg = pFile->locktype;
34275      return SQLITE_OK;
34276    }
34277    case SQLITE_LAST_ERRNO: {
34278      *(int*)pArg = (int)pFile->lastErrno;
34279      return SQLITE_OK;
34280    }
34281    case SQLITE_FCNTL_CHUNK_SIZE: {
34282      pFile->szChunk = *(int *)pArg;
34283      return SQLITE_OK;
34284    }
34285    case SQLITE_FCNTL_SIZE_HINT: {
34286      if( pFile->szChunk>0 ){
34287        sqlite3_int64 oldSz;
34288        int rc = winFileSize(id, &oldSz);
34289        if( rc==SQLITE_OK ){
34290          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
34291          if( newSz>oldSz ){
34292            SimulateIOErrorBenign(1);
34293            rc = winTruncate(id, newSz);
34294            SimulateIOErrorBenign(0);
34295          }
34296        }
34297        return rc;
34298      }
34299      return SQLITE_OK;
34300    }
34301    case SQLITE_FCNTL_PERSIST_WAL: {
34302      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
34303      return SQLITE_OK;
34304    }
34305    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
34306      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
34307      return SQLITE_OK;
34308    }
34309    case SQLITE_FCNTL_VFSNAME: {
34310      *(char**)pArg = sqlite3_mprintf("win32");
34311      return SQLITE_OK;
34312    }
34313    case SQLITE_FCNTL_WIN32_AV_RETRY: {
34314      int *a = (int*)pArg;
34315      if( a[0]>0 ){
34316        win32IoerrRetry = a[0];
34317      }else{
34318        a[0] = win32IoerrRetry;
34319      }
34320      if( a[1]>0 ){
34321        win32IoerrRetryDelay = a[1];
34322      }else{
34323        a[1] = win32IoerrRetryDelay;
34324      }
34325      return SQLITE_OK;
34326    }
34327  }
34328  return SQLITE_NOTFOUND;
34329}
34330
34331/*
34332** Return the sector size in bytes of the underlying block device for
34333** the specified file. This is almost always 512 bytes, but may be
34334** larger for some devices.
34335**
34336** SQLite code assumes this function cannot fail. It also assumes that
34337** if two files are created in the same file-system directory (i.e.
34338** a database and its journal file) that the sector size will be the
34339** same for both.
34340*/
34341static int winSectorSize(sqlite3_file *id){
34342  (void)id;
34343  return SQLITE_DEFAULT_SECTOR_SIZE;
34344}
34345
34346/*
34347** Return a vector of device characteristics.
34348*/
34349static int winDeviceCharacteristics(sqlite3_file *id){
34350  winFile *p = (winFile*)id;
34351  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
34352         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
34353}
34354
34355#ifndef SQLITE_OMIT_WAL
34356
34357/*
34358** Windows will only let you create file view mappings
34359** on allocation size granularity boundaries.
34360** During sqlite3_os_init() we do a GetSystemInfo()
34361** to get the granularity size.
34362*/
34363SYSTEM_INFO winSysInfo;
34364
34365/*
34366** Helper functions to obtain and relinquish the global mutex. The
34367** global mutex is used to protect the winLockInfo objects used by
34368** this file, all of which may be shared by multiple threads.
34369**
34370** Function winShmMutexHeld() is used to assert() that the global mutex
34371** is held when required. This function is only used as part of assert()
34372** statements. e.g.
34373**
34374**   winShmEnterMutex()
34375**     assert( winShmMutexHeld() );
34376**   winShmLeaveMutex()
34377*/
34378static void winShmEnterMutex(void){
34379  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34380}
34381static void winShmLeaveMutex(void){
34382  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34383}
34384#ifdef SQLITE_DEBUG
34385static int winShmMutexHeld(void) {
34386  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34387}
34388#endif
34389
34390/*
34391** Object used to represent a single file opened and mmapped to provide
34392** shared memory.  When multiple threads all reference the same
34393** log-summary, each thread has its own winFile object, but they all
34394** point to a single instance of this object.  In other words, each
34395** log-summary is opened only once per process.
34396**
34397** winShmMutexHeld() must be true when creating or destroying
34398** this object or while reading or writing the following fields:
34399**
34400**      nRef
34401**      pNext
34402**
34403** The following fields are read-only after the object is created:
34404**
34405**      fid
34406**      zFilename
34407**
34408** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
34409** winShmMutexHeld() is true when reading or writing any other field
34410** in this structure.
34411**
34412*/
34413struct winShmNode {
34414  sqlite3_mutex *mutex;      /* Mutex to access this object */
34415  char *zFilename;           /* Name of the file */
34416  winFile hFile;             /* File handle from winOpen */
34417
34418  int szRegion;              /* Size of shared-memory regions */
34419  int nRegion;               /* Size of array apRegion */
34420  struct ShmRegion {
34421    HANDLE hMap;             /* File handle from CreateFileMapping */
34422    void *pMap;
34423  } *aRegion;
34424  DWORD lastErrno;           /* The Windows errno from the last I/O error */
34425
34426  int nRef;                  /* Number of winShm objects pointing to this */
34427  winShm *pFirst;            /* All winShm objects pointing to this */
34428  winShmNode *pNext;         /* Next in list of all winShmNode objects */
34429#ifdef SQLITE_DEBUG
34430  u8 nextShmId;              /* Next available winShm.id value */
34431#endif
34432};
34433
34434/*
34435** A global array of all winShmNode objects.
34436**
34437** The winShmMutexHeld() must be true while reading or writing this list.
34438*/
34439static winShmNode *winShmNodeList = 0;
34440
34441/*
34442** Structure used internally by this VFS to record the state of an
34443** open shared memory connection.
34444**
34445** The following fields are initialized when this object is created and
34446** are read-only thereafter:
34447**
34448**    winShm.pShmNode
34449**    winShm.id
34450**
34451** All other fields are read/write.  The winShm.pShmNode->mutex must be held
34452** while accessing any read/write fields.
34453*/
34454struct winShm {
34455  winShmNode *pShmNode;      /* The underlying winShmNode object */
34456  winShm *pNext;             /* Next winShm with the same winShmNode */
34457  u8 hasMutex;               /* True if holding the winShmNode mutex */
34458  u16 sharedMask;            /* Mask of shared locks held */
34459  u16 exclMask;              /* Mask of exclusive locks held */
34460#ifdef SQLITE_DEBUG
34461  u8 id;                     /* Id of this connection with its winShmNode */
34462#endif
34463};
34464
34465/*
34466** Constants used for locking
34467*/
34468#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
34469#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
34470
34471/*
34472** Apply advisory locks for all n bytes beginning at ofst.
34473*/
34474#define _SHM_UNLCK  1
34475#define _SHM_RDLCK  2
34476#define _SHM_WRLCK  3
34477static int winShmSystemLock(
34478  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
34479  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
34480  int ofst,             /* Offset to first byte to be locked/unlocked */
34481  int nByte             /* Number of bytes to lock or unlock */
34482){
34483  OVERLAPPED ovlp;
34484  DWORD dwFlags;
34485  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
34486
34487  /* Access to the winShmNode object is serialized by the caller */
34488  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
34489
34490  /* Initialize the locking parameters */
34491  dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
34492  if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
34493
34494  memset(&ovlp, 0, sizeof(OVERLAPPED));
34495  ovlp.Offset = ofst;
34496
34497  /* Release/Acquire the system-level lock */
34498  if( lockType==_SHM_UNLCK ){
34499    rc = osUnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
34500  }else{
34501    rc = osLockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
34502  }
34503
34504  if( rc!= 0 ){
34505    rc = SQLITE_OK;
34506  }else{
34507    pFile->lastErrno =  osGetLastError();
34508    rc = SQLITE_BUSY;
34509  }
34510
34511  OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
34512           pFile->hFile.h,
34513           rc==SQLITE_OK ? "ok" : "failed",
34514           lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
34515           pFile->lastErrno));
34516
34517  return rc;
34518}
34519
34520/* Forward references to VFS methods */
34521static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
34522static int winDelete(sqlite3_vfs *,const char*,int);
34523
34524/*
34525** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
34526**
34527** This is not a VFS shared-memory method; it is a utility function called
34528** by VFS shared-memory methods.
34529*/
34530static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
34531  winShmNode **pp;
34532  winShmNode *p;
34533  BOOL bRc;
34534  assert( winShmMutexHeld() );
34535  pp = &winShmNodeList;
34536  while( (p = *pp)!=0 ){
34537    if( p->nRef==0 ){
34538      int i;
34539      if( p->mutex ) sqlite3_mutex_free(p->mutex);
34540      for(i=0; i<p->nRegion; i++){
34541        bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
34542        OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
34543                 (int)osGetCurrentProcessId(), i,
34544                 bRc ? "ok" : "failed"));
34545        bRc = osCloseHandle(p->aRegion[i].hMap);
34546        OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
34547                 (int)osGetCurrentProcessId(), i,
34548                 bRc ? "ok" : "failed"));
34549      }
34550      if( p->hFile.h != INVALID_HANDLE_VALUE ){
34551        SimulateIOErrorBenign(1);
34552        winClose((sqlite3_file *)&p->hFile);
34553        SimulateIOErrorBenign(0);
34554      }
34555      if( deleteFlag ){
34556        SimulateIOErrorBenign(1);
34557        sqlite3BeginBenignMalloc();
34558        winDelete(pVfs, p->zFilename, 0);
34559        sqlite3EndBenignMalloc();
34560        SimulateIOErrorBenign(0);
34561      }
34562      *pp = p->pNext;
34563      sqlite3_free(p->aRegion);
34564      sqlite3_free(p);
34565    }else{
34566      pp = &p->pNext;
34567    }
34568  }
34569}
34570
34571/*
34572** Open the shared-memory area associated with database file pDbFd.
34573**
34574** When opening a new shared-memory file, if no other instances of that
34575** file are currently open, in this process or in other processes, then
34576** the file must be truncated to zero length or have its header cleared.
34577*/
34578static int winOpenSharedMemory(winFile *pDbFd){
34579  struct winShm *p;                  /* The connection to be opened */
34580  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
34581  int rc;                            /* Result code */
34582  struct winShmNode *pNew;           /* Newly allocated winShmNode */
34583  int nName;                         /* Size of zName in bytes */
34584
34585  assert( pDbFd->pShm==0 );    /* Not previously opened */
34586
34587  /* Allocate space for the new sqlite3_shm object.  Also speculatively
34588  ** allocate space for a new winShmNode and filename.
34589  */
34590  p = sqlite3_malloc( sizeof(*p) );
34591  if( p==0 ) return SQLITE_IOERR_NOMEM;
34592  memset(p, 0, sizeof(*p));
34593  nName = sqlite3Strlen30(pDbFd->zPath);
34594  pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 17 );
34595  if( pNew==0 ){
34596    sqlite3_free(p);
34597    return SQLITE_IOERR_NOMEM;
34598  }
34599  memset(pNew, 0, sizeof(*pNew) + nName + 17);
34600  pNew->zFilename = (char*)&pNew[1];
34601  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
34602  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
34603
34604  /* Look to see if there is an existing winShmNode that can be used.
34605  ** If no matching winShmNode currently exists, create a new one.
34606  */
34607  winShmEnterMutex();
34608  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
34609    /* TBD need to come up with better match here.  Perhaps
34610    ** use FILE_ID_BOTH_DIR_INFO Structure.
34611    */
34612    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
34613  }
34614  if( pShmNode ){
34615    sqlite3_free(pNew);
34616  }else{
34617    pShmNode = pNew;
34618    pNew = 0;
34619    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
34620    pShmNode->pNext = winShmNodeList;
34621    winShmNodeList = pShmNode;
34622
34623    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
34624    if( pShmNode->mutex==0 ){
34625      rc = SQLITE_IOERR_NOMEM;
34626      goto shm_open_err;
34627    }
34628
34629    rc = winOpen(pDbFd->pVfs,
34630                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
34631                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
34632                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
34633                 0);
34634    if( SQLITE_OK!=rc ){
34635      goto shm_open_err;
34636    }
34637
34638    /* Check to see if another process is holding the dead-man switch.
34639    ** If not, truncate the file to zero length.
34640    */
34641    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
34642      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
34643      if( rc!=SQLITE_OK ){
34644        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
34645                 "winOpenShm", pDbFd->zPath);
34646      }
34647    }
34648    if( rc==SQLITE_OK ){
34649      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
34650      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
34651    }
34652    if( rc ) goto shm_open_err;
34653  }
34654
34655  /* Make the new connection a child of the winShmNode */
34656  p->pShmNode = pShmNode;
34657#ifdef SQLITE_DEBUG
34658  p->id = pShmNode->nextShmId++;
34659#endif
34660  pShmNode->nRef++;
34661  pDbFd->pShm = p;
34662  winShmLeaveMutex();
34663
34664  /* The reference count on pShmNode has already been incremented under
34665  ** the cover of the winShmEnterMutex() mutex and the pointer from the
34666  ** new (struct winShm) object to the pShmNode has been set. All that is
34667  ** left to do is to link the new object into the linked list starting
34668  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
34669  ** mutex.
34670  */
34671  sqlite3_mutex_enter(pShmNode->mutex);
34672  p->pNext = pShmNode->pFirst;
34673  pShmNode->pFirst = p;
34674  sqlite3_mutex_leave(pShmNode->mutex);
34675  return SQLITE_OK;
34676
34677  /* Jump here on any error */
34678shm_open_err:
34679  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
34680  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
34681  sqlite3_free(p);
34682  sqlite3_free(pNew);
34683  winShmLeaveMutex();
34684  return rc;
34685}
34686
34687/*
34688** Close a connection to shared-memory.  Delete the underlying
34689** storage if deleteFlag is true.
34690*/
34691static int winShmUnmap(
34692  sqlite3_file *fd,          /* Database holding shared memory */
34693  int deleteFlag             /* Delete after closing if true */
34694){
34695  winFile *pDbFd;       /* Database holding shared-memory */
34696  winShm *p;            /* The connection to be closed */
34697  winShmNode *pShmNode; /* The underlying shared-memory file */
34698  winShm **pp;          /* For looping over sibling connections */
34699
34700  pDbFd = (winFile*)fd;
34701  p = pDbFd->pShm;
34702  if( p==0 ) return SQLITE_OK;
34703  pShmNode = p->pShmNode;
34704
34705  /* Remove connection p from the set of connections associated
34706  ** with pShmNode */
34707  sqlite3_mutex_enter(pShmNode->mutex);
34708  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
34709  *pp = p->pNext;
34710
34711  /* Free the connection p */
34712  sqlite3_free(p);
34713  pDbFd->pShm = 0;
34714  sqlite3_mutex_leave(pShmNode->mutex);
34715
34716  /* If pShmNode->nRef has reached 0, then close the underlying
34717  ** shared-memory file, too */
34718  winShmEnterMutex();
34719  assert( pShmNode->nRef>0 );
34720  pShmNode->nRef--;
34721  if( pShmNode->nRef==0 ){
34722    winShmPurge(pDbFd->pVfs, deleteFlag);
34723  }
34724  winShmLeaveMutex();
34725
34726  return SQLITE_OK;
34727}
34728
34729/*
34730** Change the lock state for a shared-memory segment.
34731*/
34732static int winShmLock(
34733  sqlite3_file *fd,          /* Database file holding the shared memory */
34734  int ofst,                  /* First lock to acquire or release */
34735  int n,                     /* Number of locks to acquire or release */
34736  int flags                  /* What to do with the lock */
34737){
34738  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
34739  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
34740  winShm *pX;                           /* For looping over all siblings */
34741  winShmNode *pShmNode = p->pShmNode;
34742  int rc = SQLITE_OK;                   /* Result code */
34743  u16 mask;                             /* Mask of locks to take or release */
34744
34745  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
34746  assert( n>=1 );
34747  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
34748       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
34749       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
34750       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
34751  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
34752
34753  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
34754  assert( n>1 || mask==(1<<ofst) );
34755  sqlite3_mutex_enter(pShmNode->mutex);
34756  if( flags & SQLITE_SHM_UNLOCK ){
34757    u16 allMask = 0; /* Mask of locks held by siblings */
34758
34759    /* See if any siblings hold this same lock */
34760    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34761      if( pX==p ) continue;
34762      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
34763      allMask |= pX->sharedMask;
34764    }
34765
34766    /* Unlock the system-level locks */
34767    if( (mask & allMask)==0 ){
34768      rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
34769    }else{
34770      rc = SQLITE_OK;
34771    }
34772
34773    /* Undo the local locks */
34774    if( rc==SQLITE_OK ){
34775      p->exclMask &= ~mask;
34776      p->sharedMask &= ~mask;
34777    }
34778  }else if( flags & SQLITE_SHM_SHARED ){
34779    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
34780
34781    /* Find out which shared locks are already held by sibling connections.
34782    ** If any sibling already holds an exclusive lock, go ahead and return
34783    ** SQLITE_BUSY.
34784    */
34785    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34786      if( (pX->exclMask & mask)!=0 ){
34787        rc = SQLITE_BUSY;
34788        break;
34789      }
34790      allShared |= pX->sharedMask;
34791    }
34792
34793    /* Get shared locks at the system level, if necessary */
34794    if( rc==SQLITE_OK ){
34795      if( (allShared & mask)==0 ){
34796        rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
34797      }else{
34798        rc = SQLITE_OK;
34799      }
34800    }
34801
34802    /* Get the local shared locks */
34803    if( rc==SQLITE_OK ){
34804      p->sharedMask |= mask;
34805    }
34806  }else{
34807    /* Make sure no sibling connections hold locks that will block this
34808    ** lock.  If any do, return SQLITE_BUSY right away.
34809    */
34810    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34811      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
34812        rc = SQLITE_BUSY;
34813        break;
34814      }
34815    }
34816
34817    /* Get the exclusive locks at the system level.  Then if successful
34818    ** also mark the local connection as being locked.
34819    */
34820    if( rc==SQLITE_OK ){
34821      rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
34822      if( rc==SQLITE_OK ){
34823        assert( (p->sharedMask & mask)==0 );
34824        p->exclMask |= mask;
34825      }
34826    }
34827  }
34828  sqlite3_mutex_leave(pShmNode->mutex);
34829  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
34830           p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
34831           rc ? "failed" : "ok"));
34832  return rc;
34833}
34834
34835/*
34836** Implement a memory barrier or memory fence on shared memory.
34837**
34838** All loads and stores begun before the barrier must complete before
34839** any load or store begun after the barrier.
34840*/
34841static void winShmBarrier(
34842  sqlite3_file *fd          /* Database holding the shared memory */
34843){
34844  UNUSED_PARAMETER(fd);
34845  /* MemoryBarrier(); // does not work -- do not know why not */
34846  winShmEnterMutex();
34847  winShmLeaveMutex();
34848}
34849
34850/*
34851** This function is called to obtain a pointer to region iRegion of the
34852** shared-memory associated with the database file fd. Shared-memory regions
34853** are numbered starting from zero. Each shared-memory region is szRegion
34854** bytes in size.
34855**
34856** If an error occurs, an error code is returned and *pp is set to NULL.
34857**
34858** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
34859** region has not been allocated (by any client, including one running in a
34860** separate process), then *pp is set to NULL and SQLITE_OK returned. If
34861** isWrite is non-zero and the requested shared-memory region has not yet
34862** been allocated, it is allocated by this function.
34863**
34864** If the shared-memory region has already been allocated or is allocated by
34865** this call as described above, then it is mapped into this processes
34866** address space (if it is not already), *pp is set to point to the mapped
34867** memory and SQLITE_OK returned.
34868*/
34869static int winShmMap(
34870  sqlite3_file *fd,               /* Handle open on database file */
34871  int iRegion,                    /* Region to retrieve */
34872  int szRegion,                   /* Size of regions */
34873  int isWrite,                    /* True to extend file if necessary */
34874  void volatile **pp              /* OUT: Mapped memory */
34875){
34876  winFile *pDbFd = (winFile*)fd;
34877  winShm *p = pDbFd->pShm;
34878  winShmNode *pShmNode;
34879  int rc = SQLITE_OK;
34880
34881  if( !p ){
34882    rc = winOpenSharedMemory(pDbFd);
34883    if( rc!=SQLITE_OK ) return rc;
34884    p = pDbFd->pShm;
34885  }
34886  pShmNode = p->pShmNode;
34887
34888  sqlite3_mutex_enter(pShmNode->mutex);
34889  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
34890
34891  if( pShmNode->nRegion<=iRegion ){
34892    struct ShmRegion *apNew;           /* New aRegion[] array */
34893    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
34894    sqlite3_int64 sz;                  /* Current size of wal-index file */
34895
34896    pShmNode->szRegion = szRegion;
34897
34898    /* The requested region is not mapped into this processes address space.
34899    ** Check to see if it has been allocated (i.e. if the wal-index file is
34900    ** large enough to contain the requested region).
34901    */
34902    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
34903    if( rc!=SQLITE_OK ){
34904      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34905               "winShmMap1", pDbFd->zPath);
34906      goto shmpage_out;
34907    }
34908
34909    if( sz<nByte ){
34910      /* The requested memory region does not exist. If isWrite is set to
34911      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
34912      **
34913      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
34914      ** the requested memory region.
34915      */
34916      if( !isWrite ) goto shmpage_out;
34917      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
34918      if( rc!=SQLITE_OK ){
34919        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34920                 "winShmMap2", pDbFd->zPath);
34921        goto shmpage_out;
34922      }
34923    }
34924
34925    /* Map the requested memory region into this processes address space. */
34926    apNew = (struct ShmRegion *)sqlite3_realloc(
34927        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
34928    );
34929    if( !apNew ){
34930      rc = SQLITE_IOERR_NOMEM;
34931      goto shmpage_out;
34932    }
34933    pShmNode->aRegion = apNew;
34934
34935    while( pShmNode->nRegion<=iRegion ){
34936      HANDLE hMap;                /* file-mapping handle */
34937      void *pMap = 0;             /* Mapped memory region */
34938
34939      hMap = osCreateFileMapping(pShmNode->hFile.h,
34940          NULL, PAGE_READWRITE, 0, nByte, NULL
34941      );
34942      OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
34943               (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
34944               hMap ? "ok" : "failed"));
34945      if( hMap ){
34946        int iOffset = pShmNode->nRegion*szRegion;
34947        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34948        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
34949            0, iOffset - iOffsetShift, szRegion + iOffsetShift
34950        );
34951        OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
34952                 (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
34953                 szRegion, pMap ? "ok" : "failed"));
34954      }
34955      if( !pMap ){
34956        pShmNode->lastErrno = osGetLastError();
34957        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
34958                 "winShmMap3", pDbFd->zPath);
34959        if( hMap ) osCloseHandle(hMap);
34960        goto shmpage_out;
34961      }
34962
34963      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
34964      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
34965      pShmNode->nRegion++;
34966    }
34967  }
34968
34969shmpage_out:
34970  if( pShmNode->nRegion>iRegion ){
34971    int iOffset = iRegion*szRegion;
34972    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34973    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
34974    *pp = (void *)&p[iOffsetShift];
34975  }else{
34976    *pp = 0;
34977  }
34978  sqlite3_mutex_leave(pShmNode->mutex);
34979  return rc;
34980}
34981
34982#else
34983# define winShmMap     0
34984# define winShmLock    0
34985# define winShmBarrier 0
34986# define winShmUnmap   0
34987#endif /* #ifndef SQLITE_OMIT_WAL */
34988
34989/*
34990** Here ends the implementation of all sqlite3_file methods.
34991**
34992********************** End sqlite3_file Methods *******************************
34993******************************************************************************/
34994
34995/*
34996** This vector defines all the methods that can operate on an
34997** sqlite3_file for win32.
34998*/
34999static const sqlite3_io_methods winIoMethod = {
35000  2,                              /* iVersion */
35001  winClose,                       /* xClose */
35002  winRead,                        /* xRead */
35003  winWrite,                       /* xWrite */
35004  winTruncate,                    /* xTruncate */
35005  winSync,                        /* xSync */
35006  winFileSize,                    /* xFileSize */
35007  winLock,                        /* xLock */
35008  winUnlock,                      /* xUnlock */
35009  winCheckReservedLock,           /* xCheckReservedLock */
35010  winFileControl,                 /* xFileControl */
35011  winSectorSize,                  /* xSectorSize */
35012  winDeviceCharacteristics,       /* xDeviceCharacteristics */
35013  winShmMap,                      /* xShmMap */
35014  winShmLock,                     /* xShmLock */
35015  winShmBarrier,                  /* xShmBarrier */
35016  winShmUnmap                     /* xShmUnmap */
35017};
35018
35019/****************************************************************************
35020**************************** sqlite3_vfs methods ****************************
35021**
35022** This division contains the implementation of methods on the
35023** sqlite3_vfs object.
35024*/
35025
35026/*
35027** Convert a UTF-8 filename into whatever form the underlying
35028** operating system wants filenames in.  Space to hold the result
35029** is obtained from malloc and must be freed by the calling
35030** function.
35031*/
35032static void *convertUtf8Filename(const char *zFilename){
35033  void *zConverted = 0;
35034  if( isNT() ){
35035    zConverted = utf8ToUnicode(zFilename);
35036/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35037*/
35038#if SQLITE_OS_WINCE==0
35039  }else{
35040    zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
35041#endif
35042  }
35043  /* caller will handle out of memory */
35044  return zConverted;
35045}
35046
35047/*
35048** Create a temporary file name in zBuf.  zBuf must be big enough to
35049** hold at pVfs->mxPathname characters.
35050*/
35051static int getTempname(int nBuf, char *zBuf){
35052  static char zChars[] =
35053    "abcdefghijklmnopqrstuvwxyz"
35054    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
35055    "0123456789";
35056  size_t i, j;
35057  char zTempPath[MAX_PATH+2];
35058
35059  /* It's odd to simulate an io-error here, but really this is just
35060  ** using the io-error infrastructure to test that SQLite handles this
35061  ** function failing.
35062  */
35063  SimulateIOError( return SQLITE_IOERR );
35064
35065  if( sqlite3_temp_directory ){
35066    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
35067  }else if( isNT() ){
35068    char *zMulti;
35069    WCHAR zWidePath[MAX_PATH];
35070    osGetTempPathW(MAX_PATH-30, zWidePath);
35071    zMulti = unicodeToUtf8(zWidePath);
35072    if( zMulti ){
35073      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
35074      sqlite3_free(zMulti);
35075    }else{
35076      return SQLITE_IOERR_NOMEM;
35077    }
35078/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35079** Since the ANSI version of these Windows API do not exist for WINCE,
35080** it's important to not reference them for WINCE builds.
35081*/
35082#if SQLITE_OS_WINCE==0
35083  }else{
35084    char *zUtf8;
35085    char zMbcsPath[MAX_PATH];
35086    osGetTempPathA(MAX_PATH-30, zMbcsPath);
35087    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
35088    if( zUtf8 ){
35089      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
35090      sqlite3_free(zUtf8);
35091    }else{
35092      return SQLITE_IOERR_NOMEM;
35093    }
35094#endif
35095  }
35096
35097  /* Check that the output buffer is large enough for the temporary file
35098  ** name. If it is not, return SQLITE_ERROR.
35099  */
35100  if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
35101    return SQLITE_ERROR;
35102  }
35103
35104  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
35105  zTempPath[i] = 0;
35106
35107  sqlite3_snprintf(nBuf-18, zBuf,
35108                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
35109  j = sqlite3Strlen30(zBuf);
35110  sqlite3_randomness(15, &zBuf[j]);
35111  for(i=0; i<15; i++, j++){
35112    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
35113  }
35114  zBuf[j] = 0;
35115  zBuf[j+1] = 0;
35116
35117  OSTRACE(("TEMP FILENAME: %s\n", zBuf));
35118  return SQLITE_OK;
35119}
35120
35121/*
35122** Open a file.
35123*/
35124static int winOpen(
35125  sqlite3_vfs *pVfs,        /* Not used */
35126  const char *zName,        /* Name of the file (UTF-8) */
35127  sqlite3_file *id,         /* Write the SQLite file handle here */
35128  int flags,                /* Open mode flags */
35129  int *pOutFlags            /* Status return flags */
35130){
35131  HANDLE h;
35132  DWORD lastErrno;
35133  DWORD dwDesiredAccess;
35134  DWORD dwShareMode;
35135  DWORD dwCreationDisposition;
35136  DWORD dwFlagsAndAttributes = 0;
35137#if SQLITE_OS_WINCE
35138  int isTemp = 0;
35139#endif
35140  winFile *pFile = (winFile*)id;
35141  void *zConverted;              /* Filename in OS encoding */
35142  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
35143  int cnt = 0;
35144
35145  /* If argument zPath is a NULL pointer, this function is required to open
35146  ** a temporary file. Use this buffer to store the file name in.
35147  */
35148  char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
35149
35150  int rc = SQLITE_OK;            /* Function Return Code */
35151#if !defined(NDEBUG) || SQLITE_OS_WINCE
35152  int eType = flags&0xFFFFFF00;  /* Type of file to open */
35153#endif
35154
35155  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
35156  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
35157  int isCreate     = (flags & SQLITE_OPEN_CREATE);
35158#ifndef NDEBUG
35159  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
35160#endif
35161  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
35162
35163#ifndef NDEBUG
35164  int isOpenJournal = (isCreate && (
35165        eType==SQLITE_OPEN_MASTER_JOURNAL
35166     || eType==SQLITE_OPEN_MAIN_JOURNAL
35167     || eType==SQLITE_OPEN_WAL
35168  ));
35169#endif
35170
35171  /* Check the following statements are true:
35172  **
35173  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
35174  **   (b) if CREATE is set, then READWRITE must also be set, and
35175  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
35176  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
35177  */
35178  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
35179  assert(isCreate==0 || isReadWrite);
35180  assert(isExclusive==0 || isCreate);
35181  assert(isDelete==0 || isCreate);
35182
35183  /* The main DB, main journal, WAL file and master journal are never
35184  ** automatically deleted. Nor are they ever temporary files.  */
35185  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
35186  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
35187  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
35188  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
35189
35190  /* Assert that the upper layer has set one of the "file-type" flags. */
35191  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
35192       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
35193       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
35194       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
35195  );
35196
35197  assert( id!=0 );
35198  UNUSED_PARAMETER(pVfs);
35199
35200  pFile->h = INVALID_HANDLE_VALUE;
35201
35202  /* If the second argument to this function is NULL, generate a
35203  ** temporary file name to use
35204  */
35205  if( !zUtf8Name ){
35206    assert(isDelete && !isOpenJournal);
35207    rc = getTempname(MAX_PATH+2, zTmpname);
35208    if( rc!=SQLITE_OK ){
35209      return rc;
35210    }
35211    zUtf8Name = zTmpname;
35212  }
35213
35214  /* Database filenames are double-zero terminated if they are not
35215  ** URIs with parameters.  Hence, they can always be passed into
35216  ** sqlite3_uri_parameter().
35217  */
35218  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
35219        zUtf8Name[strlen(zUtf8Name)+1]==0 );
35220
35221  /* Convert the filename to the system encoding. */
35222  zConverted = convertUtf8Filename(zUtf8Name);
35223  if( zConverted==0 ){
35224    return SQLITE_IOERR_NOMEM;
35225  }
35226
35227  if( isReadWrite ){
35228    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
35229  }else{
35230    dwDesiredAccess = GENERIC_READ;
35231  }
35232
35233  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
35234  ** created. SQLite doesn't use it to indicate "exclusive access"
35235  ** as it is usually understood.
35236  */
35237  if( isExclusive ){
35238    /* Creates a new file, only if it does not already exist. */
35239    /* If the file exists, it fails. */
35240    dwCreationDisposition = CREATE_NEW;
35241  }else if( isCreate ){
35242    /* Open existing file, or create if it doesn't exist */
35243    dwCreationDisposition = OPEN_ALWAYS;
35244  }else{
35245    /* Opens a file, only if it exists. */
35246    dwCreationDisposition = OPEN_EXISTING;
35247  }
35248
35249  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
35250
35251  if( isDelete ){
35252#if SQLITE_OS_WINCE
35253    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
35254    isTemp = 1;
35255#else
35256    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
35257                               | FILE_ATTRIBUTE_HIDDEN
35258                               | FILE_FLAG_DELETE_ON_CLOSE;
35259#endif
35260  }else{
35261    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
35262  }
35263  /* Reports from the internet are that performance is always
35264  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
35265#if SQLITE_OS_WINCE
35266  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
35267#endif
35268
35269  if( isNT() ){
35270    while( (h = osCreateFileW((LPCWSTR)zConverted,
35271                              dwDesiredAccess,
35272                              dwShareMode, NULL,
35273                              dwCreationDisposition,
35274                              dwFlagsAndAttributes,
35275                              NULL))==INVALID_HANDLE_VALUE &&
35276                              retryIoerr(&cnt, &lastErrno) ){}
35277/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35278** Since the ANSI version of these Windows API do not exist for WINCE,
35279** it's important to not reference them for WINCE builds.
35280*/
35281#if SQLITE_OS_WINCE==0
35282  }else{
35283    while( (h = osCreateFileA((LPCSTR)zConverted,
35284                              dwDesiredAccess,
35285                              dwShareMode, NULL,
35286                              dwCreationDisposition,
35287                              dwFlagsAndAttributes,
35288                              NULL))==INVALID_HANDLE_VALUE &&
35289                              retryIoerr(&cnt, &lastErrno) ){}
35290#endif
35291  }
35292
35293  logIoerr(cnt);
35294
35295  OSTRACE(("OPEN %d %s 0x%lx %s\n",
35296           h, zName, dwDesiredAccess,
35297           h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
35298
35299  if( h==INVALID_HANDLE_VALUE ){
35300    pFile->lastErrno = lastErrno;
35301    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
35302    sqlite3_free(zConverted);
35303    if( isReadWrite && !isExclusive ){
35304      return winOpen(pVfs, zName, id,
35305             ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
35306    }else{
35307      return SQLITE_CANTOPEN_BKPT;
35308    }
35309  }
35310
35311  if( pOutFlags ){
35312    if( isReadWrite ){
35313      *pOutFlags = SQLITE_OPEN_READWRITE;
35314    }else{
35315      *pOutFlags = SQLITE_OPEN_READONLY;
35316    }
35317  }
35318
35319  memset(pFile, 0, sizeof(*pFile));
35320  pFile->pMethod = &winIoMethod;
35321  pFile->h = h;
35322  pFile->lastErrno = NO_ERROR;
35323  pFile->pVfs = pVfs;
35324  pFile->pShm = 0;
35325  pFile->zPath = zName;
35326  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
35327    pFile->ctrlFlags |= WINFILE_PSOW;
35328  }
35329
35330#if SQLITE_OS_WINCE
35331  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
35332       && !winceCreateLock(zName, pFile)
35333  ){
35334    osCloseHandle(h);
35335    sqlite3_free(zConverted);
35336    return SQLITE_CANTOPEN_BKPT;
35337  }
35338  if( isTemp ){
35339    pFile->zDeleteOnClose = zConverted;
35340  }else
35341#endif
35342  {
35343    sqlite3_free(zConverted);
35344  }
35345
35346  OpenCounter(+1);
35347  return rc;
35348}
35349
35350/*
35351** Delete the named file.
35352**
35353** Note that Windows does not allow a file to be deleted if some other
35354** process has it open.  Sometimes a virus scanner or indexing program
35355** will open a journal file shortly after it is created in order to do
35356** whatever it does.  While this other process is holding the
35357** file open, we will be unable to delete it.  To work around this
35358** problem, we delay 100 milliseconds and try to delete again.  Up
35359** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
35360** up and returning an error.
35361*/
35362static int winDelete(
35363  sqlite3_vfs *pVfs,          /* Not used on win32 */
35364  const char *zFilename,      /* Name of file to delete */
35365  int syncDir                 /* Not used on win32 */
35366){
35367  int cnt = 0;
35368  int rc;
35369  DWORD lastErrno;
35370  void *zConverted;
35371  UNUSED_PARAMETER(pVfs);
35372  UNUSED_PARAMETER(syncDir);
35373
35374  SimulateIOError(return SQLITE_IOERR_DELETE);
35375  zConverted = convertUtf8Filename(zFilename);
35376  if( zConverted==0 ){
35377    return SQLITE_IOERR_NOMEM;
35378  }
35379  if( isNT() ){
35380    rc = 1;
35381    while( osGetFileAttributesW(zConverted)!=INVALID_FILE_ATTRIBUTES &&
35382         (rc = osDeleteFileW(zConverted))==0 && retryIoerr(&cnt, &lastErrno) ){}
35383    rc = rc ? SQLITE_OK : SQLITE_ERROR;
35384/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35385** Since the ANSI version of these Windows API do not exist for WINCE,
35386** it's important to not reference them for WINCE builds.
35387*/
35388#if SQLITE_OS_WINCE==0
35389  }else{
35390    rc = 1;
35391    while( osGetFileAttributesA(zConverted)!=INVALID_FILE_ATTRIBUTES &&
35392         (rc = osDeleteFileA(zConverted))==0 && retryIoerr(&cnt, &lastErrno) ){}
35393    rc = rc ? SQLITE_OK : SQLITE_ERROR;
35394#endif
35395  }
35396  if( rc ){
35397    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
35398             "winDelete", zFilename);
35399  }else{
35400    logIoerr(cnt);
35401  }
35402  sqlite3_free(zConverted);
35403  OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
35404  return rc;
35405}
35406
35407/*
35408** Check the existance and status of a file.
35409*/
35410static int winAccess(
35411  sqlite3_vfs *pVfs,         /* Not used on win32 */
35412  const char *zFilename,     /* Name of file to check */
35413  int flags,                 /* Type of test to make on this file */
35414  int *pResOut               /* OUT: Result */
35415){
35416  DWORD attr;
35417  int rc = 0;
35418  DWORD lastErrno;
35419  void *zConverted;
35420  UNUSED_PARAMETER(pVfs);
35421
35422  SimulateIOError( return SQLITE_IOERR_ACCESS; );
35423  zConverted = convertUtf8Filename(zFilename);
35424  if( zConverted==0 ){
35425    return SQLITE_IOERR_NOMEM;
35426  }
35427  if( isNT() ){
35428    int cnt = 0;
35429    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35430    memset(&sAttrData, 0, sizeof(sAttrData));
35431    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
35432                             GetFileExInfoStandard,
35433                             &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
35434    if( rc ){
35435      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
35436      ** as if it does not exist.
35437      */
35438      if(    flags==SQLITE_ACCESS_EXISTS
35439          && sAttrData.nFileSizeHigh==0
35440          && sAttrData.nFileSizeLow==0 ){
35441        attr = INVALID_FILE_ATTRIBUTES;
35442      }else{
35443        attr = sAttrData.dwFileAttributes;
35444      }
35445    }else{
35446      logIoerr(cnt);
35447      if( lastErrno!=ERROR_FILE_NOT_FOUND ){
35448        winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
35449        sqlite3_free(zConverted);
35450        return SQLITE_IOERR_ACCESS;
35451      }else{
35452        attr = INVALID_FILE_ATTRIBUTES;
35453      }
35454    }
35455/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35456** Since the ANSI version of these Windows API do not exist for WINCE,
35457** it's important to not reference them for WINCE builds.
35458*/
35459#if SQLITE_OS_WINCE==0
35460  }else{
35461    attr = osGetFileAttributesA((char*)zConverted);
35462#endif
35463  }
35464  sqlite3_free(zConverted);
35465  switch( flags ){
35466    case SQLITE_ACCESS_READ:
35467    case SQLITE_ACCESS_EXISTS:
35468      rc = attr!=INVALID_FILE_ATTRIBUTES;
35469      break;
35470    case SQLITE_ACCESS_READWRITE:
35471      rc = attr!=INVALID_FILE_ATTRIBUTES &&
35472             (attr & FILE_ATTRIBUTE_READONLY)==0;
35473      break;
35474    default:
35475      assert(!"Invalid flags argument");
35476  }
35477  *pResOut = rc;
35478  return SQLITE_OK;
35479}
35480
35481
35482/*
35483** Turn a relative pathname into a full pathname.  Write the full
35484** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
35485** bytes in size.
35486*/
35487static int winFullPathname(
35488  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
35489  const char *zRelative,        /* Possibly relative input path */
35490  int nFull,                    /* Size of output buffer in bytes */
35491  char *zFull                   /* Output buffer */
35492){
35493
35494#if defined(__CYGWIN__)
35495  SimulateIOError( return SQLITE_ERROR );
35496  UNUSED_PARAMETER(nFull);
35497  cygwin_conv_to_full_win32_path(zRelative, zFull);
35498  return SQLITE_OK;
35499#endif
35500
35501#if SQLITE_OS_WINCE
35502  SimulateIOError( return SQLITE_ERROR );
35503  UNUSED_PARAMETER(nFull);
35504  /* WinCE has no concept of a relative pathname, or so I am told. */
35505  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
35506  return SQLITE_OK;
35507#endif
35508
35509#if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
35510  int nByte;
35511  void *zConverted;
35512  char *zOut;
35513
35514  /* If this path name begins with "/X:", where "X" is any alphabetic
35515  ** character, discard the initial "/" from the pathname.
35516  */
35517  if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
35518    zRelative++;
35519  }
35520
35521  /* It's odd to simulate an io-error here, but really this is just
35522  ** using the io-error infrastructure to test that SQLite handles this
35523  ** function failing. This function could fail if, for example, the
35524  ** current working directory has been unlinked.
35525  */
35526  SimulateIOError( return SQLITE_ERROR );
35527  UNUSED_PARAMETER(nFull);
35528  zConverted = convertUtf8Filename(zRelative);
35529  if( zConverted==0 ){
35530    return SQLITE_IOERR_NOMEM;
35531  }
35532  if( isNT() ){
35533    LPWSTR zTemp;
35534    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0) + 3;
35535    zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
35536    if( zTemp==0 ){
35537      sqlite3_free(zConverted);
35538      return SQLITE_IOERR_NOMEM;
35539    }
35540    osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
35541    sqlite3_free(zConverted);
35542    zOut = unicodeToUtf8(zTemp);
35543    sqlite3_free(zTemp);
35544/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35545** Since the ANSI version of these Windows API do not exist for WINCE,
35546** it's important to not reference them for WINCE builds.
35547*/
35548#if SQLITE_OS_WINCE==0
35549  }else{
35550    char *zTemp;
35551    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
35552    zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
35553    if( zTemp==0 ){
35554      sqlite3_free(zConverted);
35555      return SQLITE_IOERR_NOMEM;
35556    }
35557    osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
35558    sqlite3_free(zConverted);
35559    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
35560    sqlite3_free(zTemp);
35561#endif
35562  }
35563  if( zOut ){
35564    sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
35565    sqlite3_free(zOut);
35566    return SQLITE_OK;
35567  }else{
35568    return SQLITE_IOERR_NOMEM;
35569  }
35570#endif
35571}
35572
35573#ifndef SQLITE_OMIT_LOAD_EXTENSION
35574/*
35575** Interfaces for opening a shared library, finding entry points
35576** within the shared library, and closing the shared library.
35577*/
35578/*
35579** Interfaces for opening a shared library, finding entry points
35580** within the shared library, and closing the shared library.
35581*/
35582static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
35583  HANDLE h;
35584  void *zConverted = convertUtf8Filename(zFilename);
35585  UNUSED_PARAMETER(pVfs);
35586  if( zConverted==0 ){
35587    return 0;
35588  }
35589  if( isNT() ){
35590    h = osLoadLibraryW((LPCWSTR)zConverted);
35591/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35592** Since the ANSI version of these Windows API do not exist for WINCE,
35593** it's important to not reference them for WINCE builds.
35594*/
35595#if SQLITE_OS_WINCE==0
35596  }else{
35597    h = osLoadLibraryA((char*)zConverted);
35598#endif
35599  }
35600  sqlite3_free(zConverted);
35601  return (void*)h;
35602}
35603static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
35604  UNUSED_PARAMETER(pVfs);
35605  getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
35606}
35607static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
35608  UNUSED_PARAMETER(pVfs);
35609  return (void(*)(void))osGetProcAddressA((HANDLE)pHandle, zSymbol);
35610}
35611static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
35612  UNUSED_PARAMETER(pVfs);
35613  osFreeLibrary((HANDLE)pHandle);
35614}
35615#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
35616  #define winDlOpen  0
35617  #define winDlError 0
35618  #define winDlSym   0
35619  #define winDlClose 0
35620#endif
35621
35622
35623/*
35624** Write up to nBuf bytes of randomness into zBuf.
35625*/
35626static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35627  int n = 0;
35628  UNUSED_PARAMETER(pVfs);
35629#if defined(SQLITE_TEST)
35630  n = nBuf;
35631  memset(zBuf, 0, nBuf);
35632#else
35633  if( sizeof(SYSTEMTIME)<=nBuf-n ){
35634    SYSTEMTIME x;
35635    osGetSystemTime(&x);
35636    memcpy(&zBuf[n], &x, sizeof(x));
35637    n += sizeof(x);
35638  }
35639  if( sizeof(DWORD)<=nBuf-n ){
35640    DWORD pid = osGetCurrentProcessId();
35641    memcpy(&zBuf[n], &pid, sizeof(pid));
35642    n += sizeof(pid);
35643  }
35644  if( sizeof(DWORD)<=nBuf-n ){
35645    DWORD cnt = osGetTickCount();
35646    memcpy(&zBuf[n], &cnt, sizeof(cnt));
35647    n += sizeof(cnt);
35648  }
35649  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
35650    LARGE_INTEGER i;
35651    osQueryPerformanceCounter(&i);
35652    memcpy(&zBuf[n], &i, sizeof(i));
35653    n += sizeof(i);
35654  }
35655#endif
35656  return n;
35657}
35658
35659
35660/*
35661** Sleep for a little while.  Return the amount of time slept.
35662*/
35663static int winSleep(sqlite3_vfs *pVfs, int microsec){
35664  osSleep((microsec+999)/1000);
35665  UNUSED_PARAMETER(pVfs);
35666  return ((microsec+999)/1000)*1000;
35667}
35668
35669/*
35670** The following variable, if set to a non-zero value, is interpreted as
35671** the number of seconds since 1970 and is used to set the result of
35672** sqlite3OsCurrentTime() during testing.
35673*/
35674#ifdef SQLITE_TEST
35675SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
35676#endif
35677
35678/*
35679** Find the current time (in Universal Coordinated Time).  Write into *piNow
35680** the current time and date as a Julian Day number times 86_400_000.  In
35681** other words, write into *piNow the number of milliseconds since the Julian
35682** epoch of noon in Greenwich on November 24, 4714 B.C according to the
35683** proleptic Gregorian calendar.
35684**
35685** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
35686** cannot be found.
35687*/
35688static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
35689  /* FILETIME structure is a 64-bit value representing the number of
35690     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
35691  */
35692  FILETIME ft;
35693  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
35694#ifdef SQLITE_TEST
35695  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
35696#endif
35697  /* 2^32 - to avoid use of LL and warnings in gcc */
35698  static const sqlite3_int64 max32BitValue =
35699      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
35700
35701#if SQLITE_OS_WINCE
35702  SYSTEMTIME time;
35703  osGetSystemTime(&time);
35704  /* if SystemTimeToFileTime() fails, it returns zero. */
35705  if (!osSystemTimeToFileTime(&time,&ft)){
35706    return SQLITE_ERROR;
35707  }
35708#else
35709  osGetSystemTimeAsFileTime( &ft );
35710#endif
35711
35712  *piNow = winFiletimeEpoch +
35713            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
35714               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
35715
35716#ifdef SQLITE_TEST
35717  if( sqlite3_current_time ){
35718    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
35719  }
35720#endif
35721  UNUSED_PARAMETER(pVfs);
35722  return SQLITE_OK;
35723}
35724
35725/*
35726** Find the current time (in Universal Coordinated Time).  Write the
35727** current time and date as a Julian Day number into *prNow and
35728** return 0.  Return 1 if the time and date cannot be found.
35729*/
35730static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
35731  int rc;
35732  sqlite3_int64 i;
35733  rc = winCurrentTimeInt64(pVfs, &i);
35734  if( !rc ){
35735    *prNow = i/86400000.0;
35736  }
35737  return rc;
35738}
35739
35740/*
35741** The idea is that this function works like a combination of
35742** GetLastError() and FormatMessage() on Windows (or errno and
35743** strerror_r() on Unix). After an error is returned by an OS
35744** function, SQLite calls this function with zBuf pointing to
35745** a buffer of nBuf bytes. The OS layer should populate the
35746** buffer with a nul-terminated UTF-8 encoded error message
35747** describing the last IO error to have occurred within the calling
35748** thread.
35749**
35750** If the error message is too large for the supplied buffer,
35751** it should be truncated. The return value of xGetLastError
35752** is zero if the error message fits in the buffer, or non-zero
35753** otherwise (if the message was truncated). If non-zero is returned,
35754** then it is not necessary to include the nul-terminator character
35755** in the output buffer.
35756**
35757** Not supplying an error message will have no adverse effect
35758** on SQLite. It is fine to have an implementation that never
35759** returns an error message:
35760**
35761**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35762**     assert(zBuf[0]=='\0');
35763**     return 0;
35764**   }
35765**
35766** However if an error message is supplied, it will be incorporated
35767** by sqlite into the error message available to the user using
35768** sqlite3_errmsg(), possibly making IO errors easier to debug.
35769*/
35770static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35771  UNUSED_PARAMETER(pVfs);
35772  return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
35773}
35774
35775/*
35776** Initialize and deinitialize the operating system interface.
35777*/
35778SQLITE_API int sqlite3_os_init(void){
35779  static sqlite3_vfs winVfs = {
35780    3,                   /* iVersion */
35781    sizeof(winFile),     /* szOsFile */
35782    MAX_PATH,            /* mxPathname */
35783    0,                   /* pNext */
35784    "win32",             /* zName */
35785    0,                   /* pAppData */
35786    winOpen,             /* xOpen */
35787    winDelete,           /* xDelete */
35788    winAccess,           /* xAccess */
35789    winFullPathname,     /* xFullPathname */
35790    winDlOpen,           /* xDlOpen */
35791    winDlError,          /* xDlError */
35792    winDlSym,            /* xDlSym */
35793    winDlClose,          /* xDlClose */
35794    winRandomness,       /* xRandomness */
35795    winSleep,            /* xSleep */
35796    winCurrentTime,      /* xCurrentTime */
35797    winGetLastError,     /* xGetLastError */
35798    winCurrentTimeInt64, /* xCurrentTimeInt64 */
35799    winSetSystemCall,    /* xSetSystemCall */
35800    winGetSystemCall,    /* xGetSystemCall */
35801    winNextSystemCall,   /* xNextSystemCall */
35802  };
35803
35804  /* Double-check that the aSyscall[] array has been constructed
35805  ** correctly.  See ticket [bb3a86e890c8e96ab] */
35806  assert( ArraySize(aSyscall)==60 );
35807
35808#ifndef SQLITE_OMIT_WAL
35809  /* get memory map allocation granularity */
35810  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
35811  osGetSystemInfo(&winSysInfo);
35812  assert(winSysInfo.dwAllocationGranularity > 0);
35813#endif
35814
35815  sqlite3_vfs_register(&winVfs, 1);
35816  return SQLITE_OK;
35817}
35818
35819SQLITE_API int sqlite3_os_end(void){
35820  return SQLITE_OK;
35821}
35822
35823#endif /* SQLITE_OS_WIN */
35824
35825/************** End of os_win.c **********************************************/
35826/************** Begin file bitvec.c ******************************************/
35827/*
35828** 2008 February 16
35829**
35830** The author disclaims copyright to this source code.  In place of
35831** a legal notice, here is a blessing:
35832**
35833**    May you do good and not evil.
35834**    May you find forgiveness for yourself and forgive others.
35835**    May you share freely, never taking more than you give.
35836**
35837*************************************************************************
35838** This file implements an object that represents a fixed-length
35839** bitmap.  Bits are numbered starting with 1.
35840**
35841** A bitmap is used to record which pages of a database file have been
35842** journalled during a transaction, or which pages have the "dont-write"
35843** property.  Usually only a few pages are meet either condition.
35844** So the bitmap is usually sparse and has low cardinality.
35845** But sometimes (for example when during a DROP of a large table) most
35846** or all of the pages in a database can get journalled.  In those cases,
35847** the bitmap becomes dense with high cardinality.  The algorithm needs
35848** to handle both cases well.
35849**
35850** The size of the bitmap is fixed when the object is created.
35851**
35852** All bits are clear when the bitmap is created.  Individual bits
35853** may be set or cleared one at a time.
35854**
35855** Test operations are about 100 times more common that set operations.
35856** Clear operations are exceedingly rare.  There are usually between
35857** 5 and 500 set operations per Bitvec object, though the number of sets can
35858** sometimes grow into tens of thousands or larger.  The size of the
35859** Bitvec object is the number of pages in the database file at the
35860** start of a transaction, and is thus usually less than a few thousand,
35861** but can be as large as 2 billion for a really big database.
35862*/
35863
35864/* Size of the Bitvec structure in bytes. */
35865#define BITVEC_SZ        512
35866
35867/* Round the union size down to the nearest pointer boundary, since that's how
35868** it will be aligned within the Bitvec struct. */
35869#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
35870
35871/* Type of the array "element" for the bitmap representation.
35872** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
35873** Setting this to the "natural word" size of your CPU may improve
35874** performance. */
35875#define BITVEC_TELEM     u8
35876/* Size, in bits, of the bitmap element. */
35877#define BITVEC_SZELEM    8
35878/* Number of elements in a bitmap array. */
35879#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
35880/* Number of bits in the bitmap array. */
35881#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
35882
35883/* Number of u32 values in hash table. */
35884#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
35885/* Maximum number of entries in hash table before
35886** sub-dividing and re-hashing. */
35887#define BITVEC_MXHASH    (BITVEC_NINT/2)
35888/* Hashing function for the aHash representation.
35889** Empirical testing showed that the *37 multiplier
35890** (an arbitrary prime)in the hash function provided
35891** no fewer collisions than the no-op *1. */
35892#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
35893
35894#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
35895
35896
35897/*
35898** A bitmap is an instance of the following structure.
35899**
35900** This bitmap records the existance of zero or more bits
35901** with values between 1 and iSize, inclusive.
35902**
35903** There are three possible representations of the bitmap.
35904** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
35905** bitmap.  The least significant bit is bit 1.
35906**
35907** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
35908** a hash table that will hold up to BITVEC_MXHASH distinct values.
35909**
35910** Otherwise, the value i is redirected into one of BITVEC_NPTR
35911** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
35912** handles up to iDivisor separate values of i.  apSub[0] holds
35913** values between 1 and iDivisor.  apSub[1] holds values between
35914** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
35915** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
35916** to hold deal with values between 1 and iDivisor.
35917*/
35918struct Bitvec {
35919  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
35920  u32 nSet;       /* Number of bits that are set - only valid for aHash
35921                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
35922                  ** this would be 125. */
35923  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
35924                  /* Should >=0 for apSub element. */
35925                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
35926                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
35927  union {
35928    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
35929    u32 aHash[BITVEC_NINT];      /* Hash table representation */
35930    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
35931  } u;
35932};
35933
35934/*
35935** Create a new bitmap object able to handle bits between 0 and iSize,
35936** inclusive.  Return a pointer to the new object.  Return NULL if
35937** malloc fails.
35938*/
35939SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
35940  Bitvec *p;
35941  assert( sizeof(*p)==BITVEC_SZ );
35942  p = sqlite3MallocZero( sizeof(*p) );
35943  if( p ){
35944    p->iSize = iSize;
35945  }
35946  return p;
35947}
35948
35949/*
35950** Check to see if the i-th bit is set.  Return true or false.
35951** If p is NULL (if the bitmap has not been created) or if
35952** i is out of range, then return false.
35953*/
35954SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
35955  if( p==0 ) return 0;
35956  if( i>p->iSize || i==0 ) return 0;
35957  i--;
35958  while( p->iDivisor ){
35959    u32 bin = i/p->iDivisor;
35960    i = i%p->iDivisor;
35961    p = p->u.apSub[bin];
35962    if (!p) {
35963      return 0;
35964    }
35965  }
35966  if( p->iSize<=BITVEC_NBIT ){
35967    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
35968  } else{
35969    u32 h = BITVEC_HASH(i++);
35970    while( p->u.aHash[h] ){
35971      if( p->u.aHash[h]==i ) return 1;
35972      h = (h+1) % BITVEC_NINT;
35973    }
35974    return 0;
35975  }
35976}
35977
35978/*
35979** Set the i-th bit.  Return 0 on success and an error code if
35980** anything goes wrong.
35981**
35982** This routine might cause sub-bitmaps to be allocated.  Failing
35983** to get the memory needed to hold the sub-bitmap is the only
35984** that can go wrong with an insert, assuming p and i are valid.
35985**
35986** The calling function must ensure that p is a valid Bitvec object
35987** and that the value for "i" is within range of the Bitvec object.
35988** Otherwise the behavior is undefined.
35989*/
35990SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
35991  u32 h;
35992  if( p==0 ) return SQLITE_OK;
35993  assert( i>0 );
35994  assert( i<=p->iSize );
35995  i--;
35996  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
35997    u32 bin = i/p->iDivisor;
35998    i = i%p->iDivisor;
35999    if( p->u.apSub[bin]==0 ){
36000      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
36001      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
36002    }
36003    p = p->u.apSub[bin];
36004  }
36005  if( p->iSize<=BITVEC_NBIT ){
36006    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
36007    return SQLITE_OK;
36008  }
36009  h = BITVEC_HASH(i++);
36010  /* if there wasn't a hash collision, and this doesn't */
36011  /* completely fill the hash, then just add it without */
36012  /* worring about sub-dividing and re-hashing. */
36013  if( !p->u.aHash[h] ){
36014    if (p->nSet<(BITVEC_NINT-1)) {
36015      goto bitvec_set_end;
36016    } else {
36017      goto bitvec_set_rehash;
36018    }
36019  }
36020  /* there was a collision, check to see if it's already */
36021  /* in hash, if not, try to find a spot for it */
36022  do {
36023    if( p->u.aHash[h]==i ) return SQLITE_OK;
36024    h++;
36025    if( h>=BITVEC_NINT ) h = 0;
36026  } while( p->u.aHash[h] );
36027  /* we didn't find it in the hash.  h points to the first */
36028  /* available free spot. check to see if this is going to */
36029  /* make our hash too "full".  */
36030bitvec_set_rehash:
36031  if( p->nSet>=BITVEC_MXHASH ){
36032    unsigned int j;
36033    int rc;
36034    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
36035    if( aiValues==0 ){
36036      return SQLITE_NOMEM;
36037    }else{
36038      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
36039      memset(p->u.apSub, 0, sizeof(p->u.apSub));
36040      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
36041      rc = sqlite3BitvecSet(p, i);
36042      for(j=0; j<BITVEC_NINT; j++){
36043        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
36044      }
36045      sqlite3StackFree(0, aiValues);
36046      return rc;
36047    }
36048  }
36049bitvec_set_end:
36050  p->nSet++;
36051  p->u.aHash[h] = i;
36052  return SQLITE_OK;
36053}
36054
36055/*
36056** Clear the i-th bit.
36057**
36058** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
36059** that BitvecClear can use to rebuilt its hash table.
36060*/
36061SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
36062  if( p==0 ) return;
36063  assert( i>0 );
36064  i--;
36065  while( p->iDivisor ){
36066    u32 bin = i/p->iDivisor;
36067    i = i%p->iDivisor;
36068    p = p->u.apSub[bin];
36069    if (!p) {
36070      return;
36071    }
36072  }
36073  if( p->iSize<=BITVEC_NBIT ){
36074    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
36075  }else{
36076    unsigned int j;
36077    u32 *aiValues = pBuf;
36078    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
36079    memset(p->u.aHash, 0, sizeof(p->u.aHash));
36080    p->nSet = 0;
36081    for(j=0; j<BITVEC_NINT; j++){
36082      if( aiValues[j] && aiValues[j]!=(i+1) ){
36083        u32 h = BITVEC_HASH(aiValues[j]-1);
36084        p->nSet++;
36085        while( p->u.aHash[h] ){
36086          h++;
36087          if( h>=BITVEC_NINT ) h = 0;
36088        }
36089        p->u.aHash[h] = aiValues[j];
36090      }
36091    }
36092  }
36093}
36094
36095/*
36096** Destroy a bitmap object.  Reclaim all memory used.
36097*/
36098SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
36099  if( p==0 ) return;
36100  if( p->iDivisor ){
36101    unsigned int i;
36102    for(i=0; i<BITVEC_NPTR; i++){
36103      sqlite3BitvecDestroy(p->u.apSub[i]);
36104    }
36105  }
36106  sqlite3_free(p);
36107}
36108
36109/*
36110** Return the value of the iSize parameter specified when Bitvec *p
36111** was created.
36112*/
36113SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
36114  return p->iSize;
36115}
36116
36117#ifndef SQLITE_OMIT_BUILTIN_TEST
36118/*
36119** Let V[] be an array of unsigned characters sufficient to hold
36120** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
36121** Then the following macros can be used to set, clear, or test
36122** individual bits within V.
36123*/
36124#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
36125#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
36126#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
36127
36128/*
36129** This routine runs an extensive test of the Bitvec code.
36130**
36131** The input is an array of integers that acts as a program
36132** to test the Bitvec.  The integers are opcodes followed
36133** by 0, 1, or 3 operands, depending on the opcode.  Another
36134** opcode follows immediately after the last operand.
36135**
36136** There are 6 opcodes numbered from 0 through 5.  0 is the
36137** "halt" opcode and causes the test to end.
36138**
36139**    0          Halt and return the number of errors
36140**    1 N S X    Set N bits beginning with S and incrementing by X
36141**    2 N S X    Clear N bits beginning with S and incrementing by X
36142**    3 N        Set N randomly chosen bits
36143**    4 N        Clear N randomly chosen bits
36144**    5 N S X    Set N bits from S increment X in array only, not in bitvec
36145**
36146** The opcodes 1 through 4 perform set and clear operations are performed
36147** on both a Bitvec object and on a linear array of bits obtained from malloc.
36148** Opcode 5 works on the linear array only, not on the Bitvec.
36149** Opcode 5 is used to deliberately induce a fault in order to
36150** confirm that error detection works.
36151**
36152** At the conclusion of the test the linear array is compared
36153** against the Bitvec object.  If there are any differences,
36154** an error is returned.  If they are the same, zero is returned.
36155**
36156** If a memory allocation error occurs, return -1.
36157*/
36158SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
36159  Bitvec *pBitvec = 0;
36160  unsigned char *pV = 0;
36161  int rc = -1;
36162  int i, nx, pc, op;
36163  void *pTmpSpace;
36164
36165  /* Allocate the Bitvec to be tested and a linear array of
36166  ** bits to act as the reference */
36167  pBitvec = sqlite3BitvecCreate( sz );
36168  pV = sqlite3_malloc( (sz+7)/8 + 1 );
36169  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
36170  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
36171  memset(pV, 0, (sz+7)/8 + 1);
36172
36173  /* NULL pBitvec tests */
36174  sqlite3BitvecSet(0, 1);
36175  sqlite3BitvecClear(0, 1, pTmpSpace);
36176
36177  /* Run the program */
36178  pc = 0;
36179  while( (op = aOp[pc])!=0 ){
36180    switch( op ){
36181      case 1:
36182      case 2:
36183      case 5: {
36184        nx = 4;
36185        i = aOp[pc+2] - 1;
36186        aOp[pc+2] += aOp[pc+3];
36187        break;
36188      }
36189      case 3:
36190      case 4:
36191      default: {
36192        nx = 2;
36193        sqlite3_randomness(sizeof(i), &i);
36194        break;
36195      }
36196    }
36197    if( (--aOp[pc+1]) > 0 ) nx = 0;
36198    pc += nx;
36199    i = (i & 0x7fffffff)%sz;
36200    if( (op & 1)!=0 ){
36201      SETBIT(pV, (i+1));
36202      if( op!=5 ){
36203        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
36204      }
36205    }else{
36206      CLEARBIT(pV, (i+1));
36207      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
36208    }
36209  }
36210
36211  /* Test to make sure the linear array exactly matches the
36212  ** Bitvec object.  Start with the assumption that they do
36213  ** match (rc==0).  Change rc to non-zero if a discrepancy
36214  ** is found.
36215  */
36216  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
36217          + sqlite3BitvecTest(pBitvec, 0)
36218          + (sqlite3BitvecSize(pBitvec) - sz);
36219  for(i=1; i<=sz; i++){
36220    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
36221      rc = i;
36222      break;
36223    }
36224  }
36225
36226  /* Free allocated structure */
36227bitvec_end:
36228  sqlite3_free(pTmpSpace);
36229  sqlite3_free(pV);
36230  sqlite3BitvecDestroy(pBitvec);
36231  return rc;
36232}
36233#endif /* SQLITE_OMIT_BUILTIN_TEST */
36234
36235/************** End of bitvec.c **********************************************/
36236/************** Begin file pcache.c ******************************************/
36237/*
36238** 2008 August 05
36239**
36240** The author disclaims copyright to this source code.  In place of
36241** a legal notice, here is a blessing:
36242**
36243**    May you do good and not evil.
36244**    May you find forgiveness for yourself and forgive others.
36245**    May you share freely, never taking more than you give.
36246**
36247*************************************************************************
36248** This file implements that page cache.
36249*/
36250
36251/*
36252** A complete page cache is an instance of this structure.
36253*/
36254struct PCache {
36255  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
36256  PgHdr *pSynced;                     /* Last synced page in dirty page list */
36257  int nRef;                           /* Number of referenced pages */
36258  int szCache;                        /* Configured cache size */
36259  int szPage;                         /* Size of every page in this cache */
36260  int szExtra;                        /* Size of extra space for each page */
36261  int bPurgeable;                     /* True if pages are on backing store */
36262  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
36263  void *pStress;                      /* Argument to xStress */
36264  sqlite3_pcache *pCache;             /* Pluggable cache module */
36265  PgHdr *pPage1;                      /* Reference to page 1 */
36266};
36267
36268/*
36269** Some of the assert() macros in this code are too expensive to run
36270** even during normal debugging.  Use them only rarely on long-running
36271** tests.  Enable the expensive asserts using the
36272** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
36273*/
36274#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
36275# define expensive_assert(X)  assert(X)
36276#else
36277# define expensive_assert(X)
36278#endif
36279
36280/********************************** Linked List Management ********************/
36281
36282#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
36283/*
36284** Check that the pCache->pSynced variable is set correctly. If it
36285** is not, either fail an assert or return zero. Otherwise, return
36286** non-zero. This is only used in debugging builds, as follows:
36287**
36288**   expensive_assert( pcacheCheckSynced(pCache) );
36289*/
36290static int pcacheCheckSynced(PCache *pCache){
36291  PgHdr *p;
36292  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
36293    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
36294  }
36295  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
36296}
36297#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
36298
36299/*
36300** Remove page pPage from the list of dirty pages.
36301*/
36302static void pcacheRemoveFromDirtyList(PgHdr *pPage){
36303  PCache *p = pPage->pCache;
36304
36305  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
36306  assert( pPage->pDirtyPrev || pPage==p->pDirty );
36307
36308  /* Update the PCache1.pSynced variable if necessary. */
36309  if( p->pSynced==pPage ){
36310    PgHdr *pSynced = pPage->pDirtyPrev;
36311    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
36312      pSynced = pSynced->pDirtyPrev;
36313    }
36314    p->pSynced = pSynced;
36315  }
36316
36317  if( pPage->pDirtyNext ){
36318    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
36319  }else{
36320    assert( pPage==p->pDirtyTail );
36321    p->pDirtyTail = pPage->pDirtyPrev;
36322  }
36323  if( pPage->pDirtyPrev ){
36324    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
36325  }else{
36326    assert( pPage==p->pDirty );
36327    p->pDirty = pPage->pDirtyNext;
36328  }
36329  pPage->pDirtyNext = 0;
36330  pPage->pDirtyPrev = 0;
36331
36332  expensive_assert( pcacheCheckSynced(p) );
36333}
36334
36335/*
36336** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
36337** pPage).
36338*/
36339static void pcacheAddToDirtyList(PgHdr *pPage){
36340  PCache *p = pPage->pCache;
36341
36342  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
36343
36344  pPage->pDirtyNext = p->pDirty;
36345  if( pPage->pDirtyNext ){
36346    assert( pPage->pDirtyNext->pDirtyPrev==0 );
36347    pPage->pDirtyNext->pDirtyPrev = pPage;
36348  }
36349  p->pDirty = pPage;
36350  if( !p->pDirtyTail ){
36351    p->pDirtyTail = pPage;
36352  }
36353  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
36354    p->pSynced = pPage;
36355  }
36356  expensive_assert( pcacheCheckSynced(p) );
36357}
36358
36359/*
36360** Wrapper around the pluggable caches xUnpin method. If the cache is
36361** being used for an in-memory database, this function is a no-op.
36362*/
36363static void pcacheUnpin(PgHdr *p){
36364  PCache *pCache = p->pCache;
36365  if( pCache->bPurgeable ){
36366    if( p->pgno==1 ){
36367      pCache->pPage1 = 0;
36368    }
36369    sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
36370  }
36371}
36372
36373/*************************************************** General Interfaces ******
36374**
36375** Initialize and shutdown the page cache subsystem. Neither of these
36376** functions are threadsafe.
36377*/
36378SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
36379  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
36380    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
36381    ** built-in default page cache is used instead of the application defined
36382    ** page cache. */
36383    sqlite3PCacheSetDefault();
36384  }
36385  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
36386}
36387SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
36388  if( sqlite3GlobalConfig.pcache2.xShutdown ){
36389    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
36390    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
36391  }
36392}
36393
36394/*
36395** Return the size in bytes of a PCache object.
36396*/
36397SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
36398
36399/*
36400** Create a new PCache object. Storage space to hold the object
36401** has already been allocated and is passed in as the p pointer.
36402** The caller discovers how much space needs to be allocated by
36403** calling sqlite3PcacheSize().
36404*/
36405SQLITE_PRIVATE void sqlite3PcacheOpen(
36406  int szPage,                  /* Size of every page */
36407  int szExtra,                 /* Extra space associated with each page */
36408  int bPurgeable,              /* True if pages are on backing store */
36409  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
36410  void *pStress,               /* Argument to xStress */
36411  PCache *p                    /* Preallocated space for the PCache */
36412){
36413  memset(p, 0, sizeof(PCache));
36414  p->szPage = szPage;
36415  p->szExtra = szExtra;
36416  p->bPurgeable = bPurgeable;
36417  p->xStress = xStress;
36418  p->pStress = pStress;
36419  p->szCache = 100;
36420}
36421
36422/*
36423** Change the page size for PCache object. The caller must ensure that there
36424** are no outstanding page references when this function is called.
36425*/
36426SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
36427  assert( pCache->nRef==0 && pCache->pDirty==0 );
36428  if( pCache->pCache ){
36429    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
36430    pCache->pCache = 0;
36431    pCache->pPage1 = 0;
36432  }
36433  pCache->szPage = szPage;
36434}
36435
36436/*
36437** Compute the number of pages of cache requested.
36438*/
36439static int numberOfCachePages(PCache *p){
36440  if( p->szCache>=0 ){
36441    return p->szCache;
36442  }else{
36443    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
36444  }
36445}
36446
36447/*
36448** Try to obtain a page from the cache.
36449*/
36450SQLITE_PRIVATE int sqlite3PcacheFetch(
36451  PCache *pCache,       /* Obtain the page from this cache */
36452  Pgno pgno,            /* Page number to obtain */
36453  int createFlag,       /* If true, create page if it does not exist already */
36454  PgHdr **ppPage        /* Write the page here */
36455){
36456  sqlite3_pcache_page *pPage = 0;
36457  PgHdr *pPgHdr = 0;
36458  int eCreate;
36459
36460  assert( pCache!=0 );
36461  assert( createFlag==1 || createFlag==0 );
36462  assert( pgno>0 );
36463
36464  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
36465  ** allocate it now.
36466  */
36467  if( !pCache->pCache && createFlag ){
36468    sqlite3_pcache *p;
36469    p = sqlite3GlobalConfig.pcache2.xCreate(
36470        pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
36471    );
36472    if( !p ){
36473      return SQLITE_NOMEM;
36474    }
36475    sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
36476    pCache->pCache = p;
36477  }
36478
36479  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
36480  if( pCache->pCache ){
36481    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
36482  }
36483
36484  if( !pPage && eCreate==1 ){
36485    PgHdr *pPg;
36486
36487    /* Find a dirty page to write-out and recycle. First try to find a
36488    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
36489    ** cleared), but if that is not possible settle for any other
36490    ** unreferenced dirty page.
36491    */
36492    expensive_assert( pcacheCheckSynced(pCache) );
36493    for(pPg=pCache->pSynced;
36494        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
36495        pPg=pPg->pDirtyPrev
36496    );
36497    pCache->pSynced = pPg;
36498    if( !pPg ){
36499      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
36500    }
36501    if( pPg ){
36502      int rc;
36503#ifdef SQLITE_LOG_CACHE_SPILL
36504      sqlite3_log(SQLITE_FULL,
36505                  "spill page %d making room for %d - cache used: %d/%d",
36506                  pPg->pgno, pgno,
36507                  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
36508                  numberOfCachePages(pCache));
36509#endif
36510      rc = pCache->xStress(pCache->pStress, pPg);
36511      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
36512        return rc;
36513      }
36514    }
36515
36516    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
36517  }
36518
36519  if( pPage ){
36520    pPgHdr = (PgHdr *)pPage->pExtra;
36521
36522    if( !pPgHdr->pPage ){
36523      memset(pPgHdr, 0, sizeof(PgHdr));
36524      pPgHdr->pPage = pPage;
36525      pPgHdr->pData = pPage->pBuf;
36526      pPgHdr->pExtra = (void *)&pPgHdr[1];
36527      memset(pPgHdr->pExtra, 0, pCache->szExtra);
36528      pPgHdr->pCache = pCache;
36529      pPgHdr->pgno = pgno;
36530    }
36531    assert( pPgHdr->pCache==pCache );
36532    assert( pPgHdr->pgno==pgno );
36533    assert( pPgHdr->pData==pPage->pBuf );
36534    assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
36535
36536    if( 0==pPgHdr->nRef ){
36537      pCache->nRef++;
36538    }
36539    pPgHdr->nRef++;
36540    if( pgno==1 ){
36541      pCache->pPage1 = pPgHdr;
36542    }
36543  }
36544  *ppPage = pPgHdr;
36545  return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
36546}
36547
36548/*
36549** Decrement the reference count on a page. If the page is clean and the
36550** reference count drops to 0, then it is made elible for recycling.
36551*/
36552SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
36553  assert( p->nRef>0 );
36554  p->nRef--;
36555  if( p->nRef==0 ){
36556    PCache *pCache = p->pCache;
36557    pCache->nRef--;
36558    if( (p->flags&PGHDR_DIRTY)==0 ){
36559      pcacheUnpin(p);
36560    }else{
36561      /* Move the page to the head of the dirty list. */
36562      pcacheRemoveFromDirtyList(p);
36563      pcacheAddToDirtyList(p);
36564    }
36565  }
36566}
36567
36568/*
36569** Increase the reference count of a supplied page by 1.
36570*/
36571SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
36572  assert(p->nRef>0);
36573  p->nRef++;
36574}
36575
36576/*
36577** Drop a page from the cache. There must be exactly one reference to the
36578** page. This function deletes that reference, so after it returns the
36579** page pointed to by p is invalid.
36580*/
36581SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
36582  PCache *pCache;
36583  assert( p->nRef==1 );
36584  if( p->flags&PGHDR_DIRTY ){
36585    pcacheRemoveFromDirtyList(p);
36586  }
36587  pCache = p->pCache;
36588  pCache->nRef--;
36589  if( p->pgno==1 ){
36590    pCache->pPage1 = 0;
36591  }
36592  sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
36593}
36594
36595/*
36596** Make sure the page is marked as dirty. If it isn't dirty already,
36597** make it so.
36598*/
36599SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
36600  p->flags &= ~PGHDR_DONT_WRITE;
36601  assert( p->nRef>0 );
36602  if( 0==(p->flags & PGHDR_DIRTY) ){
36603    p->flags |= PGHDR_DIRTY;
36604    pcacheAddToDirtyList( p);
36605  }
36606}
36607
36608/*
36609** Make sure the page is marked as clean. If it isn't clean already,
36610** make it so.
36611*/
36612SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
36613  if( (p->flags & PGHDR_DIRTY) ){
36614    pcacheRemoveFromDirtyList(p);
36615    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
36616    if( p->nRef==0 ){
36617      pcacheUnpin(p);
36618    }
36619  }
36620}
36621
36622/*
36623** Make every page in the cache clean.
36624*/
36625SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
36626  PgHdr *p;
36627  while( (p = pCache->pDirty)!=0 ){
36628    sqlite3PcacheMakeClean(p);
36629  }
36630}
36631
36632/*
36633** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
36634*/
36635SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
36636  PgHdr *p;
36637  for(p=pCache->pDirty; p; p=p->pDirtyNext){
36638    p->flags &= ~PGHDR_NEED_SYNC;
36639  }
36640  pCache->pSynced = pCache->pDirtyTail;
36641}
36642
36643/*
36644** Change the page number of page p to newPgno.
36645*/
36646SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
36647  PCache *pCache = p->pCache;
36648  assert( p->nRef>0 );
36649  assert( newPgno>0 );
36650  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
36651  p->pgno = newPgno;
36652  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
36653    pcacheRemoveFromDirtyList(p);
36654    pcacheAddToDirtyList(p);
36655  }
36656}
36657
36658/*
36659** Drop every cache entry whose page number is greater than "pgno". The
36660** caller must ensure that there are no outstanding references to any pages
36661** other than page 1 with a page number greater than pgno.
36662**
36663** If there is a reference to page 1 and the pgno parameter passed to this
36664** function is 0, then the data area associated with page 1 is zeroed, but
36665** the page object is not dropped.
36666*/
36667SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
36668  if( pCache->pCache ){
36669    PgHdr *p;
36670    PgHdr *pNext;
36671    for(p=pCache->pDirty; p; p=pNext){
36672      pNext = p->pDirtyNext;
36673      /* This routine never gets call with a positive pgno except right
36674      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
36675      ** it must be that pgno==0.
36676      */
36677      assert( p->pgno>0 );
36678      if( ALWAYS(p->pgno>pgno) ){
36679        assert( p->flags&PGHDR_DIRTY );
36680        sqlite3PcacheMakeClean(p);
36681      }
36682    }
36683    if( pgno==0 && pCache->pPage1 ){
36684      memset(pCache->pPage1->pData, 0, pCache->szPage);
36685      pgno = 1;
36686    }
36687    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
36688  }
36689}
36690
36691/*
36692** Close a cache.
36693*/
36694SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
36695  if( pCache->pCache ){
36696    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
36697  }
36698}
36699
36700/*
36701** Discard the contents of the cache.
36702*/
36703SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
36704  sqlite3PcacheTruncate(pCache, 0);
36705}
36706
36707/*
36708** Merge two lists of pages connected by pDirty and in pgno order.
36709** Do not both fixing the pDirtyPrev pointers.
36710*/
36711static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
36712  PgHdr result, *pTail;
36713  pTail = &result;
36714  while( pA && pB ){
36715    if( pA->pgno<pB->pgno ){
36716      pTail->pDirty = pA;
36717      pTail = pA;
36718      pA = pA->pDirty;
36719    }else{
36720      pTail->pDirty = pB;
36721      pTail = pB;
36722      pB = pB->pDirty;
36723    }
36724  }
36725  if( pA ){
36726    pTail->pDirty = pA;
36727  }else if( pB ){
36728    pTail->pDirty = pB;
36729  }else{
36730    pTail->pDirty = 0;
36731  }
36732  return result.pDirty;
36733}
36734
36735/*
36736** Sort the list of pages in accending order by pgno.  Pages are
36737** connected by pDirty pointers.  The pDirtyPrev pointers are
36738** corrupted by this sort.
36739**
36740** Since there cannot be more than 2^31 distinct pages in a database,
36741** there cannot be more than 31 buckets required by the merge sorter.
36742** One extra bucket is added to catch overflow in case something
36743** ever changes to make the previous sentence incorrect.
36744*/
36745#define N_SORT_BUCKET  32
36746static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
36747  PgHdr *a[N_SORT_BUCKET], *p;
36748  int i;
36749  memset(a, 0, sizeof(a));
36750  while( pIn ){
36751    p = pIn;
36752    pIn = p->pDirty;
36753    p->pDirty = 0;
36754    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
36755      if( a[i]==0 ){
36756        a[i] = p;
36757        break;
36758      }else{
36759        p = pcacheMergeDirtyList(a[i], p);
36760        a[i] = 0;
36761      }
36762    }
36763    if( NEVER(i==N_SORT_BUCKET-1) ){
36764      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
36765      ** the input list.  But that is impossible.
36766      */
36767      a[i] = pcacheMergeDirtyList(a[i], p);
36768    }
36769  }
36770  p = a[0];
36771  for(i=1; i<N_SORT_BUCKET; i++){
36772    p = pcacheMergeDirtyList(p, a[i]);
36773  }
36774  return p;
36775}
36776
36777/*
36778** Return a list of all dirty pages in the cache, sorted by page number.
36779*/
36780SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
36781  PgHdr *p;
36782  for(p=pCache->pDirty; p; p=p->pDirtyNext){
36783    p->pDirty = p->pDirtyNext;
36784  }
36785  return pcacheSortDirtyList(pCache->pDirty);
36786}
36787
36788/*
36789** Return the total number of referenced pages held by the cache.
36790*/
36791SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
36792  return pCache->nRef;
36793}
36794
36795/*
36796** Return the number of references to the page supplied as an argument.
36797*/
36798SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
36799  return p->nRef;
36800}
36801
36802/*
36803** Return the total number of pages in the cache.
36804*/
36805SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
36806  int nPage = 0;
36807  if( pCache->pCache ){
36808    nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
36809  }
36810  return nPage;
36811}
36812
36813#ifdef SQLITE_TEST
36814/*
36815** Get the suggested cache-size value.
36816*/
36817SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
36818  return numberOfCachePages(pCache);
36819}
36820#endif
36821
36822/*
36823** Set the suggested cache-size value.
36824*/
36825SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
36826  pCache->szCache = mxPage;
36827  if( pCache->pCache ){
36828    sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
36829                                           numberOfCachePages(pCache));
36830  }
36831}
36832
36833/*
36834** Free up as much memory as possible from the page cache.
36835*/
36836SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
36837  if( pCache->pCache ){
36838    sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
36839  }
36840}
36841
36842#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
36843/*
36844** For all dirty pages currently in the cache, invoke the specified
36845** callback. This is only used if the SQLITE_CHECK_PAGES macro is
36846** defined.
36847*/
36848SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
36849  PgHdr *pDirty;
36850  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
36851    xIter(pDirty);
36852  }
36853}
36854#endif
36855
36856/************** End of pcache.c **********************************************/
36857/************** Begin file pcache1.c *****************************************/
36858/*
36859** 2008 November 05
36860**
36861** The author disclaims copyright to this source code.  In place of
36862** a legal notice, here is a blessing:
36863**
36864**    May you do good and not evil.
36865**    May you find forgiveness for yourself and forgive others.
36866**    May you share freely, never taking more than you give.
36867**
36868*************************************************************************
36869**
36870** This file implements the default page cache implementation (the
36871** sqlite3_pcache interface). It also contains part of the implementation
36872** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
36873** If the default page cache implementation is overriden, then neither of
36874** these two features are available.
36875*/
36876
36877
36878typedef struct PCache1 PCache1;
36879typedef struct PgHdr1 PgHdr1;
36880typedef struct PgFreeslot PgFreeslot;
36881typedef struct PGroup PGroup;
36882
36883/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
36884** of one or more PCaches that are able to recycle each others unpinned
36885** pages when they are under memory pressure.  A PGroup is an instance of
36886** the following object.
36887**
36888** This page cache implementation works in one of two modes:
36889**
36890**   (1)  Every PCache is the sole member of its own PGroup.  There is
36891**        one PGroup per PCache.
36892**
36893**   (2)  There is a single global PGroup that all PCaches are a member
36894**        of.
36895**
36896** Mode 1 uses more memory (since PCache instances are not able to rob
36897** unused pages from other PCaches) but it also operates without a mutex,
36898** and is therefore often faster.  Mode 2 requires a mutex in order to be
36899** threadsafe, but recycles pages more efficiently.
36900**
36901** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
36902** PGroup which is the pcache1.grp global variable and its mutex is
36903** SQLITE_MUTEX_STATIC_LRU.
36904*/
36905struct PGroup {
36906  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
36907  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
36908  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
36909  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
36910  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
36911  PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
36912};
36913
36914/* Each page cache is an instance of the following object.  Every
36915** open database file (including each in-memory database and each
36916** temporary or transient database) has a single page cache which
36917** is an instance of this object.
36918**
36919** Pointers to structures of this type are cast and returned as
36920** opaque sqlite3_pcache* handles.
36921*/
36922struct PCache1 {
36923  /* Cache configuration parameters. Page size (szPage) and the purgeable
36924  ** flag (bPurgeable) are set when the cache is created. nMax may be
36925  ** modified at any time by a call to the pcache1Cachesize() method.
36926  ** The PGroup mutex must be held when accessing nMax.
36927  */
36928  PGroup *pGroup;                     /* PGroup this cache belongs to */
36929  int szPage;                         /* Size of allocated pages in bytes */
36930  int szExtra;                        /* Size of extra space in bytes */
36931  int bPurgeable;                     /* True if cache is purgeable */
36932  unsigned int nMin;                  /* Minimum number of pages reserved */
36933  unsigned int nMax;                  /* Configured "cache_size" value */
36934  unsigned int n90pct;                /* nMax*9/10 */
36935  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
36936
36937  /* Hash table of all pages. The following variables may only be accessed
36938  ** when the accessor is holding the PGroup mutex.
36939  */
36940  unsigned int nRecyclable;           /* Number of pages in the LRU list */
36941  unsigned int nPage;                 /* Total number of pages in apHash */
36942  unsigned int nHash;                 /* Number of slots in apHash[] */
36943  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
36944};
36945
36946/*
36947** Each cache entry is represented by an instance of the following
36948** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
36949** PgHdr1.pCache->szPage bytes is allocated directly before this structure
36950** in memory.
36951*/
36952struct PgHdr1 {
36953  sqlite3_pcache_page page;
36954  unsigned int iKey;             /* Key value (page number) */
36955  PgHdr1 *pNext;                 /* Next in hash table chain */
36956  PCache1 *pCache;               /* Cache that currently owns this page */
36957  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
36958  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
36959};
36960
36961/*
36962** Free slots in the allocator used to divide up the buffer provided using
36963** the SQLITE_CONFIG_PAGECACHE mechanism.
36964*/
36965struct PgFreeslot {
36966  PgFreeslot *pNext;  /* Next free slot */
36967};
36968
36969/*
36970** Global data used by this cache.
36971*/
36972static SQLITE_WSD struct PCacheGlobal {
36973  PGroup grp;                    /* The global PGroup for mode (2) */
36974
36975  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
36976  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
36977  ** fixed at sqlite3_initialize() time and do not require mutex protection.
36978  ** The nFreeSlot and pFree values do require mutex protection.
36979  */
36980  int isInit;                    /* True if initialized */
36981  int szSlot;                    /* Size of each free slot */
36982  int nSlot;                     /* The number of pcache slots */
36983  int nReserve;                  /* Try to keep nFreeSlot above this */
36984  void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
36985  /* Above requires no mutex.  Use mutex below for variable that follow. */
36986  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
36987  PgFreeslot *pFree;             /* Free page blocks */
36988  int nFreeSlot;                 /* Number of unused pcache slots */
36989  /* The following value requires a mutex to change.  We skip the mutex on
36990  ** reading because (1) most platforms read a 32-bit integer atomically and
36991  ** (2) even if an incorrect value is read, no great harm is done since this
36992  ** is really just an optimization. */
36993  int bUnderPressure;            /* True if low on PAGECACHE memory */
36994} pcache1_g;
36995
36996/*
36997** All code in this file should access the global structure above via the
36998** alias "pcache1". This ensures that the WSD emulation is used when
36999** compiling for systems that do not support real WSD.
37000*/
37001#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
37002
37003/*
37004** Macros to enter and leave the PCache LRU mutex.
37005*/
37006#define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
37007#define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
37008
37009/******************************************************************************/
37010/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
37011
37012/*
37013** This function is called during initialization if a static buffer is
37014** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
37015** verb to sqlite3_config(). Parameter pBuf points to an allocation large
37016** enough to contain 'n' buffers of 'sz' bytes each.
37017**
37018** This routine is called from sqlite3_initialize() and so it is guaranteed
37019** to be serialized already.  There is no need for further mutexing.
37020*/
37021SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
37022  if( pcache1.isInit ){
37023    PgFreeslot *p;
37024    sz = ROUNDDOWN8(sz);
37025    pcache1.szSlot = sz;
37026    pcache1.nSlot = pcache1.nFreeSlot = n;
37027    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
37028    pcache1.pStart = pBuf;
37029    pcache1.pFree = 0;
37030    pcache1.bUnderPressure = 0;
37031    while( n-- ){
37032      p = (PgFreeslot*)pBuf;
37033      p->pNext = pcache1.pFree;
37034      pcache1.pFree = p;
37035      pBuf = (void*)&((char*)pBuf)[sz];
37036    }
37037    pcache1.pEnd = pBuf;
37038  }
37039}
37040
37041/*
37042** Malloc function used within this file to allocate space from the buffer
37043** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
37044** such buffer exists or there is no space left in it, this function falls
37045** back to sqlite3Malloc().
37046**
37047** Multiple threads can run this routine at the same time.  Global variables
37048** in pcache1 need to be protected via mutex.
37049*/
37050static void *pcache1Alloc(int nByte){
37051  void *p = 0;
37052  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
37053  sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
37054  if( nByte<=pcache1.szSlot ){
37055    sqlite3_mutex_enter(pcache1.mutex);
37056    p = (PgHdr1 *)pcache1.pFree;
37057    if( p ){
37058      pcache1.pFree = pcache1.pFree->pNext;
37059      pcache1.nFreeSlot--;
37060      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
37061      assert( pcache1.nFreeSlot>=0 );
37062      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
37063    }
37064    sqlite3_mutex_leave(pcache1.mutex);
37065  }
37066  if( p==0 ){
37067    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
37068    ** it from sqlite3Malloc instead.
37069    */
37070    p = sqlite3Malloc(nByte);
37071    if( p ){
37072      int sz = sqlite3MallocSize(p);
37073      sqlite3_mutex_enter(pcache1.mutex);
37074      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
37075      sqlite3_mutex_leave(pcache1.mutex);
37076    }
37077    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
37078  }
37079  return p;
37080}
37081
37082/*
37083** Free an allocated buffer obtained from pcache1Alloc().
37084*/
37085static int pcache1Free(void *p){
37086  int nFreed = 0;
37087  if( p==0 ) return 0;
37088  if( p>=pcache1.pStart && p<pcache1.pEnd ){
37089    PgFreeslot *pSlot;
37090    sqlite3_mutex_enter(pcache1.mutex);
37091    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
37092    pSlot = (PgFreeslot*)p;
37093    pSlot->pNext = pcache1.pFree;
37094    pcache1.pFree = pSlot;
37095    pcache1.nFreeSlot++;
37096    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
37097    assert( pcache1.nFreeSlot<=pcache1.nSlot );
37098    sqlite3_mutex_leave(pcache1.mutex);
37099  }else{
37100    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
37101    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
37102    nFreed = sqlite3MallocSize(p);
37103    sqlite3_mutex_enter(pcache1.mutex);
37104    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
37105    sqlite3_mutex_leave(pcache1.mutex);
37106    sqlite3_free(p);
37107  }
37108  return nFreed;
37109}
37110
37111#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
37112/*
37113** Return the size of a pcache allocation
37114*/
37115static int pcache1MemSize(void *p){
37116  if( p>=pcache1.pStart && p<pcache1.pEnd ){
37117    return pcache1.szSlot;
37118  }else{
37119    int iSize;
37120    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
37121    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
37122    iSize = sqlite3MallocSize(p);
37123    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
37124    return iSize;
37125  }
37126}
37127#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
37128
37129/*
37130** Allocate a new page object initially associated with cache pCache.
37131*/
37132static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
37133  PgHdr1 *p = 0;
37134  void *pPg;
37135
37136  /* The group mutex must be released before pcache1Alloc() is called. This
37137  ** is because it may call sqlite3_release_memory(), which assumes that
37138  ** this mutex is not held. */
37139  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37140  pcache1LeaveMutex(pCache->pGroup);
37141#ifdef SQLITE_PCACHE_SEPARATE_HEADER
37142  pPg = pcache1Alloc(pCache->szPage);
37143  p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
37144  if( !pPg || !p ){
37145    pcache1Free(pPg);
37146    sqlite3_free(p);
37147    pPg = 0;
37148  }
37149#else
37150  pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
37151  p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
37152#endif
37153  pcache1EnterMutex(pCache->pGroup);
37154
37155  if( pPg ){
37156    p->page.pBuf = pPg;
37157    p->page.pExtra = &p[1];
37158    if( pCache->bPurgeable ){
37159      pCache->pGroup->nCurrentPage++;
37160    }
37161    return p;
37162  }
37163  return 0;
37164}
37165
37166/*
37167** Free a page object allocated by pcache1AllocPage().
37168**
37169** The pointer is allowed to be NULL, which is prudent.  But it turns out
37170** that the current implementation happens to never call this routine
37171** with a NULL pointer, so we mark the NULL test with ALWAYS().
37172*/
37173static void pcache1FreePage(PgHdr1 *p){
37174  if( ALWAYS(p) ){
37175    PCache1 *pCache = p->pCache;
37176    assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
37177    pcache1Free(p->page.pBuf);
37178#ifdef SQLITE_PCACHE_SEPARATE_HEADER
37179    sqlite3_free(p);
37180#endif
37181    if( pCache->bPurgeable ){
37182      pCache->pGroup->nCurrentPage--;
37183    }
37184  }
37185}
37186
37187/*
37188** Malloc function used by SQLite to obtain space from the buffer configured
37189** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
37190** exists, this function falls back to sqlite3Malloc().
37191*/
37192SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
37193  return pcache1Alloc(sz);
37194}
37195
37196/*
37197** Free an allocated buffer obtained from sqlite3PageMalloc().
37198*/
37199SQLITE_PRIVATE void sqlite3PageFree(void *p){
37200  pcache1Free(p);
37201}
37202
37203
37204/*
37205** Return true if it desirable to avoid allocating a new page cache
37206** entry.
37207**
37208** If memory was allocated specifically to the page cache using
37209** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
37210** it is desirable to avoid allocating a new page cache entry because
37211** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
37212** for all page cache needs and we should not need to spill the
37213** allocation onto the heap.
37214**
37215** Or, the heap is used for all page cache memory but the heap is
37216** under memory pressure, then again it is desirable to avoid
37217** allocating a new page cache entry in order to avoid stressing
37218** the heap even further.
37219*/
37220static int pcache1UnderMemoryPressure(PCache1 *pCache){
37221  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
37222    return pcache1.bUnderPressure;
37223  }else{
37224    return sqlite3HeapNearlyFull();
37225  }
37226}
37227
37228/******************************************************************************/
37229/******** General Implementation Functions ************************************/
37230
37231/*
37232** This function is used to resize the hash table used by the cache passed
37233** as the first argument.
37234**
37235** The PCache mutex must be held when this function is called.
37236*/
37237static int pcache1ResizeHash(PCache1 *p){
37238  PgHdr1 **apNew;
37239  unsigned int nNew;
37240  unsigned int i;
37241
37242  assert( sqlite3_mutex_held(p->pGroup->mutex) );
37243
37244  nNew = p->nHash*2;
37245  if( nNew<256 ){
37246    nNew = 256;
37247  }
37248
37249  pcache1LeaveMutex(p->pGroup);
37250  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
37251  apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
37252  if( p->nHash ){ sqlite3EndBenignMalloc(); }
37253  pcache1EnterMutex(p->pGroup);
37254  if( apNew ){
37255    memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
37256    for(i=0; i<p->nHash; i++){
37257      PgHdr1 *pPage;
37258      PgHdr1 *pNext = p->apHash[i];
37259      while( (pPage = pNext)!=0 ){
37260        unsigned int h = pPage->iKey % nNew;
37261        pNext = pPage->pNext;
37262        pPage->pNext = apNew[h];
37263        apNew[h] = pPage;
37264      }
37265    }
37266    sqlite3_free(p->apHash);
37267    p->apHash = apNew;
37268    p->nHash = nNew;
37269  }
37270
37271  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
37272}
37273
37274/*
37275** This function is used internally to remove the page pPage from the
37276** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
37277** LRU list, then this function is a no-op.
37278**
37279** The PGroup mutex must be held when this function is called.
37280**
37281** If pPage is NULL then this routine is a no-op.
37282*/
37283static void pcache1PinPage(PgHdr1 *pPage){
37284  PCache1 *pCache;
37285  PGroup *pGroup;
37286
37287  if( pPage==0 ) return;
37288  pCache = pPage->pCache;
37289  pGroup = pCache->pGroup;
37290  assert( sqlite3_mutex_held(pGroup->mutex) );
37291  if( pPage->pLruNext || pPage==pGroup->pLruTail ){
37292    if( pPage->pLruPrev ){
37293      pPage->pLruPrev->pLruNext = pPage->pLruNext;
37294    }
37295    if( pPage->pLruNext ){
37296      pPage->pLruNext->pLruPrev = pPage->pLruPrev;
37297    }
37298    if( pGroup->pLruHead==pPage ){
37299      pGroup->pLruHead = pPage->pLruNext;
37300    }
37301    if( pGroup->pLruTail==pPage ){
37302      pGroup->pLruTail = pPage->pLruPrev;
37303    }
37304    pPage->pLruNext = 0;
37305    pPage->pLruPrev = 0;
37306    pPage->pCache->nRecyclable--;
37307  }
37308}
37309
37310
37311/*
37312** Remove the page supplied as an argument from the hash table
37313** (PCache1.apHash structure) that it is currently stored in.
37314**
37315** The PGroup mutex must be held when this function is called.
37316*/
37317static void pcache1RemoveFromHash(PgHdr1 *pPage){
37318  unsigned int h;
37319  PCache1 *pCache = pPage->pCache;
37320  PgHdr1 **pp;
37321
37322  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37323  h = pPage->iKey % pCache->nHash;
37324  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
37325  *pp = (*pp)->pNext;
37326
37327  pCache->nPage--;
37328}
37329
37330/*
37331** If there are currently more than nMaxPage pages allocated, try
37332** to recycle pages to reduce the number allocated to nMaxPage.
37333*/
37334static void pcache1EnforceMaxPage(PGroup *pGroup){
37335  assert( sqlite3_mutex_held(pGroup->mutex) );
37336  while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
37337    PgHdr1 *p = pGroup->pLruTail;
37338    assert( p->pCache->pGroup==pGroup );
37339    pcache1PinPage(p);
37340    pcache1RemoveFromHash(p);
37341    pcache1FreePage(p);
37342  }
37343}
37344
37345/*
37346** Discard all pages from cache pCache with a page number (key value)
37347** greater than or equal to iLimit. Any pinned pages that meet this
37348** criteria are unpinned before they are discarded.
37349**
37350** The PCache mutex must be held when this function is called.
37351*/
37352static void pcache1TruncateUnsafe(
37353  PCache1 *pCache,             /* The cache to truncate */
37354  unsigned int iLimit          /* Drop pages with this pgno or larger */
37355){
37356  TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
37357  unsigned int h;
37358  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37359  for(h=0; h<pCache->nHash; h++){
37360    PgHdr1 **pp = &pCache->apHash[h];
37361    PgHdr1 *pPage;
37362    while( (pPage = *pp)!=0 ){
37363      if( pPage->iKey>=iLimit ){
37364        pCache->nPage--;
37365        *pp = pPage->pNext;
37366        pcache1PinPage(pPage);
37367        pcache1FreePage(pPage);
37368      }else{
37369        pp = &pPage->pNext;
37370        TESTONLY( nPage++; )
37371      }
37372    }
37373  }
37374  assert( pCache->nPage==nPage );
37375}
37376
37377/******************************************************************************/
37378/******** sqlite3_pcache Methods **********************************************/
37379
37380/*
37381** Implementation of the sqlite3_pcache.xInit method.
37382*/
37383static int pcache1Init(void *NotUsed){
37384  UNUSED_PARAMETER(NotUsed);
37385  assert( pcache1.isInit==0 );
37386  memset(&pcache1, 0, sizeof(pcache1));
37387  if( sqlite3GlobalConfig.bCoreMutex ){
37388    pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
37389    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
37390  }
37391  pcache1.grp.mxPinned = 10;
37392  pcache1.isInit = 1;
37393  return SQLITE_OK;
37394}
37395
37396/*
37397** Implementation of the sqlite3_pcache.xShutdown method.
37398** Note that the static mutex allocated in xInit does
37399** not need to be freed.
37400*/
37401static void pcache1Shutdown(void *NotUsed){
37402  UNUSED_PARAMETER(NotUsed);
37403  assert( pcache1.isInit!=0 );
37404  memset(&pcache1, 0, sizeof(pcache1));
37405}
37406
37407/*
37408** Implementation of the sqlite3_pcache.xCreate method.
37409**
37410** Allocate a new cache.
37411*/
37412static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
37413  PCache1 *pCache;      /* The newly created page cache */
37414  PGroup *pGroup;       /* The group the new page cache will belong to */
37415  int sz;               /* Bytes of memory required to allocate the new cache */
37416
37417  /*
37418  ** The seperateCache variable is true if each PCache has its own private
37419  ** PGroup.  In other words, separateCache is true for mode (1) where no
37420  ** mutexing is required.
37421  **
37422  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
37423  **
37424  **   *  Always use a unified cache in single-threaded applications
37425  **
37426  **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
37427  **      use separate caches (mode-1)
37428  */
37429#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
37430  const int separateCache = 0;
37431#else
37432  int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
37433#endif
37434
37435  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
37436  assert( szExtra < 300 );
37437
37438  sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
37439  pCache = (PCache1 *)sqlite3_malloc(sz);
37440  if( pCache ){
37441    memset(pCache, 0, sz);
37442    if( separateCache ){
37443      pGroup = (PGroup*)&pCache[1];
37444      pGroup->mxPinned = 10;
37445    }else{
37446      pGroup = &pcache1.grp;
37447    }
37448    pCache->pGroup = pGroup;
37449    pCache->szPage = szPage;
37450    pCache->szExtra = szExtra;
37451    pCache->bPurgeable = (bPurgeable ? 1 : 0);
37452    if( bPurgeable ){
37453      pCache->nMin = 10;
37454      pcache1EnterMutex(pGroup);
37455      pGroup->nMinPage += pCache->nMin;
37456      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37457      pcache1LeaveMutex(pGroup);
37458    }
37459  }
37460  return (sqlite3_pcache *)pCache;
37461}
37462
37463/*
37464** Implementation of the sqlite3_pcache.xCachesize method.
37465**
37466** Configure the cache_size limit for a cache.
37467*/
37468static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
37469  PCache1 *pCache = (PCache1 *)p;
37470  if( pCache->bPurgeable ){
37471    PGroup *pGroup = pCache->pGroup;
37472    pcache1EnterMutex(pGroup);
37473    pGroup->nMaxPage += (nMax - pCache->nMax);
37474    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37475    pCache->nMax = nMax;
37476    pCache->n90pct = pCache->nMax*9/10;
37477    pcache1EnforceMaxPage(pGroup);
37478    pcache1LeaveMutex(pGroup);
37479  }
37480}
37481
37482/*
37483** Implementation of the sqlite3_pcache.xShrink method.
37484**
37485** Free up as much memory as possible.
37486*/
37487static void pcache1Shrink(sqlite3_pcache *p){
37488  PCache1 *pCache = (PCache1*)p;
37489  if( pCache->bPurgeable ){
37490    PGroup *pGroup = pCache->pGroup;
37491    int savedMaxPage;
37492    pcache1EnterMutex(pGroup);
37493    savedMaxPage = pGroup->nMaxPage;
37494    pGroup->nMaxPage = 0;
37495    pcache1EnforceMaxPage(pGroup);
37496    pGroup->nMaxPage = savedMaxPage;
37497    pcache1LeaveMutex(pGroup);
37498  }
37499}
37500
37501/*
37502** Implementation of the sqlite3_pcache.xPagecount method.
37503*/
37504static int pcache1Pagecount(sqlite3_pcache *p){
37505  int n;
37506  PCache1 *pCache = (PCache1*)p;
37507  pcache1EnterMutex(pCache->pGroup);
37508  n = pCache->nPage;
37509  pcache1LeaveMutex(pCache->pGroup);
37510  return n;
37511}
37512
37513/*
37514** Implementation of the sqlite3_pcache.xFetch method.
37515**
37516** Fetch a page by key value.
37517**
37518** Whether or not a new page may be allocated by this function depends on
37519** the value of the createFlag argument.  0 means do not allocate a new
37520** page.  1 means allocate a new page if space is easily available.  2
37521** means to try really hard to allocate a new page.
37522**
37523** For a non-purgeable cache (a cache used as the storage for an in-memory
37524** database) there is really no difference between createFlag 1 and 2.  So
37525** the calling function (pcache.c) will never have a createFlag of 1 on
37526** a non-purgeable cache.
37527**
37528** There are three different approaches to obtaining space for a page,
37529** depending on the value of parameter createFlag (which may be 0, 1 or 2).
37530**
37531**   1. Regardless of the value of createFlag, the cache is searched for a
37532**      copy of the requested page. If one is found, it is returned.
37533**
37534**   2. If createFlag==0 and the page is not already in the cache, NULL is
37535**      returned.
37536**
37537**   3. If createFlag is 1, and the page is not already in the cache, then
37538**      return NULL (do not allocate a new page) if any of the following
37539**      conditions are true:
37540**
37541**       (a) the number of pages pinned by the cache is greater than
37542**           PCache1.nMax, or
37543**
37544**       (b) the number of pages pinned by the cache is greater than
37545**           the sum of nMax for all purgeable caches, less the sum of
37546**           nMin for all other purgeable caches, or
37547**
37548**   4. If none of the first three conditions apply and the cache is marked
37549**      as purgeable, and if one of the following is true:
37550**
37551**       (a) The number of pages allocated for the cache is already
37552**           PCache1.nMax, or
37553**
37554**       (b) The number of pages allocated for all purgeable caches is
37555**           already equal to or greater than the sum of nMax for all
37556**           purgeable caches,
37557**
37558**       (c) The system is under memory pressure and wants to avoid
37559**           unnecessary pages cache entry allocations
37560**
37561**      then attempt to recycle a page from the LRU list. If it is the right
37562**      size, return the recycled buffer. Otherwise, free the buffer and
37563**      proceed to step 5.
37564**
37565**   5. Otherwise, allocate and return a new page buffer.
37566*/
37567static sqlite3_pcache_page *pcache1Fetch(
37568  sqlite3_pcache *p,
37569  unsigned int iKey,
37570  int createFlag
37571){
37572  unsigned int nPinned;
37573  PCache1 *pCache = (PCache1 *)p;
37574  PGroup *pGroup;
37575  PgHdr1 *pPage = 0;
37576
37577  assert( pCache->bPurgeable || createFlag!=1 );
37578  assert( pCache->bPurgeable || pCache->nMin==0 );
37579  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
37580  assert( pCache->nMin==0 || pCache->bPurgeable );
37581  pcache1EnterMutex(pGroup = pCache->pGroup);
37582
37583  /* Step 1: Search the hash table for an existing entry. */
37584  if( pCache->nHash>0 ){
37585    unsigned int h = iKey % pCache->nHash;
37586    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
37587  }
37588
37589  /* Step 2: Abort if no existing page is found and createFlag is 0 */
37590  if( pPage || createFlag==0 ){
37591    pcache1PinPage(pPage);
37592    goto fetch_out;
37593  }
37594
37595  /* The pGroup local variable will normally be initialized by the
37596  ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
37597  ** then pcache1EnterMutex() is a no-op, so we have to initialize the
37598  ** local variable here.  Delaying the initialization of pGroup is an
37599  ** optimization:  The common case is to exit the module before reaching
37600  ** this point.
37601  */
37602#ifdef SQLITE_MUTEX_OMIT
37603  pGroup = pCache->pGroup;
37604#endif
37605
37606  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
37607  assert( pCache->nPage >= pCache->nRecyclable );
37608  nPinned = pCache->nPage - pCache->nRecyclable;
37609  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
37610  assert( pCache->n90pct == pCache->nMax*9/10 );
37611  if( createFlag==1 && (
37612        nPinned>=pGroup->mxPinned
37613     || nPinned>=pCache->n90pct
37614     || pcache1UnderMemoryPressure(pCache)
37615  )){
37616    goto fetch_out;
37617  }
37618
37619  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
37620    goto fetch_out;
37621  }
37622
37623  /* Step 4. Try to recycle a page. */
37624  if( pCache->bPurgeable && pGroup->pLruTail && (
37625         (pCache->nPage+1>=pCache->nMax)
37626      || pGroup->nCurrentPage>=pGroup->nMaxPage
37627      || pcache1UnderMemoryPressure(pCache)
37628  )){
37629    PCache1 *pOther;
37630    pPage = pGroup->pLruTail;
37631    pcache1RemoveFromHash(pPage);
37632    pcache1PinPage(pPage);
37633    pOther = pPage->pCache;
37634
37635    /* We want to verify that szPage and szExtra are the same for pOther
37636    ** and pCache.  Assert that we can verify this by comparing sums. */
37637    assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
37638    assert( pCache->szExtra<512 );
37639    assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
37640    assert( pOther->szExtra<512 );
37641
37642    if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
37643      pcache1FreePage(pPage);
37644      pPage = 0;
37645    }else{
37646      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
37647    }
37648  }
37649
37650  /* Step 5. If a usable page buffer has still not been found,
37651  ** attempt to allocate a new one.
37652  */
37653  if( !pPage ){
37654    if( createFlag==1 ) sqlite3BeginBenignMalloc();
37655    pPage = pcache1AllocPage(pCache);
37656    if( createFlag==1 ) sqlite3EndBenignMalloc();
37657  }
37658
37659  if( pPage ){
37660    unsigned int h = iKey % pCache->nHash;
37661    pCache->nPage++;
37662    pPage->iKey = iKey;
37663    pPage->pNext = pCache->apHash[h];
37664    pPage->pCache = pCache;
37665    pPage->pLruPrev = 0;
37666    pPage->pLruNext = 0;
37667    *(void **)pPage->page.pExtra = 0;
37668    pCache->apHash[h] = pPage;
37669  }
37670
37671fetch_out:
37672  if( pPage && iKey>pCache->iMaxKey ){
37673    pCache->iMaxKey = iKey;
37674  }
37675  pcache1LeaveMutex(pGroup);
37676  return &pPage->page;
37677}
37678
37679
37680/*
37681** Implementation of the sqlite3_pcache.xUnpin method.
37682**
37683** Mark a page as unpinned (eligible for asynchronous recycling).
37684*/
37685static void pcache1Unpin(
37686  sqlite3_pcache *p,
37687  sqlite3_pcache_page *pPg,
37688  int reuseUnlikely
37689){
37690  PCache1 *pCache = (PCache1 *)p;
37691  PgHdr1 *pPage = (PgHdr1 *)pPg;
37692  PGroup *pGroup = pCache->pGroup;
37693
37694  assert( pPage->pCache==pCache );
37695  pcache1EnterMutex(pGroup);
37696
37697  /* It is an error to call this function if the page is already
37698  ** part of the PGroup LRU list.
37699  */
37700  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
37701  assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
37702
37703  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
37704    pcache1RemoveFromHash(pPage);
37705    pcache1FreePage(pPage);
37706  }else{
37707    /* Add the page to the PGroup LRU list. */
37708    if( pGroup->pLruHead ){
37709      pGroup->pLruHead->pLruPrev = pPage;
37710      pPage->pLruNext = pGroup->pLruHead;
37711      pGroup->pLruHead = pPage;
37712    }else{
37713      pGroup->pLruTail = pPage;
37714      pGroup->pLruHead = pPage;
37715    }
37716    pCache->nRecyclable++;
37717  }
37718
37719  pcache1LeaveMutex(pCache->pGroup);
37720}
37721
37722/*
37723** Implementation of the sqlite3_pcache.xRekey method.
37724*/
37725static void pcache1Rekey(
37726  sqlite3_pcache *p,
37727  sqlite3_pcache_page *pPg,
37728  unsigned int iOld,
37729  unsigned int iNew
37730){
37731  PCache1 *pCache = (PCache1 *)p;
37732  PgHdr1 *pPage = (PgHdr1 *)pPg;
37733  PgHdr1 **pp;
37734  unsigned int h;
37735  assert( pPage->iKey==iOld );
37736  assert( pPage->pCache==pCache );
37737
37738  pcache1EnterMutex(pCache->pGroup);
37739
37740  h = iOld%pCache->nHash;
37741  pp = &pCache->apHash[h];
37742  while( (*pp)!=pPage ){
37743    pp = &(*pp)->pNext;
37744  }
37745  *pp = pPage->pNext;
37746
37747  h = iNew%pCache->nHash;
37748  pPage->iKey = iNew;
37749  pPage->pNext = pCache->apHash[h];
37750  pCache->apHash[h] = pPage;
37751  if( iNew>pCache->iMaxKey ){
37752    pCache->iMaxKey = iNew;
37753  }
37754
37755  pcache1LeaveMutex(pCache->pGroup);
37756}
37757
37758/*
37759** Implementation of the sqlite3_pcache.xTruncate method.
37760**
37761** Discard all unpinned pages in the cache with a page number equal to
37762** or greater than parameter iLimit. Any pinned pages with a page number
37763** equal to or greater than iLimit are implicitly unpinned.
37764*/
37765static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
37766  PCache1 *pCache = (PCache1 *)p;
37767  pcache1EnterMutex(pCache->pGroup);
37768  if( iLimit<=pCache->iMaxKey ){
37769    pcache1TruncateUnsafe(pCache, iLimit);
37770    pCache->iMaxKey = iLimit-1;
37771  }
37772  pcache1LeaveMutex(pCache->pGroup);
37773}
37774
37775/*
37776** Implementation of the sqlite3_pcache.xDestroy method.
37777**
37778** Destroy a cache allocated using pcache1Create().
37779*/
37780static void pcache1Destroy(sqlite3_pcache *p){
37781  PCache1 *pCache = (PCache1 *)p;
37782  PGroup *pGroup = pCache->pGroup;
37783  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
37784  pcache1EnterMutex(pGroup);
37785  pcache1TruncateUnsafe(pCache, 0);
37786  assert( pGroup->nMaxPage >= pCache->nMax );
37787  pGroup->nMaxPage -= pCache->nMax;
37788  assert( pGroup->nMinPage >= pCache->nMin );
37789  pGroup->nMinPage -= pCache->nMin;
37790  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37791  pcache1EnforceMaxPage(pGroup);
37792  pcache1LeaveMutex(pGroup);
37793  sqlite3_free(pCache->apHash);
37794  sqlite3_free(pCache);
37795}
37796
37797/*
37798** This function is called during initialization (sqlite3_initialize()) to
37799** install the default pluggable cache module, assuming the user has not
37800** already provided an alternative.
37801*/
37802SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
37803  static const sqlite3_pcache_methods2 defaultMethods = {
37804    1,                       /* iVersion */
37805    0,                       /* pArg */
37806    pcache1Init,             /* xInit */
37807    pcache1Shutdown,         /* xShutdown */
37808    pcache1Create,           /* xCreate */
37809    pcache1Cachesize,        /* xCachesize */
37810    pcache1Pagecount,        /* xPagecount */
37811    pcache1Fetch,            /* xFetch */
37812    pcache1Unpin,            /* xUnpin */
37813    pcache1Rekey,            /* xRekey */
37814    pcache1Truncate,         /* xTruncate */
37815    pcache1Destroy,          /* xDestroy */
37816    pcache1Shrink            /* xShrink */
37817  };
37818  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
37819}
37820
37821#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
37822/*
37823** This function is called to free superfluous dynamically allocated memory
37824** held by the pager system. Memory in use by any SQLite pager allocated
37825** by the current thread may be sqlite3_free()ed.
37826**
37827** nReq is the number of bytes of memory required. Once this much has
37828** been released, the function returns. The return value is the total number
37829** of bytes of memory released.
37830*/
37831SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
37832  int nFree = 0;
37833  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
37834  assert( sqlite3_mutex_notheld(pcache1.mutex) );
37835  if( pcache1.pStart==0 ){
37836    PgHdr1 *p;
37837    pcache1EnterMutex(&pcache1.grp);
37838    while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
37839      nFree += pcache1MemSize(p->page.pBuf);
37840#ifdef SQLITE_PCACHE_SEPARATE_HEADER
37841      nFree += sqlite3MemSize(p);
37842#endif
37843      pcache1PinPage(p);
37844      pcache1RemoveFromHash(p);
37845      pcache1FreePage(p);
37846    }
37847    pcache1LeaveMutex(&pcache1.grp);
37848  }
37849  return nFree;
37850}
37851#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
37852
37853#ifdef SQLITE_TEST
37854/*
37855** This function is used by test procedures to inspect the internal state
37856** of the global cache.
37857*/
37858SQLITE_PRIVATE void sqlite3PcacheStats(
37859  int *pnCurrent,      /* OUT: Total number of pages cached */
37860  int *pnMax,          /* OUT: Global maximum cache size */
37861  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
37862  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
37863){
37864  PgHdr1 *p;
37865  int nRecyclable = 0;
37866  for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
37867    nRecyclable++;
37868  }
37869  *pnCurrent = pcache1.grp.nCurrentPage;
37870  *pnMax = (int)pcache1.grp.nMaxPage;
37871  *pnMin = (int)pcache1.grp.nMinPage;
37872  *pnRecyclable = nRecyclable;
37873}
37874#endif
37875
37876/************** End of pcache1.c *********************************************/
37877/************** Begin file rowset.c ******************************************/
37878/*
37879** 2008 December 3
37880**
37881** The author disclaims copyright to this source code.  In place of
37882** a legal notice, here is a blessing:
37883**
37884**    May you do good and not evil.
37885**    May you find forgiveness for yourself and forgive others.
37886**    May you share freely, never taking more than you give.
37887**
37888*************************************************************************
37889**
37890** This module implements an object we call a "RowSet".
37891**
37892** The RowSet object is a collection of rowids.  Rowids
37893** are inserted into the RowSet in an arbitrary order.  Inserts
37894** can be intermixed with tests to see if a given rowid has been
37895** previously inserted into the RowSet.
37896**
37897** After all inserts are finished, it is possible to extract the
37898** elements of the RowSet in sorted order.  Once this extraction
37899** process has started, no new elements may be inserted.
37900**
37901** Hence, the primitive operations for a RowSet are:
37902**
37903**    CREATE
37904**    INSERT
37905**    TEST
37906**    SMALLEST
37907**    DESTROY
37908**
37909** The CREATE and DESTROY primitives are the constructor and destructor,
37910** obviously.  The INSERT primitive adds a new element to the RowSet.
37911** TEST checks to see if an element is already in the RowSet.  SMALLEST
37912** extracts the least value from the RowSet.
37913**
37914** The INSERT primitive might allocate additional memory.  Memory is
37915** allocated in chunks so most INSERTs do no allocation.  There is an
37916** upper bound on the size of allocated memory.  No memory is freed
37917** until DESTROY.
37918**
37919** The TEST primitive includes a "batch" number.  The TEST primitive
37920** will only see elements that were inserted before the last change
37921** in the batch number.  In other words, if an INSERT occurs between
37922** two TESTs where the TESTs have the same batch nubmer, then the
37923** value added by the INSERT will not be visible to the second TEST.
37924** The initial batch number is zero, so if the very first TEST contains
37925** a non-zero batch number, it will see all prior INSERTs.
37926**
37927** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
37928** that is attempted.
37929**
37930** The cost of an INSERT is roughly constant.  (Sometime new memory
37931** has to be allocated on an INSERT.)  The cost of a TEST with a new
37932** batch number is O(NlogN) where N is the number of elements in the RowSet.
37933** The cost of a TEST using the same batch number is O(logN).  The cost
37934** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
37935** primitives are constant time.  The cost of DESTROY is O(N).
37936**
37937** There is an added cost of O(N) when switching between TEST and
37938** SMALLEST primitives.
37939*/
37940
37941
37942/*
37943** Target size for allocation chunks.
37944*/
37945#define ROWSET_ALLOCATION_SIZE 1024
37946
37947/*
37948** The number of rowset entries per allocation chunk.
37949*/
37950#define ROWSET_ENTRY_PER_CHUNK  \
37951                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
37952
37953/*
37954** Each entry in a RowSet is an instance of the following object.
37955*/
37956struct RowSetEntry {
37957  i64 v;                        /* ROWID value for this entry */
37958  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
37959  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
37960};
37961
37962/*
37963** RowSetEntry objects are allocated in large chunks (instances of the
37964** following structure) to reduce memory allocation overhead.  The
37965** chunks are kept on a linked list so that they can be deallocated
37966** when the RowSet is destroyed.
37967*/
37968struct RowSetChunk {
37969  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
37970  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
37971};
37972
37973/*
37974** A RowSet in an instance of the following structure.
37975**
37976** A typedef of this structure if found in sqliteInt.h.
37977*/
37978struct RowSet {
37979  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
37980  sqlite3 *db;                   /* The database connection */
37981  struct RowSetEntry *pEntry;    /* List of entries using pRight */
37982  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
37983  struct RowSetEntry *pFresh;    /* Source of new entry objects */
37984  struct RowSetEntry *pTree;     /* Binary tree of entries */
37985  u16 nFresh;                    /* Number of objects on pFresh */
37986  u8 isSorted;                   /* True if pEntry is sorted */
37987  u8 iBatch;                     /* Current insert batch */
37988};
37989
37990/*
37991** Turn bulk memory into a RowSet object.  N bytes of memory
37992** are available at pSpace.  The db pointer is used as a memory context
37993** for any subsequent allocations that need to occur.
37994** Return a pointer to the new RowSet object.
37995**
37996** It must be the case that N is sufficient to make a Rowset.  If not
37997** an assertion fault occurs.
37998**
37999** If N is larger than the minimum, use the surplus as an initial
38000** allocation of entries available to be filled.
38001*/
38002SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
38003  RowSet *p;
38004  assert( N >= ROUND8(sizeof(*p)) );
38005  p = pSpace;
38006  p->pChunk = 0;
38007  p->db = db;
38008  p->pEntry = 0;
38009  p->pLast = 0;
38010  p->pTree = 0;
38011  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
38012  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
38013  p->isSorted = 1;
38014  p->iBatch = 0;
38015  return p;
38016}
38017
38018/*
38019** Deallocate all chunks from a RowSet.  This frees all memory that
38020** the RowSet has allocated over its lifetime.  This routine is
38021** the destructor for the RowSet.
38022*/
38023SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
38024  struct RowSetChunk *pChunk, *pNextChunk;
38025  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
38026    pNextChunk = pChunk->pNextChunk;
38027    sqlite3DbFree(p->db, pChunk);
38028  }
38029  p->pChunk = 0;
38030  p->nFresh = 0;
38031  p->pEntry = 0;
38032  p->pLast = 0;
38033  p->pTree = 0;
38034  p->isSorted = 1;
38035}
38036
38037/*
38038** Insert a new value into a RowSet.
38039**
38040** The mallocFailed flag of the database connection is set if a
38041** memory allocation fails.
38042*/
38043SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
38044  struct RowSetEntry *pEntry;  /* The new entry */
38045  struct RowSetEntry *pLast;   /* The last prior entry */
38046  assert( p!=0 );
38047  if( p->nFresh==0 ){
38048    struct RowSetChunk *pNew;
38049    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
38050    if( pNew==0 ){
38051      return;
38052    }
38053    pNew->pNextChunk = p->pChunk;
38054    p->pChunk = pNew;
38055    p->pFresh = pNew->aEntry;
38056    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
38057  }
38058  pEntry = p->pFresh++;
38059  p->nFresh--;
38060  pEntry->v = rowid;
38061  pEntry->pRight = 0;
38062  pLast = p->pLast;
38063  if( pLast ){
38064    if( p->isSorted && rowid<=pLast->v ){
38065      p->isSorted = 0;
38066    }
38067    pLast->pRight = pEntry;
38068  }else{
38069    assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
38070    p->pEntry = pEntry;
38071  }
38072  p->pLast = pEntry;
38073}
38074
38075/*
38076** Merge two lists of RowSetEntry objects.  Remove duplicates.
38077**
38078** The input lists are connected via pRight pointers and are
38079** assumed to each already be in sorted order.
38080*/
38081static struct RowSetEntry *rowSetMerge(
38082  struct RowSetEntry *pA,    /* First sorted list to be merged */
38083  struct RowSetEntry *pB     /* Second sorted list to be merged */
38084){
38085  struct RowSetEntry head;
38086  struct RowSetEntry *pTail;
38087
38088  pTail = &head;
38089  while( pA && pB ){
38090    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
38091    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
38092    if( pA->v<pB->v ){
38093      pTail->pRight = pA;
38094      pA = pA->pRight;
38095      pTail = pTail->pRight;
38096    }else if( pB->v<pA->v ){
38097      pTail->pRight = pB;
38098      pB = pB->pRight;
38099      pTail = pTail->pRight;
38100    }else{
38101      pA = pA->pRight;
38102    }
38103  }
38104  if( pA ){
38105    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
38106    pTail->pRight = pA;
38107  }else{
38108    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
38109    pTail->pRight = pB;
38110  }
38111  return head.pRight;
38112}
38113
38114/*
38115** Sort all elements on the pEntry list of the RowSet into ascending order.
38116*/
38117static void rowSetSort(RowSet *p){
38118  unsigned int i;
38119  struct RowSetEntry *pEntry;
38120  struct RowSetEntry *aBucket[40];
38121
38122  assert( p->isSorted==0 );
38123  memset(aBucket, 0, sizeof(aBucket));
38124  while( p->pEntry ){
38125    pEntry = p->pEntry;
38126    p->pEntry = pEntry->pRight;
38127    pEntry->pRight = 0;
38128    for(i=0; aBucket[i]; i++){
38129      pEntry = rowSetMerge(aBucket[i], pEntry);
38130      aBucket[i] = 0;
38131    }
38132    aBucket[i] = pEntry;
38133  }
38134  pEntry = 0;
38135  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
38136    pEntry = rowSetMerge(pEntry, aBucket[i]);
38137  }
38138  p->pEntry = pEntry;
38139  p->pLast = 0;
38140  p->isSorted = 1;
38141}
38142
38143
38144/*
38145** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
38146** Convert this tree into a linked list connected by the pRight pointers
38147** and return pointers to the first and last elements of the new list.
38148*/
38149static void rowSetTreeToList(
38150  struct RowSetEntry *pIn,         /* Root of the input tree */
38151  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
38152  struct RowSetEntry **ppLast      /* Write tail of the output list here */
38153){
38154  assert( pIn!=0 );
38155  if( pIn->pLeft ){
38156    struct RowSetEntry *p;
38157    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
38158    p->pRight = pIn;
38159  }else{
38160    *ppFirst = pIn;
38161  }
38162  if( pIn->pRight ){
38163    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
38164  }else{
38165    *ppLast = pIn;
38166  }
38167  assert( (*ppLast)->pRight==0 );
38168}
38169
38170
38171/*
38172** Convert a sorted list of elements (connected by pRight) into a binary
38173** tree with depth of iDepth.  A depth of 1 means the tree contains a single
38174** node taken from the head of *ppList.  A depth of 2 means a tree with
38175** three nodes.  And so forth.
38176**
38177** Use as many entries from the input list as required and update the
38178** *ppList to point to the unused elements of the list.  If the input
38179** list contains too few elements, then construct an incomplete tree
38180** and leave *ppList set to NULL.
38181**
38182** Return a pointer to the root of the constructed binary tree.
38183*/
38184static struct RowSetEntry *rowSetNDeepTree(
38185  struct RowSetEntry **ppList,
38186  int iDepth
38187){
38188  struct RowSetEntry *p;         /* Root of the new tree */
38189  struct RowSetEntry *pLeft;     /* Left subtree */
38190  if( *ppList==0 ){
38191    return 0;
38192  }
38193  if( iDepth==1 ){
38194    p = *ppList;
38195    *ppList = p->pRight;
38196    p->pLeft = p->pRight = 0;
38197    return p;
38198  }
38199  pLeft = rowSetNDeepTree(ppList, iDepth-1);
38200  p = *ppList;
38201  if( p==0 ){
38202    return pLeft;
38203  }
38204  p->pLeft = pLeft;
38205  *ppList = p->pRight;
38206  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
38207  return p;
38208}
38209
38210/*
38211** Convert a sorted list of elements into a binary tree. Make the tree
38212** as deep as it needs to be in order to contain the entire list.
38213*/
38214static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
38215  int iDepth;           /* Depth of the tree so far */
38216  struct RowSetEntry *p;       /* Current tree root */
38217  struct RowSetEntry *pLeft;   /* Left subtree */
38218
38219  assert( pList!=0 );
38220  p = pList;
38221  pList = p->pRight;
38222  p->pLeft = p->pRight = 0;
38223  for(iDepth=1; pList; iDepth++){
38224    pLeft = p;
38225    p = pList;
38226    pList = p->pRight;
38227    p->pLeft = pLeft;
38228    p->pRight = rowSetNDeepTree(&pList, iDepth);
38229  }
38230  return p;
38231}
38232
38233/*
38234** Convert the list in p->pEntry into a sorted list if it is not
38235** sorted already.  If there is a binary tree on p->pTree, then
38236** convert it into a list too and merge it into the p->pEntry list.
38237*/
38238static void rowSetToList(RowSet *p){
38239  if( !p->isSorted ){
38240    rowSetSort(p);
38241  }
38242  if( p->pTree ){
38243    struct RowSetEntry *pHead, *pTail;
38244    rowSetTreeToList(p->pTree, &pHead, &pTail);
38245    p->pTree = 0;
38246    p->pEntry = rowSetMerge(p->pEntry, pHead);
38247  }
38248}
38249
38250/*
38251** Extract the smallest element from the RowSet.
38252** Write the element into *pRowid.  Return 1 on success.  Return
38253** 0 if the RowSet is already empty.
38254**
38255** After this routine has been called, the sqlite3RowSetInsert()
38256** routine may not be called again.
38257*/
38258SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
38259  rowSetToList(p);
38260  if( p->pEntry ){
38261    *pRowid = p->pEntry->v;
38262    p->pEntry = p->pEntry->pRight;
38263    if( p->pEntry==0 ){
38264      sqlite3RowSetClear(p);
38265    }
38266    return 1;
38267  }else{
38268    return 0;
38269  }
38270}
38271
38272/*
38273** Check to see if element iRowid was inserted into the the rowset as
38274** part of any insert batch prior to iBatch.  Return 1 or 0.
38275*/
38276SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
38277  struct RowSetEntry *p;
38278  if( iBatch!=pRowSet->iBatch ){
38279    if( pRowSet->pEntry ){
38280      rowSetToList(pRowSet);
38281      pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
38282      pRowSet->pEntry = 0;
38283      pRowSet->pLast = 0;
38284    }
38285    pRowSet->iBatch = iBatch;
38286  }
38287  p = pRowSet->pTree;
38288  while( p ){
38289    if( p->v<iRowid ){
38290      p = p->pRight;
38291    }else if( p->v>iRowid ){
38292      p = p->pLeft;
38293    }else{
38294      return 1;
38295    }
38296  }
38297  return 0;
38298}
38299
38300/************** End of rowset.c **********************************************/
38301/************** Begin file pager.c *******************************************/
38302/*
38303** 2001 September 15
38304**
38305** The author disclaims copyright to this source code.  In place of
38306** a legal notice, here is a blessing:
38307**
38308**    May you do good and not evil.
38309**    May you find forgiveness for yourself and forgive others.
38310**    May you share freely, never taking more than you give.
38311**
38312*************************************************************************
38313** This is the implementation of the page cache subsystem or "pager".
38314**
38315** The pager is used to access a database disk file.  It implements
38316** atomic commit and rollback through the use of a journal file that
38317** is separate from the database file.  The pager also implements file
38318** locking to prevent two processes from writing the same database
38319** file simultaneously, or one process from reading the database while
38320** another is writing.
38321*/
38322#ifndef SQLITE_OMIT_DISKIO
38323/************** Include wal.h in the middle of pager.c ***********************/
38324/************** Begin file wal.h *********************************************/
38325/*
38326** 2010 February 1
38327**
38328** The author disclaims copyright to this source code.  In place of
38329** a legal notice, here is a blessing:
38330**
38331**    May you do good and not evil.
38332**    May you find forgiveness for yourself and forgive others.
38333**    May you share freely, never taking more than you give.
38334**
38335*************************************************************************
38336** This header file defines the interface to the write-ahead logging
38337** system. Refer to the comments below and the header comment attached to
38338** the implementation of each function in log.c for further details.
38339*/
38340
38341#ifndef _WAL_H_
38342#define _WAL_H_
38343
38344
38345/* Additional values that can be added to the sync_flags argument of
38346** sqlite3WalFrames():
38347*/
38348#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
38349#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
38350
38351#ifdef SQLITE_OMIT_WAL
38352# define sqlite3WalOpen(x,y,z)                   0
38353# define sqlite3WalLimit(x,y)
38354# define sqlite3WalClose(w,x,y,z)                0
38355# define sqlite3WalBeginReadTransaction(y,z)     0
38356# define sqlite3WalEndReadTransaction(z)
38357# define sqlite3WalRead(v,w,x,y,z)               0
38358# define sqlite3WalDbsize(y)                     0
38359# define sqlite3WalBeginWriteTransaction(y)      0
38360# define sqlite3WalEndWriteTransaction(x)        0
38361# define sqlite3WalUndo(x,y,z)                   0
38362# define sqlite3WalSavepoint(y,z)
38363# define sqlite3WalSavepointUndo(y,z)            0
38364# define sqlite3WalFrames(u,v,w,x,y,z)           0
38365# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
38366# define sqlite3WalCallback(z)                   0
38367# define sqlite3WalExclusiveMode(y,z)            0
38368# define sqlite3WalHeapMemory(z)                 0
38369# define sqlite3WalFramesize(z)                  0
38370#else
38371
38372#define WAL_SAVEPOINT_NDATA 4
38373
38374/* Connection to a write-ahead log (WAL) file.
38375** There is one object of this type for each pager.
38376*/
38377typedef struct Wal Wal;
38378
38379/* Open and close a connection to a write-ahead log. */
38380SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
38381SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
38382
38383/* Set the limiting size of a WAL file. */
38384SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
38385
38386/* Used by readers to open (lock) and close (unlock) a snapshot.  A
38387** snapshot is like a read-transaction.  It is the state of the database
38388** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
38389** preserves the current state even if the other threads or processes
38390** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
38391** transaction and releases the lock.
38392*/
38393SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
38394SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
38395
38396/* Read a page from the write-ahead log, if it is present. */
38397SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
38398
38399/* If the WAL is not empty, return the size of the database. */
38400SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
38401
38402/* Obtain or release the WRITER lock. */
38403SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
38404SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
38405
38406/* Undo any frames written (but not committed) to the log */
38407SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
38408
38409/* Return an integer that records the current (uncommitted) write
38410** position in the WAL */
38411SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
38412
38413/* Move the write position of the WAL back to iFrame.  Called in
38414** response to a ROLLBACK TO command. */
38415SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
38416
38417/* Write a frame or frames to the log. */
38418SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
38419
38420/* Copy pages from the log to the database file */
38421SQLITE_PRIVATE int sqlite3WalCheckpoint(
38422  Wal *pWal,                      /* Write-ahead log connection */
38423  int eMode,                      /* One of PASSIVE, FULL and RESTART */
38424  int (*xBusy)(void*),            /* Function to call when busy */
38425  void *pBusyArg,                 /* Context argument for xBusyHandler */
38426  int sync_flags,                 /* Flags to sync db file with (or 0) */
38427  int nBuf,                       /* Size of buffer nBuf */
38428  u8 *zBuf,                       /* Temporary buffer to use */
38429  int *pnLog,                     /* OUT: Number of frames in WAL */
38430  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
38431);
38432
38433/* Return the value to pass to a sqlite3_wal_hook callback, the
38434** number of frames in the WAL at the point of the last commit since
38435** sqlite3WalCallback() was called.  If no commits have occurred since
38436** the last call, then return 0.
38437*/
38438SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
38439
38440/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
38441** by the pager layer on the database file.
38442*/
38443SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
38444
38445/* Return true if the argument is non-NULL and the WAL module is using
38446** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
38447** WAL module is using shared-memory, return false.
38448*/
38449SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
38450
38451#ifdef SQLITE_ENABLE_ZIPVFS
38452/* If the WAL file is not empty, return the number of bytes of content
38453** stored in each frame (i.e. the db page-size when the WAL was created).
38454*/
38455SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
38456#endif
38457
38458#endif /* ifndef SQLITE_OMIT_WAL */
38459#endif /* _WAL_H_ */
38460
38461/************** End of wal.h *************************************************/
38462/************** Continuing where we left off in pager.c **********************/
38463
38464
38465/******************* NOTES ON THE DESIGN OF THE PAGER ************************
38466**
38467** This comment block describes invariants that hold when using a rollback
38468** journal.  These invariants do not apply for journal_mode=WAL,
38469** journal_mode=MEMORY, or journal_mode=OFF.
38470**
38471** Within this comment block, a page is deemed to have been synced
38472** automatically as soon as it is written when PRAGMA synchronous=OFF.
38473** Otherwise, the page is not synced until the xSync method of the VFS
38474** is called successfully on the file containing the page.
38475**
38476** Definition:  A page of the database file is said to be "overwriteable" if
38477** one or more of the following are true about the page:
38478**
38479**     (a)  The original content of the page as it was at the beginning of
38480**          the transaction has been written into the rollback journal and
38481**          synced.
38482**
38483**     (b)  The page was a freelist leaf page at the start of the transaction.
38484**
38485**     (c)  The page number is greater than the largest page that existed in
38486**          the database file at the start of the transaction.
38487**
38488** (1) A page of the database file is never overwritten unless one of the
38489**     following are true:
38490**
38491**     (a) The page and all other pages on the same sector are overwriteable.
38492**
38493**     (b) The atomic page write optimization is enabled, and the entire
38494**         transaction other than the update of the transaction sequence
38495**         number consists of a single page change.
38496**
38497** (2) The content of a page written into the rollback journal exactly matches
38498**     both the content in the database when the rollback journal was written
38499**     and the content in the database at the beginning of the current
38500**     transaction.
38501**
38502** (3) Writes to the database file are an integer multiple of the page size
38503**     in length and are aligned on a page boundary.
38504**
38505** (4) Reads from the database file are either aligned on a page boundary and
38506**     an integer multiple of the page size in length or are taken from the
38507**     first 100 bytes of the database file.
38508**
38509** (5) All writes to the database file are synced prior to the rollback journal
38510**     being deleted, truncated, or zeroed.
38511**
38512** (6) If a master journal file is used, then all writes to the database file
38513**     are synced prior to the master journal being deleted.
38514**
38515** Definition: Two databases (or the same database at two points it time)
38516** are said to be "logically equivalent" if they give the same answer to
38517** all queries.  Note in particular the the content of freelist leaf
38518** pages can be changed arbitarily without effecting the logical equivalence
38519** of the database.
38520**
38521** (7) At any time, if any subset, including the empty set and the total set,
38522**     of the unsynced changes to a rollback journal are removed and the
38523**     journal is rolled back, the resulting database file will be logical
38524**     equivalent to the database file at the beginning of the transaction.
38525**
38526** (8) When a transaction is rolled back, the xTruncate method of the VFS
38527**     is called to restore the database file to the same size it was at
38528**     the beginning of the transaction.  (In some VFSes, the xTruncate
38529**     method is a no-op, but that does not change the fact the SQLite will
38530**     invoke it.)
38531**
38532** (9) Whenever the database file is modified, at least one bit in the range
38533**     of bytes from 24 through 39 inclusive will be changed prior to releasing
38534**     the EXCLUSIVE lock, thus signaling other connections on the same
38535**     database to flush their caches.
38536**
38537** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
38538**      than one billion transactions.
38539**
38540** (11) A database file is well-formed at the beginning and at the conclusion
38541**      of every transaction.
38542**
38543** (12) An EXCLUSIVE lock is held on the database file when writing to
38544**      the database file.
38545**
38546** (13) A SHARED lock is held on the database file while reading any
38547**      content out of the database file.
38548**
38549******************************************************************************/
38550
38551/*
38552** Macros for troubleshooting.  Normally turned off
38553*/
38554#if 0
38555int sqlite3PagerTrace=1;  /* True to enable tracing */
38556#define sqlite3DebugPrintf printf
38557#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
38558#else
38559#define PAGERTRACE(X)
38560#endif
38561
38562/*
38563** The following two macros are used within the PAGERTRACE() macros above
38564** to print out file-descriptors.
38565**
38566** PAGERID() takes a pointer to a Pager struct as its argument. The
38567** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
38568** struct as its argument.
38569*/
38570#define PAGERID(p) ((int)(p->fd))
38571#define FILEHANDLEID(fd) ((int)fd)
38572
38573/*
38574** The Pager.eState variable stores the current 'state' of a pager. A
38575** pager may be in any one of the seven states shown in the following
38576** state diagram.
38577**
38578**                            OPEN <------+------+
38579**                              |         |      |
38580**                              V         |      |
38581**               +---------> READER-------+      |
38582**               |              |                |
38583**               |              V                |
38584**               |<-------WRITER_LOCKED------> ERROR
38585**               |              |                ^
38586**               |              V                |
38587**               |<------WRITER_CACHEMOD-------->|
38588**               |              |                |
38589**               |              V                |
38590**               |<-------WRITER_DBMOD---------->|
38591**               |              |                |
38592**               |              V                |
38593**               +<------WRITER_FINISHED-------->+
38594**
38595**
38596** List of state transitions and the C [function] that performs each:
38597**
38598**   OPEN              -> READER              [sqlite3PagerSharedLock]
38599**   READER            -> OPEN                [pager_unlock]
38600**
38601**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
38602**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
38603**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
38604**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
38605**   WRITER_***        -> READER              [pager_end_transaction]
38606**
38607**   WRITER_***        -> ERROR               [pager_error]
38608**   ERROR             -> OPEN                [pager_unlock]
38609**
38610**
38611**  OPEN:
38612**
38613**    The pager starts up in this state. Nothing is guaranteed in this
38614**    state - the file may or may not be locked and the database size is
38615**    unknown. The database may not be read or written.
38616**
38617**    * No read or write transaction is active.
38618**    * Any lock, or no lock at all, may be held on the database file.
38619**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
38620**
38621**  READER:
38622**
38623**    In this state all the requirements for reading the database in
38624**    rollback (non-WAL) mode are met. Unless the pager is (or recently
38625**    was) in exclusive-locking mode, a user-level read transaction is
38626**    open. The database size is known in this state.
38627**
38628**    A connection running with locking_mode=normal enters this state when
38629**    it opens a read-transaction on the database and returns to state
38630**    OPEN after the read-transaction is completed. However a connection
38631**    running in locking_mode=exclusive (including temp databases) remains in
38632**    this state even after the read-transaction is closed. The only way
38633**    a locking_mode=exclusive connection can transition from READER to OPEN
38634**    is via the ERROR state (see below).
38635**
38636**    * A read transaction may be active (but a write-transaction cannot).
38637**    * A SHARED or greater lock is held on the database file.
38638**    * The dbSize variable may be trusted (even if a user-level read
38639**      transaction is not active). The dbOrigSize and dbFileSize variables
38640**      may not be trusted at this point.
38641**    * If the database is a WAL database, then the WAL connection is open.
38642**    * Even if a read-transaction is not open, it is guaranteed that
38643**      there is no hot-journal in the file-system.
38644**
38645**  WRITER_LOCKED:
38646**
38647**    The pager moves to this state from READER when a write-transaction
38648**    is first opened on the database. In WRITER_LOCKED state, all locks
38649**    required to start a write-transaction are held, but no actual
38650**    modifications to the cache or database have taken place.
38651**
38652**    In rollback mode, a RESERVED or (if the transaction was opened with
38653**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
38654**    moving to this state, but the journal file is not written to or opened
38655**    to in this state. If the transaction is committed or rolled back while
38656**    in WRITER_LOCKED state, all that is required is to unlock the database
38657**    file.
38658**
38659**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
38660**    If the connection is running with locking_mode=exclusive, an attempt
38661**    is made to obtain an EXCLUSIVE lock on the database file.
38662**
38663**    * A write transaction is active.
38664**    * If the connection is open in rollback-mode, a RESERVED or greater
38665**      lock is held on the database file.
38666**    * If the connection is open in WAL-mode, a WAL write transaction
38667**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
38668**      called).
38669**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
38670**    * The contents of the pager cache have not been modified.
38671**    * The journal file may or may not be open.
38672**    * Nothing (not even the first header) has been written to the journal.
38673**
38674**  WRITER_CACHEMOD:
38675**
38676**    A pager moves from WRITER_LOCKED state to this state when a page is
38677**    first modified by the upper layer. In rollback mode the journal file
38678**    is opened (if it is not already open) and a header written to the
38679**    start of it. The database file on disk has not been modified.
38680**
38681**    * A write transaction is active.
38682**    * A RESERVED or greater lock is held on the database file.
38683**    * The journal file is open and the first header has been written
38684**      to it, but the header has not been synced to disk.
38685**    * The contents of the page cache have been modified.
38686**
38687**  WRITER_DBMOD:
38688**
38689**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
38690**    when it modifies the contents of the database file. WAL connections
38691**    never enter this state (since they do not modify the database file,
38692**    just the log file).
38693**
38694**    * A write transaction is active.
38695**    * An EXCLUSIVE or greater lock is held on the database file.
38696**    * The journal file is open and the first header has been written
38697**      and synced to disk.
38698**    * The contents of the page cache have been modified (and possibly
38699**      written to disk).
38700**
38701**  WRITER_FINISHED:
38702**
38703**    It is not possible for a WAL connection to enter this state.
38704**
38705**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
38706**    state after the entire transaction has been successfully written into the
38707**    database file. In this state the transaction may be committed simply
38708**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
38709**    not possible to modify the database further. At this point, the upper
38710**    layer must either commit or rollback the transaction.
38711**
38712**    * A write transaction is active.
38713**    * An EXCLUSIVE or greater lock is held on the database file.
38714**    * All writing and syncing of journal and database data has finished.
38715**      If no error occured, all that remains is to finalize the journal to
38716**      commit the transaction. If an error did occur, the caller will need
38717**      to rollback the transaction.
38718**
38719**  ERROR:
38720**
38721**    The ERROR state is entered when an IO or disk-full error (including
38722**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
38723**    difficult to be sure that the in-memory pager state (cache contents,
38724**    db size etc.) are consistent with the contents of the file-system.
38725**
38726**    Temporary pager files may enter the ERROR state, but in-memory pagers
38727**    cannot.
38728**
38729**    For example, if an IO error occurs while performing a rollback,
38730**    the contents of the page-cache may be left in an inconsistent state.
38731**    At this point it would be dangerous to change back to READER state
38732**    (as usually happens after a rollback). Any subsequent readers might
38733**    report database corruption (due to the inconsistent cache), and if
38734**    they upgrade to writers, they may inadvertently corrupt the database
38735**    file. To avoid this hazard, the pager switches into the ERROR state
38736**    instead of READER following such an error.
38737**
38738**    Once it has entered the ERROR state, any attempt to use the pager
38739**    to read or write data returns an error. Eventually, once all
38740**    outstanding transactions have been abandoned, the pager is able to
38741**    transition back to OPEN state, discarding the contents of the
38742**    page-cache and any other in-memory state at the same time. Everything
38743**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
38744**    when a read-transaction is next opened on the pager (transitioning
38745**    the pager into READER state). At that point the system has recovered
38746**    from the error.
38747**
38748**    Specifically, the pager jumps into the ERROR state if:
38749**
38750**      1. An error occurs while attempting a rollback. This happens in
38751**         function sqlite3PagerRollback().
38752**
38753**      2. An error occurs while attempting to finalize a journal file
38754**         following a commit in function sqlite3PagerCommitPhaseTwo().
38755**
38756**      3. An error occurs while attempting to write to the journal or
38757**         database file in function pagerStress() in order to free up
38758**         memory.
38759**
38760**    In other cases, the error is returned to the b-tree layer. The b-tree
38761**    layer then attempts a rollback operation. If the error condition
38762**    persists, the pager enters the ERROR state via condition (1) above.
38763**
38764**    Condition (3) is necessary because it can be triggered by a read-only
38765**    statement executed within a transaction. In this case, if the error
38766**    code were simply returned to the user, the b-tree layer would not
38767**    automatically attempt a rollback, as it assumes that an error in a
38768**    read-only statement cannot leave the pager in an internally inconsistent
38769**    state.
38770**
38771**    * The Pager.errCode variable is set to something other than SQLITE_OK.
38772**    * There are one or more outstanding references to pages (after the
38773**      last reference is dropped the pager should move back to OPEN state).
38774**    * The pager is not an in-memory pager.
38775**
38776**
38777** Notes:
38778**
38779**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
38780**     connection is open in WAL mode. A WAL connection is always in one
38781**     of the first four states.
38782**
38783**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
38784**     state. There are two exceptions: immediately after exclusive-mode has
38785**     been turned on (and before any read or write transactions are
38786**     executed), and when the pager is leaving the "error state".
38787**
38788**   * See also: assert_pager_state().
38789*/
38790#define PAGER_OPEN                  0
38791#define PAGER_READER                1
38792#define PAGER_WRITER_LOCKED         2
38793#define PAGER_WRITER_CACHEMOD       3
38794#define PAGER_WRITER_DBMOD          4
38795#define PAGER_WRITER_FINISHED       5
38796#define PAGER_ERROR                 6
38797
38798/*
38799** The Pager.eLock variable is almost always set to one of the
38800** following locking-states, according to the lock currently held on
38801** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
38802** This variable is kept up to date as locks are taken and released by
38803** the pagerLockDb() and pagerUnlockDb() wrappers.
38804**
38805** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
38806** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
38807** the operation was successful. In these circumstances pagerLockDb() and
38808** pagerUnlockDb() take a conservative approach - eLock is always updated
38809** when unlocking the file, and only updated when locking the file if the
38810** VFS call is successful. This way, the Pager.eLock variable may be set
38811** to a less exclusive (lower) value than the lock that is actually held
38812** at the system level, but it is never set to a more exclusive value.
38813**
38814** This is usually safe. If an xUnlock fails or appears to fail, there may
38815** be a few redundant xLock() calls or a lock may be held for longer than
38816** required, but nothing really goes wrong.
38817**
38818** The exception is when the database file is unlocked as the pager moves
38819** from ERROR to OPEN state. At this point there may be a hot-journal file
38820** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
38821** transition, by the same pager or any other). If the call to xUnlock()
38822** fails at this point and the pager is left holding an EXCLUSIVE lock, this
38823** can confuse the call to xCheckReservedLock() call made later as part
38824** of hot-journal detection.
38825**
38826** xCheckReservedLock() is defined as returning true "if there is a RESERVED
38827** lock held by this process or any others". So xCheckReservedLock may
38828** return true because the caller itself is holding an EXCLUSIVE lock (but
38829** doesn't know it because of a previous error in xUnlock). If this happens
38830** a hot-journal may be mistaken for a journal being created by an active
38831** transaction in another process, causing SQLite to read from the database
38832** without rolling it back.
38833**
38834** To work around this, if a call to xUnlock() fails when unlocking the
38835** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
38836** is only changed back to a real locking state after a successful call
38837** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
38838** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
38839** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
38840** lock on the database file before attempting to roll it back. See function
38841** PagerSharedLock() for more detail.
38842**
38843** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
38844** PAGER_OPEN state.
38845*/
38846#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
38847
38848/*
38849** A macro used for invoking the codec if there is one
38850*/
38851#ifdef SQLITE_HAS_CODEC
38852# define CODEC1(P,D,N,X,E) \
38853    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
38854# define CODEC2(P,D,N,X,E,O) \
38855    if( P->xCodec==0 ){ O=(char*)D; }else \
38856    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
38857#else
38858# define CODEC1(P,D,N,X,E)   /* NO-OP */
38859# define CODEC2(P,D,N,X,E,O) O=(char*)D
38860#endif
38861
38862/*
38863** The maximum allowed sector size. 64KiB. If the xSectorsize() method
38864** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
38865** This could conceivably cause corruption following a power failure on
38866** such a system. This is currently an undocumented limit.
38867*/
38868#define MAX_SECTOR_SIZE 0x10000
38869
38870/*
38871** An instance of the following structure is allocated for each active
38872** savepoint and statement transaction in the system. All such structures
38873** are stored in the Pager.aSavepoint[] array, which is allocated and
38874** resized using sqlite3Realloc().
38875**
38876** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
38877** set to 0. If a journal-header is written into the main journal while
38878** the savepoint is active, then iHdrOffset is set to the byte offset
38879** immediately following the last journal record written into the main
38880** journal before the journal-header. This is required during savepoint
38881** rollback (see pagerPlaybackSavepoint()).
38882*/
38883typedef struct PagerSavepoint PagerSavepoint;
38884struct PagerSavepoint {
38885  i64 iOffset;                 /* Starting offset in main journal */
38886  i64 iHdrOffset;              /* See above */
38887  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
38888  Pgno nOrig;                  /* Original number of pages in file */
38889  Pgno iSubRec;                /* Index of first record in sub-journal */
38890#ifndef SQLITE_OMIT_WAL
38891  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
38892#endif
38893};
38894
38895/*
38896** A open page cache is an instance of struct Pager. A description of
38897** some of the more important member variables follows:
38898**
38899** eState
38900**
38901**   The current 'state' of the pager object. See the comment and state
38902**   diagram above for a description of the pager state.
38903**
38904** eLock
38905**
38906**   For a real on-disk database, the current lock held on the database file -
38907**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
38908**
38909**   For a temporary or in-memory database (neither of which require any
38910**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
38911**   databases always have Pager.exclusiveMode==1, this tricks the pager
38912**   logic into thinking that it already has all the locks it will ever
38913**   need (and no reason to release them).
38914**
38915**   In some (obscure) circumstances, this variable may also be set to
38916**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
38917**   details.
38918**
38919** changeCountDone
38920**
38921**   This boolean variable is used to make sure that the change-counter
38922**   (the 4-byte header field at byte offset 24 of the database file) is
38923**   not updated more often than necessary.
38924**
38925**   It is set to true when the change-counter field is updated, which
38926**   can only happen if an exclusive lock is held on the database file.
38927**   It is cleared (set to false) whenever an exclusive lock is
38928**   relinquished on the database file. Each time a transaction is committed,
38929**   The changeCountDone flag is inspected. If it is true, the work of
38930**   updating the change-counter is omitted for the current transaction.
38931**
38932**   This mechanism means that when running in exclusive mode, a connection
38933**   need only update the change-counter once, for the first transaction
38934**   committed.
38935**
38936** setMaster
38937**
38938**   When PagerCommitPhaseOne() is called to commit a transaction, it may
38939**   (or may not) specify a master-journal name to be written into the
38940**   journal file before it is synced to disk.
38941**
38942**   Whether or not a journal file contains a master-journal pointer affects
38943**   the way in which the journal file is finalized after the transaction is
38944**   committed or rolled back when running in "journal_mode=PERSIST" mode.
38945**   If a journal file does not contain a master-journal pointer, it is
38946**   finalized by overwriting the first journal header with zeroes. If
38947**   it does contain a master-journal pointer the journal file is finalized
38948**   by truncating it to zero bytes, just as if the connection were
38949**   running in "journal_mode=truncate" mode.
38950**
38951**   Journal files that contain master journal pointers cannot be finalized
38952**   simply by overwriting the first journal-header with zeroes, as the
38953**   master journal pointer could interfere with hot-journal rollback of any
38954**   subsequently interrupted transaction that reuses the journal file.
38955**
38956**   The flag is cleared as soon as the journal file is finalized (either
38957**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
38958**   journal file from being successfully finalized, the setMaster flag
38959**   is cleared anyway (and the pager will move to ERROR state).
38960**
38961** doNotSpill, doNotSyncSpill
38962**
38963**   These two boolean variables control the behaviour of cache-spills
38964**   (calls made by the pcache module to the pagerStress() routine to
38965**   write cached data to the file-system in order to free up memory).
38966**
38967**   When doNotSpill is non-zero, writing to the database from pagerStress()
38968**   is disabled altogether. This is done in a very obscure case that
38969**   comes up during savepoint rollback that requires the pcache module
38970**   to allocate a new page to prevent the journal file from being written
38971**   while it is being traversed by code in pager_playback().
38972**
38973**   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
38974**   is permitted, but syncing the journal file is not. This flag is set
38975**   by sqlite3PagerWrite() when the file-system sector-size is larger than
38976**   the database page-size in order to prevent a journal sync from happening
38977**   in between the journalling of two pages on the same sector.
38978**
38979** subjInMemory
38980**
38981**   This is a boolean variable. If true, then any required sub-journal
38982**   is opened as an in-memory journal file. If false, then in-memory
38983**   sub-journals are only used for in-memory pager files.
38984**
38985**   This variable is updated by the upper layer each time a new
38986**   write-transaction is opened.
38987**
38988** dbSize, dbOrigSize, dbFileSize
38989**
38990**   Variable dbSize is set to the number of pages in the database file.
38991**   It is valid in PAGER_READER and higher states (all states except for
38992**   OPEN and ERROR).
38993**
38994**   dbSize is set based on the size of the database file, which may be
38995**   larger than the size of the database (the value stored at offset
38996**   28 of the database header by the btree). If the size of the file
38997**   is not an integer multiple of the page-size, the value stored in
38998**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
38999**   Except, any file that is greater than 0 bytes in size is considered
39000**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
39001**   to dbSize==1).
39002**
39003**   During a write-transaction, if pages with page-numbers greater than
39004**   dbSize are modified in the cache, dbSize is updated accordingly.
39005**   Similarly, if the database is truncated using PagerTruncateImage(),
39006**   dbSize is updated.
39007**
39008**   Variables dbOrigSize and dbFileSize are valid in states
39009**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
39010**   variable at the start of the transaction. It is used during rollback,
39011**   and to determine whether or not pages need to be journalled before
39012**   being modified.
39013**
39014**   Throughout a write-transaction, dbFileSize contains the size of
39015**   the file on disk in pages. It is set to a copy of dbSize when the
39016**   write-transaction is first opened, and updated when VFS calls are made
39017**   to write or truncate the database file on disk.
39018**
39019**   The only reason the dbFileSize variable is required is to suppress
39020**   unnecessary calls to xTruncate() after committing a transaction. If,
39021**   when a transaction is committed, the dbFileSize variable indicates
39022**   that the database file is larger than the database image (Pager.dbSize),
39023**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
39024**   to measure the database file on disk, and then truncates it if required.
39025**   dbFileSize is not used when rolling back a transaction. In this case
39026**   pager_truncate() is called unconditionally (which means there may be
39027**   a call to xFilesize() that is not strictly required). In either case,
39028**   pager_truncate() may cause the file to become smaller or larger.
39029**
39030** dbHintSize
39031**
39032**   The dbHintSize variable is used to limit the number of calls made to
39033**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
39034**
39035**   dbHintSize is set to a copy of the dbSize variable when a
39036**   write-transaction is opened (at the same time as dbFileSize and
39037**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
39038**   dbHintSize is increased to the number of pages that correspond to the
39039**   size-hint passed to the method call. See pager_write_pagelist() for
39040**   details.
39041**
39042** errCode
39043**
39044**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
39045**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
39046**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
39047**   sub-codes.
39048*/
39049struct Pager {
39050  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
39051  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
39052  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
39053  u8 useJournal;              /* Use a rollback journal on this file */
39054  u8 noSync;                  /* Do not sync the journal if true */
39055  u8 fullSync;                /* Do extra syncs of the journal for robustness */
39056  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
39057  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
39058  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
39059  u8 tempFile;                /* zFilename is a temporary file */
39060  u8 readOnly;                /* True for a read-only database */
39061  u8 memDb;                   /* True to inhibit all file I/O */
39062
39063  /**************************************************************************
39064  ** The following block contains those class members that change during
39065  ** routine opertion.  Class members not in this block are either fixed
39066  ** when the pager is first created or else only change when there is a
39067  ** significant mode change (such as changing the page_size, locking_mode,
39068  ** or the journal_mode).  From another view, these class members describe
39069  ** the "state" of the pager, while other class members describe the
39070  ** "configuration" of the pager.
39071  */
39072  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
39073  u8 eLock;                   /* Current lock held on database file */
39074  u8 changeCountDone;         /* Set after incrementing the change-counter */
39075  u8 setMaster;               /* True if a m-j name has been written to jrnl */
39076  u8 doNotSpill;              /* Do not spill the cache when non-zero */
39077  u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
39078  u8 subjInMemory;            /* True to use in-memory sub-journals */
39079  Pgno dbSize;                /* Number of pages in the database */
39080  Pgno dbOrigSize;            /* dbSize before the current transaction */
39081  Pgno dbFileSize;            /* Number of pages in the database file */
39082  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
39083  int errCode;                /* One of several kinds of errors */
39084  int nRec;                   /* Pages journalled since last j-header written */
39085  u32 cksumInit;              /* Quasi-random value added to every checksum */
39086  u32 nSubRec;                /* Number of records written to sub-journal */
39087  Bitvec *pInJournal;         /* One bit for each page in the database file */
39088  sqlite3_file *fd;           /* File descriptor for database */
39089  sqlite3_file *jfd;          /* File descriptor for main journal */
39090  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
39091  i64 journalOff;             /* Current write offset in the journal file */
39092  i64 journalHdr;             /* Byte offset to previous journal header */
39093  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
39094  PagerSavepoint *aSavepoint; /* Array of active savepoints */
39095  int nSavepoint;             /* Number of elements in aSavepoint[] */
39096  char dbFileVers[16];        /* Changes whenever database file changes */
39097  /*
39098  ** End of the routinely-changing class members
39099  ***************************************************************************/
39100
39101  u16 nExtra;                 /* Add this many bytes to each in-memory page */
39102  i16 nReserve;               /* Number of unused bytes at end of each page */
39103  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
39104  u32 sectorSize;             /* Assumed sector size during rollback */
39105  int pageSize;               /* Number of bytes in a page */
39106  Pgno mxPgno;                /* Maximum allowed size of the database */
39107  i64 journalSizeLimit;       /* Size limit for persistent journal files */
39108  char *zFilename;            /* Name of the database file */
39109  char *zJournal;             /* Name of the journal file */
39110  int (*xBusyHandler)(void*); /* Function to call when busy */
39111  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
39112  int nHit, nMiss;            /* Total cache hits and misses */
39113#ifdef SQLITE_TEST
39114  int nRead, nWrite;          /* Database pages read/written */
39115#endif
39116  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
39117#ifdef SQLITE_HAS_CODEC
39118  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
39119  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
39120  void (*xCodecFree)(void*);             /* Destructor for the codec */
39121  void *pCodec;               /* First argument to xCodec... methods */
39122#endif
39123  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
39124  PCache *pPCache;            /* Pointer to page cache object */
39125#ifndef SQLITE_OMIT_WAL
39126  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
39127  char *zWal;                 /* File name for write-ahead log */
39128#endif
39129};
39130
39131/*
39132** The following global variables hold counters used for
39133** testing purposes only.  These variables do not exist in
39134** a non-testing build.  These variables are not thread-safe.
39135*/
39136#ifdef SQLITE_TEST
39137SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
39138SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
39139SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
39140# define PAGER_INCR(v)  v++
39141#else
39142# define PAGER_INCR(v)
39143#endif
39144
39145
39146
39147/*
39148** Journal files begin with the following magic string.  The data
39149** was obtained from /dev/random.  It is used only as a sanity check.
39150**
39151** Since version 2.8.0, the journal format contains additional sanity
39152** checking information.  If the power fails while the journal is being
39153** written, semi-random garbage data might appear in the journal
39154** file after power is restored.  If an attempt is then made
39155** to roll the journal back, the database could be corrupted.  The additional
39156** sanity checking data is an attempt to discover the garbage in the
39157** journal and ignore it.
39158**
39159** The sanity checking information for the new journal format consists
39160** of a 32-bit checksum on each page of data.  The checksum covers both
39161** the page number and the pPager->pageSize bytes of data for the page.
39162** This cksum is initialized to a 32-bit random value that appears in the
39163** journal file right after the header.  The random initializer is important,
39164** because garbage data that appears at the end of a journal is likely
39165** data that was once in other files that have now been deleted.  If the
39166** garbage data came from an obsolete journal file, the checksums might
39167** be correct.  But by initializing the checksum to random value which
39168** is different for every journal, we minimize that risk.
39169*/
39170static const unsigned char aJournalMagic[] = {
39171  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
39172};
39173
39174/*
39175** The size of the of each page record in the journal is given by
39176** the following macro.
39177*/
39178#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
39179
39180/*
39181** The journal header size for this pager. This is usually the same
39182** size as a single disk sector. See also setSectorSize().
39183*/
39184#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
39185
39186/*
39187** The macro MEMDB is true if we are dealing with an in-memory database.
39188** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
39189** the value of MEMDB will be a constant and the compiler will optimize
39190** out code that would never execute.
39191*/
39192#ifdef SQLITE_OMIT_MEMORYDB
39193# define MEMDB 0
39194#else
39195# define MEMDB pPager->memDb
39196#endif
39197
39198/*
39199** The maximum legal page number is (2^31 - 1).
39200*/
39201#define PAGER_MAX_PGNO 2147483647
39202
39203/*
39204** The argument to this macro is a file descriptor (type sqlite3_file*).
39205** Return 0 if it is not open, or non-zero (but not 1) if it is.
39206**
39207** This is so that expressions can be written as:
39208**
39209**   if( isOpen(pPager->jfd) ){ ...
39210**
39211** instead of
39212**
39213**   if( pPager->jfd->pMethods ){ ...
39214*/
39215#define isOpen(pFd) ((pFd)->pMethods)
39216
39217/*
39218** Return true if this pager uses a write-ahead log instead of the usual
39219** rollback journal. Otherwise false.
39220*/
39221#ifndef SQLITE_OMIT_WAL
39222static int pagerUseWal(Pager *pPager){
39223  return (pPager->pWal!=0);
39224}
39225#else
39226# define pagerUseWal(x) 0
39227# define pagerRollbackWal(x) 0
39228# define pagerWalFrames(v,w,x,y) 0
39229# define pagerOpenWalIfPresent(z) SQLITE_OK
39230# define pagerBeginReadTransaction(z) SQLITE_OK
39231#endif
39232
39233#ifndef NDEBUG
39234/*
39235** Usage:
39236**
39237**   assert( assert_pager_state(pPager) );
39238**
39239** This function runs many asserts to try to find inconsistencies in
39240** the internal state of the Pager object.
39241*/
39242static int assert_pager_state(Pager *p){
39243  Pager *pPager = p;
39244
39245  /* State must be valid. */
39246  assert( p->eState==PAGER_OPEN
39247       || p->eState==PAGER_READER
39248       || p->eState==PAGER_WRITER_LOCKED
39249       || p->eState==PAGER_WRITER_CACHEMOD
39250       || p->eState==PAGER_WRITER_DBMOD
39251       || p->eState==PAGER_WRITER_FINISHED
39252       || p->eState==PAGER_ERROR
39253  );
39254
39255  /* Regardless of the current state, a temp-file connection always behaves
39256  ** as if it has an exclusive lock on the database file. It never updates
39257  ** the change-counter field, so the changeCountDone flag is always set.
39258  */
39259  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
39260  assert( p->tempFile==0 || pPager->changeCountDone );
39261
39262  /* If the useJournal flag is clear, the journal-mode must be "OFF".
39263  ** And if the journal-mode is "OFF", the journal file must not be open.
39264  */
39265  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
39266  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
39267
39268  /* Check that MEMDB implies noSync. And an in-memory journal. Since
39269  ** this means an in-memory pager performs no IO at all, it cannot encounter
39270  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
39271  ** a journal file. (although the in-memory journal implementation may
39272  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
39273  ** is therefore not possible for an in-memory pager to enter the ERROR
39274  ** state.
39275  */
39276  if( MEMDB ){
39277    assert( p->noSync );
39278    assert( p->journalMode==PAGER_JOURNALMODE_OFF
39279         || p->journalMode==PAGER_JOURNALMODE_MEMORY
39280    );
39281    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
39282    assert( pagerUseWal(p)==0 );
39283  }
39284
39285  /* If changeCountDone is set, a RESERVED lock or greater must be held
39286  ** on the file.
39287  */
39288  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
39289  assert( p->eLock!=PENDING_LOCK );
39290
39291  switch( p->eState ){
39292    case PAGER_OPEN:
39293      assert( !MEMDB );
39294      assert( pPager->errCode==SQLITE_OK );
39295      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
39296      break;
39297
39298    case PAGER_READER:
39299      assert( pPager->errCode==SQLITE_OK );
39300      assert( p->eLock!=UNKNOWN_LOCK );
39301      assert( p->eLock>=SHARED_LOCK );
39302      break;
39303
39304    case PAGER_WRITER_LOCKED:
39305      assert( p->eLock!=UNKNOWN_LOCK );
39306      assert( pPager->errCode==SQLITE_OK );
39307      if( !pagerUseWal(pPager) ){
39308        assert( p->eLock>=RESERVED_LOCK );
39309      }
39310      assert( pPager->dbSize==pPager->dbOrigSize );
39311      assert( pPager->dbOrigSize==pPager->dbFileSize );
39312      assert( pPager->dbOrigSize==pPager->dbHintSize );
39313      assert( pPager->setMaster==0 );
39314      break;
39315
39316    case PAGER_WRITER_CACHEMOD:
39317      assert( p->eLock!=UNKNOWN_LOCK );
39318      assert( pPager->errCode==SQLITE_OK );
39319      if( !pagerUseWal(pPager) ){
39320        /* It is possible that if journal_mode=wal here that neither the
39321        ** journal file nor the WAL file are open. This happens during
39322        ** a rollback transaction that switches from journal_mode=off
39323        ** to journal_mode=wal.
39324        */
39325        assert( p->eLock>=RESERVED_LOCK );
39326        assert( isOpen(p->jfd)
39327             || p->journalMode==PAGER_JOURNALMODE_OFF
39328             || p->journalMode==PAGER_JOURNALMODE_WAL
39329        );
39330      }
39331      assert( pPager->dbOrigSize==pPager->dbFileSize );
39332      assert( pPager->dbOrigSize==pPager->dbHintSize );
39333      break;
39334
39335    case PAGER_WRITER_DBMOD:
39336      assert( p->eLock==EXCLUSIVE_LOCK );
39337      assert( pPager->errCode==SQLITE_OK );
39338      assert( !pagerUseWal(pPager) );
39339      assert( p->eLock>=EXCLUSIVE_LOCK );
39340      assert( isOpen(p->jfd)
39341           || p->journalMode==PAGER_JOURNALMODE_OFF
39342           || p->journalMode==PAGER_JOURNALMODE_WAL
39343      );
39344      assert( pPager->dbOrigSize<=pPager->dbHintSize );
39345      break;
39346
39347    case PAGER_WRITER_FINISHED:
39348      assert( p->eLock==EXCLUSIVE_LOCK );
39349      assert( pPager->errCode==SQLITE_OK );
39350      assert( !pagerUseWal(pPager) );
39351      assert( isOpen(p->jfd)
39352           || p->journalMode==PAGER_JOURNALMODE_OFF
39353           || p->journalMode==PAGER_JOURNALMODE_WAL
39354      );
39355      break;
39356
39357    case PAGER_ERROR:
39358      /* There must be at least one outstanding reference to the pager if
39359      ** in ERROR state. Otherwise the pager should have already dropped
39360      ** back to OPEN state.
39361      */
39362      assert( pPager->errCode!=SQLITE_OK );
39363      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
39364      break;
39365  }
39366
39367  return 1;
39368}
39369#endif /* ifndef NDEBUG */
39370
39371#ifdef SQLITE_DEBUG
39372/*
39373** Return a pointer to a human readable string in a static buffer
39374** containing the state of the Pager object passed as an argument. This
39375** is intended to be used within debuggers. For example, as an alternative
39376** to "print *pPager" in gdb:
39377**
39378** (gdb) printf "%s", print_pager_state(pPager)
39379*/
39380static char *print_pager_state(Pager *p){
39381  static char zRet[1024];
39382
39383  sqlite3_snprintf(1024, zRet,
39384      "Filename:      %s\n"
39385      "State:         %s errCode=%d\n"
39386      "Lock:          %s\n"
39387      "Locking mode:  locking_mode=%s\n"
39388      "Journal mode:  journal_mode=%s\n"
39389      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
39390      "Journal:       journalOff=%lld journalHdr=%lld\n"
39391      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
39392      , p->zFilename
39393      , p->eState==PAGER_OPEN            ? "OPEN" :
39394        p->eState==PAGER_READER          ? "READER" :
39395        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
39396        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
39397        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
39398        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
39399        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
39400      , (int)p->errCode
39401      , p->eLock==NO_LOCK         ? "NO_LOCK" :
39402        p->eLock==RESERVED_LOCK   ? "RESERVED" :
39403        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
39404        p->eLock==SHARED_LOCK     ? "SHARED" :
39405        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
39406      , p->exclusiveMode ? "exclusive" : "normal"
39407      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
39408        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
39409        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
39410        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
39411        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
39412        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
39413      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
39414      , p->journalOff, p->journalHdr
39415      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
39416  );
39417
39418  return zRet;
39419}
39420#endif
39421
39422/*
39423** Return true if it is necessary to write page *pPg into the sub-journal.
39424** A page needs to be written into the sub-journal if there exists one
39425** or more open savepoints for which:
39426**
39427**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
39428**   * The bit corresponding to the page-number is not set in
39429**     PagerSavepoint.pInSavepoint.
39430*/
39431static int subjRequiresPage(PgHdr *pPg){
39432  Pgno pgno = pPg->pgno;
39433  Pager *pPager = pPg->pPager;
39434  int i;
39435  for(i=0; i<pPager->nSavepoint; i++){
39436    PagerSavepoint *p = &pPager->aSavepoint[i];
39437    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
39438      return 1;
39439    }
39440  }
39441  return 0;
39442}
39443
39444/*
39445** Return true if the page is already in the journal file.
39446*/
39447static int pageInJournal(PgHdr *pPg){
39448  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
39449}
39450
39451/*
39452** Read a 32-bit integer from the given file descriptor.  Store the integer
39453** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
39454** error code is something goes wrong.
39455**
39456** All values are stored on disk as big-endian.
39457*/
39458static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
39459  unsigned char ac[4];
39460  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
39461  if( rc==SQLITE_OK ){
39462    *pRes = sqlite3Get4byte(ac);
39463  }
39464  return rc;
39465}
39466
39467/*
39468** Write a 32-bit integer into a string buffer in big-endian byte order.
39469*/
39470#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
39471
39472
39473/*
39474** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
39475** on success or an error code is something goes wrong.
39476*/
39477static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
39478  char ac[4];
39479  put32bits(ac, val);
39480  return sqlite3OsWrite(fd, ac, 4, offset);
39481}
39482
39483/*
39484** Unlock the database file to level eLock, which must be either NO_LOCK
39485** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
39486** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
39487**
39488** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
39489** called, do not modify it. See the comment above the #define of
39490** UNKNOWN_LOCK for an explanation of this.
39491*/
39492static int pagerUnlockDb(Pager *pPager, int eLock){
39493  int rc = SQLITE_OK;
39494
39495  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
39496  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
39497  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
39498  if( isOpen(pPager->fd) ){
39499    assert( pPager->eLock>=eLock );
39500    rc = sqlite3OsUnlock(pPager->fd, eLock);
39501    if( pPager->eLock!=UNKNOWN_LOCK ){
39502      pPager->eLock = (u8)eLock;
39503    }
39504    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
39505  }
39506  return rc;
39507}
39508
39509/*
39510** Lock the database file to level eLock, which must be either SHARED_LOCK,
39511** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
39512** Pager.eLock variable to the new locking state.
39513**
39514** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
39515** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
39516** See the comment above the #define of UNKNOWN_LOCK for an explanation
39517** of this.
39518*/
39519static int pagerLockDb(Pager *pPager, int eLock){
39520  int rc = SQLITE_OK;
39521
39522  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
39523  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
39524    rc = sqlite3OsLock(pPager->fd, eLock);
39525    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
39526      pPager->eLock = (u8)eLock;
39527      IOTRACE(("LOCK %p %d\n", pPager, eLock))
39528    }
39529  }
39530  return rc;
39531}
39532
39533/*
39534** This function determines whether or not the atomic-write optimization
39535** can be used with this pager. The optimization can be used if:
39536**
39537**  (a) the value returned by OsDeviceCharacteristics() indicates that
39538**      a database page may be written atomically, and
39539**  (b) the value returned by OsSectorSize() is less than or equal
39540**      to the page size.
39541**
39542** The optimization is also always enabled for temporary files. It is
39543** an error to call this function if pPager is opened on an in-memory
39544** database.
39545**
39546** If the optimization cannot be used, 0 is returned. If it can be used,
39547** then the value returned is the size of the journal file when it
39548** contains rollback data for exactly one page.
39549*/
39550#ifdef SQLITE_ENABLE_ATOMIC_WRITE
39551static int jrnlBufferSize(Pager *pPager){
39552  assert( !MEMDB );
39553  if( !pPager->tempFile ){
39554    int dc;                           /* Device characteristics */
39555    int nSector;                      /* Sector size */
39556    int szPage;                       /* Page size */
39557
39558    assert( isOpen(pPager->fd) );
39559    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
39560    nSector = pPager->sectorSize;
39561    szPage = pPager->pageSize;
39562
39563    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
39564    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
39565    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
39566      return 0;
39567    }
39568  }
39569
39570  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
39571}
39572#endif
39573
39574/*
39575** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
39576** on the cache using a hash function.  This is used for testing
39577** and debugging only.
39578*/
39579#ifdef SQLITE_CHECK_PAGES
39580/*
39581** Return a 32-bit hash of the page data for pPage.
39582*/
39583static u32 pager_datahash(int nByte, unsigned char *pData){
39584  u32 hash = 0;
39585  int i;
39586  for(i=0; i<nByte; i++){
39587    hash = (hash*1039) + pData[i];
39588  }
39589  return hash;
39590}
39591static u32 pager_pagehash(PgHdr *pPage){
39592  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
39593}
39594static void pager_set_pagehash(PgHdr *pPage){
39595  pPage->pageHash = pager_pagehash(pPage);
39596}
39597
39598/*
39599** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
39600** is defined, and NDEBUG is not defined, an assert() statement checks
39601** that the page is either dirty or still matches the calculated page-hash.
39602*/
39603#define CHECK_PAGE(x) checkPage(x)
39604static void checkPage(PgHdr *pPg){
39605  Pager *pPager = pPg->pPager;
39606  assert( pPager->eState!=PAGER_ERROR );
39607  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
39608}
39609
39610#else
39611#define pager_datahash(X,Y)  0
39612#define pager_pagehash(X)  0
39613#define pager_set_pagehash(X)
39614#define CHECK_PAGE(x)
39615#endif  /* SQLITE_CHECK_PAGES */
39616
39617/*
39618** When this is called the journal file for pager pPager must be open.
39619** This function attempts to read a master journal file name from the
39620** end of the file and, if successful, copies it into memory supplied
39621** by the caller. See comments above writeMasterJournal() for the format
39622** used to store a master journal file name at the end of a journal file.
39623**
39624** zMaster must point to a buffer of at least nMaster bytes allocated by
39625** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
39626** enough space to write the master journal name). If the master journal
39627** name in the journal is longer than nMaster bytes (including a
39628** nul-terminator), then this is handled as if no master journal name
39629** were present in the journal.
39630**
39631** If a master journal file name is present at the end of the journal
39632** file, then it is copied into the buffer pointed to by zMaster. A
39633** nul-terminator byte is appended to the buffer following the master
39634** journal file name.
39635**
39636** If it is determined that no master journal file name is present
39637** zMaster[0] is set to 0 and SQLITE_OK returned.
39638**
39639** If an error occurs while reading from the journal file, an SQLite
39640** error code is returned.
39641*/
39642static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
39643  int rc;                    /* Return code */
39644  u32 len;                   /* Length in bytes of master journal name */
39645  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
39646  u32 cksum;                 /* MJ checksum value read from journal */
39647  u32 u;                     /* Unsigned loop counter */
39648  unsigned char aMagic[8];   /* A buffer to hold the magic header */
39649  zMaster[0] = '\0';
39650
39651  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
39652   || szJ<16
39653   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
39654   || len>=nMaster
39655   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
39656   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
39657   || memcmp(aMagic, aJournalMagic, 8)
39658   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
39659  ){
39660    return rc;
39661  }
39662
39663  /* See if the checksum matches the master journal name */
39664  for(u=0; u<len; u++){
39665    cksum -= zMaster[u];
39666  }
39667  if( cksum ){
39668    /* If the checksum doesn't add up, then one or more of the disk sectors
39669    ** containing the master journal filename is corrupted. This means
39670    ** definitely roll back, so just return SQLITE_OK and report a (nul)
39671    ** master-journal filename.
39672    */
39673    len = 0;
39674  }
39675  zMaster[len] = '\0';
39676
39677  return SQLITE_OK;
39678}
39679
39680/*
39681** Return the offset of the sector boundary at or immediately
39682** following the value in pPager->journalOff, assuming a sector
39683** size of pPager->sectorSize bytes.
39684**
39685** i.e for a sector size of 512:
39686**
39687**   Pager.journalOff          Return value
39688**   ---------------------------------------
39689**   0                         0
39690**   512                       512
39691**   100                       512
39692**   2000                      2048
39693**
39694*/
39695static i64 journalHdrOffset(Pager *pPager){
39696  i64 offset = 0;
39697  i64 c = pPager->journalOff;
39698  if( c ){
39699    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
39700  }
39701  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
39702  assert( offset>=c );
39703  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
39704  return offset;
39705}
39706
39707/*
39708** The journal file must be open when this function is called.
39709**
39710** This function is a no-op if the journal file has not been written to
39711** within the current transaction (i.e. if Pager.journalOff==0).
39712**
39713** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
39714** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
39715** zero the 28-byte header at the start of the journal file. In either case,
39716** if the pager is not in no-sync mode, sync the journal file immediately
39717** after writing or truncating it.
39718**
39719** If Pager.journalSizeLimit is set to a positive, non-zero value, and
39720** following the truncation or zeroing described above the size of the
39721** journal file in bytes is larger than this value, then truncate the
39722** journal file to Pager.journalSizeLimit bytes. The journal file does
39723** not need to be synced following this operation.
39724**
39725** If an IO error occurs, abandon processing and return the IO error code.
39726** Otherwise, return SQLITE_OK.
39727*/
39728static int zeroJournalHdr(Pager *pPager, int doTruncate){
39729  int rc = SQLITE_OK;                               /* Return code */
39730  assert( isOpen(pPager->jfd) );
39731  if( pPager->journalOff ){
39732    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
39733
39734    IOTRACE(("JZEROHDR %p\n", pPager))
39735    if( doTruncate || iLimit==0 ){
39736      rc = sqlite3OsTruncate(pPager->jfd, 0);
39737    }else{
39738      static const char zeroHdr[28] = {0};
39739      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
39740    }
39741    if( rc==SQLITE_OK && !pPager->noSync ){
39742      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
39743    }
39744
39745    /* At this point the transaction is committed but the write lock
39746    ** is still held on the file. If there is a size limit configured for
39747    ** the persistent journal and the journal file currently consumes more
39748    ** space than that limit allows for, truncate it now. There is no need
39749    ** to sync the file following this operation.
39750    */
39751    if( rc==SQLITE_OK && iLimit>0 ){
39752      i64 sz;
39753      rc = sqlite3OsFileSize(pPager->jfd, &sz);
39754      if( rc==SQLITE_OK && sz>iLimit ){
39755        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
39756      }
39757    }
39758  }
39759  return rc;
39760}
39761
39762/*
39763** The journal file must be open when this routine is called. A journal
39764** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
39765** current location.
39766**
39767** The format for the journal header is as follows:
39768** - 8 bytes: Magic identifying journal format.
39769** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
39770** - 4 bytes: Random number used for page hash.
39771** - 4 bytes: Initial database page count.
39772** - 4 bytes: Sector size used by the process that wrote this journal.
39773** - 4 bytes: Database page size.
39774**
39775** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
39776*/
39777static int writeJournalHdr(Pager *pPager){
39778  int rc = SQLITE_OK;                 /* Return code */
39779  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
39780  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
39781  u32 nWrite;                         /* Bytes of header sector written */
39782  int ii;                             /* Loop counter */
39783
39784  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
39785
39786  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
39787    nHeader = JOURNAL_HDR_SZ(pPager);
39788  }
39789
39790  /* If there are active savepoints and any of them were created
39791  ** since the most recent journal header was written, update the
39792  ** PagerSavepoint.iHdrOffset fields now.
39793  */
39794  for(ii=0; ii<pPager->nSavepoint; ii++){
39795    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
39796      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
39797    }
39798  }
39799
39800  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
39801
39802  /*
39803  ** Write the nRec Field - the number of page records that follow this
39804  ** journal header. Normally, zero is written to this value at this time.
39805  ** After the records are added to the journal (and the journal synced,
39806  ** if in full-sync mode), the zero is overwritten with the true number
39807  ** of records (see syncJournal()).
39808  **
39809  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
39810  ** reading the journal this value tells SQLite to assume that the
39811  ** rest of the journal file contains valid page records. This assumption
39812  ** is dangerous, as if a failure occurred whilst writing to the journal
39813  ** file it may contain some garbage data. There are two scenarios
39814  ** where this risk can be ignored:
39815  **
39816  **   * When the pager is in no-sync mode. Corruption can follow a
39817  **     power failure in this case anyway.
39818  **
39819  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
39820  **     that garbage data is never appended to the journal file.
39821  */
39822  assert( isOpen(pPager->fd) || pPager->noSync );
39823  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
39824   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
39825  ){
39826    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
39827    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
39828  }else{
39829    memset(zHeader, 0, sizeof(aJournalMagic)+4);
39830  }
39831
39832  /* The random check-hash initialiser */
39833  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
39834  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
39835  /* The initial database size */
39836  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
39837  /* The assumed sector size for this process */
39838  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
39839
39840  /* The page size */
39841  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
39842
39843  /* Initializing the tail of the buffer is not necessary.  Everything
39844  ** works find if the following memset() is omitted.  But initializing
39845  ** the memory prevents valgrind from complaining, so we are willing to
39846  ** take the performance hit.
39847  */
39848  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
39849         nHeader-(sizeof(aJournalMagic)+20));
39850
39851  /* In theory, it is only necessary to write the 28 bytes that the
39852  ** journal header consumes to the journal file here. Then increment the
39853  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
39854  ** record is written to the following sector (leaving a gap in the file
39855  ** that will be implicitly filled in by the OS).
39856  **
39857  ** However it has been discovered that on some systems this pattern can
39858  ** be significantly slower than contiguously writing data to the file,
39859  ** even if that means explicitly writing data to the block of
39860  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
39861  ** is done.
39862  **
39863  ** The loop is required here in case the sector-size is larger than the
39864  ** database page size. Since the zHeader buffer is only Pager.pageSize
39865  ** bytes in size, more than one call to sqlite3OsWrite() may be required
39866  ** to populate the entire journal header sector.
39867  */
39868  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
39869    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
39870    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
39871    assert( pPager->journalHdr <= pPager->journalOff );
39872    pPager->journalOff += nHeader;
39873  }
39874
39875  return rc;
39876}
39877
39878/*
39879** The journal file must be open when this is called. A journal header file
39880** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
39881** file. The current location in the journal file is given by
39882** pPager->journalOff. See comments above function writeJournalHdr() for
39883** a description of the journal header format.
39884**
39885** If the header is read successfully, *pNRec is set to the number of
39886** page records following this header and *pDbSize is set to the size of the
39887** database before the transaction began, in pages. Also, pPager->cksumInit
39888** is set to the value read from the journal header. SQLITE_OK is returned
39889** in this case.
39890**
39891** If the journal header file appears to be corrupted, SQLITE_DONE is
39892** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
39893** cannot be read from the journal file an error code is returned.
39894*/
39895static int readJournalHdr(
39896  Pager *pPager,               /* Pager object */
39897  int isHot,
39898  i64 journalSize,             /* Size of the open journal file in bytes */
39899  u32 *pNRec,                  /* OUT: Value read from the nRec field */
39900  u32 *pDbSize                 /* OUT: Value of original database size field */
39901){
39902  int rc;                      /* Return code */
39903  unsigned char aMagic[8];     /* A buffer to hold the magic header */
39904  i64 iHdrOff;                 /* Offset of journal header being read */
39905
39906  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
39907
39908  /* Advance Pager.journalOff to the start of the next sector. If the
39909  ** journal file is too small for there to be a header stored at this
39910  ** point, return SQLITE_DONE.
39911  */
39912  pPager->journalOff = journalHdrOffset(pPager);
39913  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
39914    return SQLITE_DONE;
39915  }
39916  iHdrOff = pPager->journalOff;
39917
39918  /* Read in the first 8 bytes of the journal header. If they do not match
39919  ** the  magic string found at the start of each journal header, return
39920  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
39921  ** proceed.
39922  */
39923  if( isHot || iHdrOff!=pPager->journalHdr ){
39924    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
39925    if( rc ){
39926      return rc;
39927    }
39928    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
39929      return SQLITE_DONE;
39930    }
39931  }
39932
39933  /* Read the first three 32-bit fields of the journal header: The nRec
39934  ** field, the checksum-initializer and the database size at the start
39935  ** of the transaction. Return an error code if anything goes wrong.
39936  */
39937  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
39938   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
39939   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
39940  ){
39941    return rc;
39942  }
39943
39944  if( pPager->journalOff==0 ){
39945    u32 iPageSize;               /* Page-size field of journal header */
39946    u32 iSectorSize;             /* Sector-size field of journal header */
39947
39948    /* Read the page-size and sector-size journal header fields. */
39949    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
39950     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
39951    ){
39952      return rc;
39953    }
39954
39955    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
39956    ** journal header to zero. In this case, assume that the Pager.pageSize
39957    ** variable is already set to the correct page size.
39958    */
39959    if( iPageSize==0 ){
39960      iPageSize = pPager->pageSize;
39961    }
39962
39963    /* Check that the values read from the page-size and sector-size fields
39964    ** are within range. To be 'in range', both values need to be a power
39965    ** of two greater than or equal to 512 or 32, and not greater than their
39966    ** respective compile time maximum limits.
39967    */
39968    if( iPageSize<512                  || iSectorSize<32
39969     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
39970     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
39971    ){
39972      /* If the either the page-size or sector-size in the journal-header is
39973      ** invalid, then the process that wrote the journal-header must have
39974      ** crashed before the header was synced. In this case stop reading
39975      ** the journal file here.
39976      */
39977      return SQLITE_DONE;
39978    }
39979
39980    /* Update the page-size to match the value read from the journal.
39981    ** Use a testcase() macro to make sure that malloc failure within
39982    ** PagerSetPagesize() is tested.
39983    */
39984    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
39985    testcase( rc!=SQLITE_OK );
39986
39987    /* Update the assumed sector-size to match the value used by
39988    ** the process that created this journal. If this journal was
39989    ** created by a process other than this one, then this routine
39990    ** is being called from within pager_playback(). The local value
39991    ** of Pager.sectorSize is restored at the end of that routine.
39992    */
39993    pPager->sectorSize = iSectorSize;
39994  }
39995
39996  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
39997  return rc;
39998}
39999
40000
40001/*
40002** Write the supplied master journal name into the journal file for pager
40003** pPager at the current location. The master journal name must be the last
40004** thing written to a journal file. If the pager is in full-sync mode, the
40005** journal file descriptor is advanced to the next sector boundary before
40006** anything is written. The format is:
40007**
40008**   + 4 bytes: PAGER_MJ_PGNO.
40009**   + N bytes: Master journal filename in utf-8.
40010**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
40011**   + 4 bytes: Master journal name checksum.
40012**   + 8 bytes: aJournalMagic[].
40013**
40014** The master journal page checksum is the sum of the bytes in the master
40015** journal name, where each byte is interpreted as a signed 8-bit integer.
40016**
40017** If zMaster is a NULL pointer (occurs for a single database transaction),
40018** this call is a no-op.
40019*/
40020static int writeMasterJournal(Pager *pPager, const char *zMaster){
40021  int rc;                          /* Return code */
40022  int nMaster;                     /* Length of string zMaster */
40023  i64 iHdrOff;                     /* Offset of header in journal file */
40024  i64 jrnlSize;                    /* Size of journal file on disk */
40025  u32 cksum = 0;                   /* Checksum of string zMaster */
40026
40027  assert( pPager->setMaster==0 );
40028  assert( !pagerUseWal(pPager) );
40029
40030  if( !zMaster
40031   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
40032   || pPager->journalMode==PAGER_JOURNALMODE_OFF
40033  ){
40034    return SQLITE_OK;
40035  }
40036  pPager->setMaster = 1;
40037  assert( isOpen(pPager->jfd) );
40038  assert( pPager->journalHdr <= pPager->journalOff );
40039
40040  /* Calculate the length in bytes and the checksum of zMaster */
40041  for(nMaster=0; zMaster[nMaster]; nMaster++){
40042    cksum += zMaster[nMaster];
40043  }
40044
40045  /* If in full-sync mode, advance to the next disk sector before writing
40046  ** the master journal name. This is in case the previous page written to
40047  ** the journal has already been synced.
40048  */
40049  if( pPager->fullSync ){
40050    pPager->journalOff = journalHdrOffset(pPager);
40051  }
40052  iHdrOff = pPager->journalOff;
40053
40054  /* Write the master journal data to the end of the journal file. If
40055  ** an error occurs, return the error code to the caller.
40056  */
40057  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
40058   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
40059   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
40060   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
40061   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
40062  ){
40063    return rc;
40064  }
40065  pPager->journalOff += (nMaster+20);
40066
40067  /* If the pager is in peristent-journal mode, then the physical
40068  ** journal-file may extend past the end of the master-journal name
40069  ** and 8 bytes of magic data just written to the file. This is
40070  ** dangerous because the code to rollback a hot-journal file
40071  ** will not be able to find the master-journal name to determine
40072  ** whether or not the journal is hot.
40073  **
40074  ** Easiest thing to do in this scenario is to truncate the journal
40075  ** file to the required size.
40076  */
40077  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
40078   && jrnlSize>pPager->journalOff
40079  ){
40080    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
40081  }
40082  return rc;
40083}
40084
40085/*
40086** Find a page in the hash table given its page number. Return
40087** a pointer to the page or NULL if the requested page is not
40088** already in memory.
40089*/
40090static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
40091  PgHdr *p;                         /* Return value */
40092
40093  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
40094  ** fail, since no attempt to allocate dynamic memory will be made.
40095  */
40096  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
40097  return p;
40098}
40099
40100/*
40101** Discard the entire contents of the in-memory page-cache.
40102*/
40103static void pager_reset(Pager *pPager){
40104  sqlite3BackupRestart(pPager->pBackup);
40105  sqlite3PcacheClear(pPager->pPCache);
40106}
40107
40108/*
40109** Free all structures in the Pager.aSavepoint[] array and set both
40110** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
40111** if it is open and the pager is not in exclusive mode.
40112*/
40113static void releaseAllSavepoints(Pager *pPager){
40114  int ii;               /* Iterator for looping through Pager.aSavepoint */
40115  for(ii=0; ii<pPager->nSavepoint; ii++){
40116    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
40117  }
40118  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
40119    sqlite3OsClose(pPager->sjfd);
40120  }
40121  sqlite3_free(pPager->aSavepoint);
40122  pPager->aSavepoint = 0;
40123  pPager->nSavepoint = 0;
40124  pPager->nSubRec = 0;
40125}
40126
40127/*
40128** Set the bit number pgno in the PagerSavepoint.pInSavepoint
40129** bitvecs of all open savepoints. Return SQLITE_OK if successful
40130** or SQLITE_NOMEM if a malloc failure occurs.
40131*/
40132static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
40133  int ii;                   /* Loop counter */
40134  int rc = SQLITE_OK;       /* Result code */
40135
40136  for(ii=0; ii<pPager->nSavepoint; ii++){
40137    PagerSavepoint *p = &pPager->aSavepoint[ii];
40138    if( pgno<=p->nOrig ){
40139      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
40140      testcase( rc==SQLITE_NOMEM );
40141      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
40142    }
40143  }
40144  return rc;
40145}
40146
40147/*
40148** This function is a no-op if the pager is in exclusive mode and not
40149** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
40150** state.
40151**
40152** If the pager is not in exclusive-access mode, the database file is
40153** completely unlocked. If the file is unlocked and the file-system does
40154** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
40155** closed (if it is open).
40156**
40157** If the pager is in ERROR state when this function is called, the
40158** contents of the pager cache are discarded before switching back to
40159** the OPEN state. Regardless of whether the pager is in exclusive-mode
40160** or not, any journal file left in the file-system will be treated
40161** as a hot-journal and rolled back the next time a read-transaction
40162** is opened (by this or by any other connection).
40163*/
40164static void pager_unlock(Pager *pPager){
40165
40166  assert( pPager->eState==PAGER_READER
40167       || pPager->eState==PAGER_OPEN
40168       || pPager->eState==PAGER_ERROR
40169  );
40170
40171  sqlite3BitvecDestroy(pPager->pInJournal);
40172  pPager->pInJournal = 0;
40173  releaseAllSavepoints(pPager);
40174
40175  if( pagerUseWal(pPager) ){
40176    assert( !isOpen(pPager->jfd) );
40177    sqlite3WalEndReadTransaction(pPager->pWal);
40178    pPager->eState = PAGER_OPEN;
40179  }else if( !pPager->exclusiveMode ){
40180    int rc;                       /* Error code returned by pagerUnlockDb() */
40181    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
40182
40183    /* If the operating system support deletion of open files, then
40184    ** close the journal file when dropping the database lock.  Otherwise
40185    ** another connection with journal_mode=delete might delete the file
40186    ** out from under us.
40187    */
40188    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
40189    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
40190    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
40191    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
40192    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
40193    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
40194    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
40195     || 1!=(pPager->journalMode & 5)
40196    ){
40197      sqlite3OsClose(pPager->jfd);
40198    }
40199
40200    /* If the pager is in the ERROR state and the call to unlock the database
40201    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
40202    ** above the #define for UNKNOWN_LOCK for an explanation of why this
40203    ** is necessary.
40204    */
40205    rc = pagerUnlockDb(pPager, NO_LOCK);
40206    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
40207      pPager->eLock = UNKNOWN_LOCK;
40208    }
40209
40210    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
40211    ** without clearing the error code. This is intentional - the error
40212    ** code is cleared and the cache reset in the block below.
40213    */
40214    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
40215    pPager->changeCountDone = 0;
40216    pPager->eState = PAGER_OPEN;
40217  }
40218
40219  /* If Pager.errCode is set, the contents of the pager cache cannot be
40220  ** trusted. Now that there are no outstanding references to the pager,
40221  ** it can safely move back to PAGER_OPEN state. This happens in both
40222  ** normal and exclusive-locking mode.
40223  */
40224  if( pPager->errCode ){
40225    assert( !MEMDB );
40226    pager_reset(pPager);
40227    pPager->changeCountDone = pPager->tempFile;
40228    pPager->eState = PAGER_OPEN;
40229    pPager->errCode = SQLITE_OK;
40230  }
40231
40232  pPager->journalOff = 0;
40233  pPager->journalHdr = 0;
40234  pPager->setMaster = 0;
40235}
40236
40237/*
40238** This function is called whenever an IOERR or FULL error that requires
40239** the pager to transition into the ERROR state may ahve occurred.
40240** The first argument is a pointer to the pager structure, the second
40241** the error-code about to be returned by a pager API function. The
40242** value returned is a copy of the second argument to this function.
40243**
40244** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
40245** IOERR sub-codes, the pager enters the ERROR state and the error code
40246** is stored in Pager.errCode. While the pager remains in the ERROR state,
40247** all major API calls on the Pager will immediately return Pager.errCode.
40248**
40249** The ERROR state indicates that the contents of the pager-cache
40250** cannot be trusted. This state can be cleared by completely discarding
40251** the contents of the pager-cache. If a transaction was active when
40252** the persistent error occurred, then the rollback journal may need
40253** to be replayed to restore the contents of the database file (as if
40254** it were a hot-journal).
40255*/
40256static int pager_error(Pager *pPager, int rc){
40257  int rc2 = rc & 0xff;
40258  assert( rc==SQLITE_OK || !MEMDB );
40259  assert(
40260       pPager->errCode==SQLITE_FULL ||
40261       pPager->errCode==SQLITE_OK ||
40262       (pPager->errCode & 0xff)==SQLITE_IOERR
40263  );
40264  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
40265    pPager->errCode = rc;
40266    pPager->eState = PAGER_ERROR;
40267  }
40268  return rc;
40269}
40270
40271/*
40272** This routine ends a transaction. A transaction is usually ended by
40273** either a COMMIT or a ROLLBACK operation. This routine may be called
40274** after rollback of a hot-journal, or if an error occurs while opening
40275** the journal file or writing the very first journal-header of a
40276** database transaction.
40277**
40278** This routine is never called in PAGER_ERROR state. If it is called
40279** in PAGER_NONE or PAGER_SHARED state and the lock held is less
40280** exclusive than a RESERVED lock, it is a no-op.
40281**
40282** Otherwise, any active savepoints are released.
40283**
40284** If the journal file is open, then it is "finalized". Once a journal
40285** file has been finalized it is not possible to use it to roll back a
40286** transaction. Nor will it be considered to be a hot-journal by this
40287** or any other database connection. Exactly how a journal is finalized
40288** depends on whether or not the pager is running in exclusive mode and
40289** the current journal-mode (Pager.journalMode value), as follows:
40290**
40291**   journalMode==MEMORY
40292**     Journal file descriptor is simply closed. This destroys an
40293**     in-memory journal.
40294**
40295**   journalMode==TRUNCATE
40296**     Journal file is truncated to zero bytes in size.
40297**
40298**   journalMode==PERSIST
40299**     The first 28 bytes of the journal file are zeroed. This invalidates
40300**     the first journal header in the file, and hence the entire journal
40301**     file. An invalid journal file cannot be rolled back.
40302**
40303**   journalMode==DELETE
40304**     The journal file is closed and deleted using sqlite3OsDelete().
40305**
40306**     If the pager is running in exclusive mode, this method of finalizing
40307**     the journal file is never used. Instead, if the journalMode is
40308**     DELETE and the pager is in exclusive mode, the method described under
40309**     journalMode==PERSIST is used instead.
40310**
40311** After the journal is finalized, the pager moves to PAGER_READER state.
40312** If running in non-exclusive rollback mode, the lock on the file is
40313** downgraded to a SHARED_LOCK.
40314**
40315** SQLITE_OK is returned if no error occurs. If an error occurs during
40316** any of the IO operations to finalize the journal file or unlock the
40317** database then the IO error code is returned to the user. If the
40318** operation to finalize the journal file fails, then the code still
40319** tries to unlock the database file if not in exclusive mode. If the
40320** unlock operation fails as well, then the first error code related
40321** to the first error encountered (the journal finalization one) is
40322** returned.
40323*/
40324static int pager_end_transaction(Pager *pPager, int hasMaster){
40325  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
40326  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
40327
40328  /* Do nothing if the pager does not have an open write transaction
40329  ** or at least a RESERVED lock. This function may be called when there
40330  ** is no write-transaction active but a RESERVED or greater lock is
40331  ** held under two circumstances:
40332  **
40333  **   1. After a successful hot-journal rollback, it is called with
40334  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
40335  **
40336  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
40337  **      lock switches back to locking_mode=normal and then executes a
40338  **      read-transaction, this function is called with eState==PAGER_READER
40339  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
40340  */
40341  assert( assert_pager_state(pPager) );
40342  assert( pPager->eState!=PAGER_ERROR );
40343  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
40344    return SQLITE_OK;
40345  }
40346
40347  releaseAllSavepoints(pPager);
40348  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
40349  if( isOpen(pPager->jfd) ){
40350    assert( !pagerUseWal(pPager) );
40351
40352    /* Finalize the journal file. */
40353    if( sqlite3IsMemJournal(pPager->jfd) ){
40354      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
40355      sqlite3OsClose(pPager->jfd);
40356    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
40357      if( pPager->journalOff==0 ){
40358        rc = SQLITE_OK;
40359      }else{
40360        rc = sqlite3OsTruncate(pPager->jfd, 0);
40361      }
40362      pPager->journalOff = 0;
40363    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
40364      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
40365    ){
40366      rc = zeroJournalHdr(pPager, hasMaster);
40367      pPager->journalOff = 0;
40368    }else{
40369      /* This branch may be executed with Pager.journalMode==MEMORY if
40370      ** a hot-journal was just rolled back. In this case the journal
40371      ** file should be closed and deleted. If this connection writes to
40372      ** the database file, it will do so using an in-memory journal.
40373      */
40374      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
40375           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
40376           || pPager->journalMode==PAGER_JOURNALMODE_WAL
40377      );
40378      sqlite3OsClose(pPager->jfd);
40379      if( !pPager->tempFile ){
40380        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
40381      }
40382    }
40383  }
40384
40385#ifdef SQLITE_CHECK_PAGES
40386  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
40387  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
40388    PgHdr *p = pager_lookup(pPager, 1);
40389    if( p ){
40390      p->pageHash = 0;
40391      sqlite3PagerUnref(p);
40392    }
40393  }
40394#endif
40395
40396  sqlite3BitvecDestroy(pPager->pInJournal);
40397  pPager->pInJournal = 0;
40398  pPager->nRec = 0;
40399  sqlite3PcacheCleanAll(pPager->pPCache);
40400  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
40401
40402  if( pagerUseWal(pPager) ){
40403    /* Drop the WAL write-lock, if any. Also, if the connection was in
40404    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
40405    ** lock held on the database file.
40406    */
40407    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
40408    assert( rc2==SQLITE_OK );
40409  }
40410  if( !pPager->exclusiveMode
40411   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
40412  ){
40413    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
40414    pPager->changeCountDone = 0;
40415  }
40416  pPager->eState = PAGER_READER;
40417  pPager->setMaster = 0;
40418
40419  return (rc==SQLITE_OK?rc2:rc);
40420}
40421
40422/*
40423** Execute a rollback if a transaction is active and unlock the
40424** database file.
40425**
40426** If the pager has already entered the ERROR state, do not attempt
40427** the rollback at this time. Instead, pager_unlock() is called. The
40428** call to pager_unlock() will discard all in-memory pages, unlock
40429** the database file and move the pager back to OPEN state. If this
40430** means that there is a hot-journal left in the file-system, the next
40431** connection to obtain a shared lock on the pager (which may be this one)
40432** will roll it back.
40433**
40434** If the pager has not already entered the ERROR state, but an IO or
40435** malloc error occurs during a rollback, then this will itself cause
40436** the pager to enter the ERROR state. Which will be cleared by the
40437** call to pager_unlock(), as described above.
40438*/
40439static void pagerUnlockAndRollback(Pager *pPager){
40440  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
40441    assert( assert_pager_state(pPager) );
40442    if( pPager->eState>=PAGER_WRITER_LOCKED ){
40443      sqlite3BeginBenignMalloc();
40444      sqlite3PagerRollback(pPager);
40445      sqlite3EndBenignMalloc();
40446    }else if( !pPager->exclusiveMode ){
40447      assert( pPager->eState==PAGER_READER );
40448      pager_end_transaction(pPager, 0);
40449    }
40450  }
40451  pager_unlock(pPager);
40452}
40453
40454/*
40455** Parameter aData must point to a buffer of pPager->pageSize bytes
40456** of data. Compute and return a checksum based ont the contents of the
40457** page of data and the current value of pPager->cksumInit.
40458**
40459** This is not a real checksum. It is really just the sum of the
40460** random initial value (pPager->cksumInit) and every 200th byte
40461** of the page data, starting with byte offset (pPager->pageSize%200).
40462** Each byte is interpreted as an 8-bit unsigned integer.
40463**
40464** Changing the formula used to compute this checksum results in an
40465** incompatible journal file format.
40466**
40467** If journal corruption occurs due to a power failure, the most likely
40468** scenario is that one end or the other of the record will be changed.
40469** It is much less likely that the two ends of the journal record will be
40470** correct and the middle be corrupt.  Thus, this "checksum" scheme,
40471** though fast and simple, catches the mostly likely kind of corruption.
40472*/
40473static u32 pager_cksum(Pager *pPager, const u8 *aData){
40474  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
40475  int i = pPager->pageSize-200;          /* Loop counter */
40476  while( i>0 ){
40477    cksum += aData[i];
40478    i -= 200;
40479  }
40480  return cksum;
40481}
40482
40483/*
40484** Report the current page size and number of reserved bytes back
40485** to the codec.
40486*/
40487#ifdef SQLITE_HAS_CODEC
40488static void pagerReportSize(Pager *pPager){
40489  if( pPager->xCodecSizeChng ){
40490    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
40491                           (int)pPager->nReserve);
40492  }
40493}
40494#else
40495# define pagerReportSize(X)     /* No-op if we do not support a codec */
40496#endif
40497
40498/*
40499** Read a single page from either the journal file (if isMainJrnl==1) or
40500** from the sub-journal (if isMainJrnl==0) and playback that page.
40501** The page begins at offset *pOffset into the file. The *pOffset
40502** value is increased to the start of the next page in the journal.
40503**
40504** The main rollback journal uses checksums - the statement journal does
40505** not.
40506**
40507** If the page number of the page record read from the (sub-)journal file
40508** is greater than the current value of Pager.dbSize, then playback is
40509** skipped and SQLITE_OK is returned.
40510**
40511** If pDone is not NULL, then it is a record of pages that have already
40512** been played back.  If the page at *pOffset has already been played back
40513** (if the corresponding pDone bit is set) then skip the playback.
40514** Make sure the pDone bit corresponding to the *pOffset page is set
40515** prior to returning.
40516**
40517** If the page record is successfully read from the (sub-)journal file
40518** and played back, then SQLITE_OK is returned. If an IO error occurs
40519** while reading the record from the (sub-)journal file or while writing
40520** to the database file, then the IO error code is returned. If data
40521** is successfully read from the (sub-)journal file but appears to be
40522** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
40523** two circumstances:
40524**
40525**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
40526**   * If the record is being rolled back from the main journal file
40527**     and the checksum field does not match the record content.
40528**
40529** Neither of these two scenarios are possible during a savepoint rollback.
40530**
40531** If this is a savepoint rollback, then memory may have to be dynamically
40532** allocated by this function. If this is the case and an allocation fails,
40533** SQLITE_NOMEM is returned.
40534*/
40535static int pager_playback_one_page(
40536  Pager *pPager,                /* The pager being played back */
40537  i64 *pOffset,                 /* Offset of record to playback */
40538  Bitvec *pDone,                /* Bitvec of pages already played back */
40539  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
40540  int isSavepnt                 /* True for a savepoint rollback */
40541){
40542  int rc;
40543  PgHdr *pPg;                   /* An existing page in the cache */
40544  Pgno pgno;                    /* The page number of a page in journal */
40545  u32 cksum;                    /* Checksum used for sanity checking */
40546  char *aData;                  /* Temporary storage for the page */
40547  sqlite3_file *jfd;            /* The file descriptor for the journal file */
40548  int isSynced;                 /* True if journal page is synced */
40549
40550  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
40551  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
40552  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
40553  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
40554
40555  aData = pPager->pTmpSpace;
40556  assert( aData );         /* Temp storage must have already been allocated */
40557  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
40558
40559  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
40560  ** or savepoint rollback done at the request of the caller) or this is
40561  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
40562  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
40563  ** only reads from the main journal, not the sub-journal.
40564  */
40565  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
40566       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
40567  );
40568  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
40569
40570  /* Read the page number and page data from the journal or sub-journal
40571  ** file. Return an error code to the caller if an IO error occurs.
40572  */
40573  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
40574  rc = read32bits(jfd, *pOffset, &pgno);
40575  if( rc!=SQLITE_OK ) return rc;
40576  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
40577  if( rc!=SQLITE_OK ) return rc;
40578  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
40579
40580  /* Sanity checking on the page.  This is more important that I originally
40581  ** thought.  If a power failure occurs while the journal is being written,
40582  ** it could cause invalid data to be written into the journal.  We need to
40583  ** detect this invalid data (with high probability) and ignore it.
40584  */
40585  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
40586    assert( !isSavepnt );
40587    return SQLITE_DONE;
40588  }
40589  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
40590    return SQLITE_OK;
40591  }
40592  if( isMainJrnl ){
40593    rc = read32bits(jfd, (*pOffset)-4, &cksum);
40594    if( rc ) return rc;
40595    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
40596      return SQLITE_DONE;
40597    }
40598  }
40599
40600  /* If this page has already been played by before during the current
40601  ** rollback, then don't bother to play it back again.
40602  */
40603  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
40604    return rc;
40605  }
40606
40607  /* When playing back page 1, restore the nReserve setting
40608  */
40609  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
40610    pPager->nReserve = ((u8*)aData)[20];
40611    pagerReportSize(pPager);
40612  }
40613
40614  /* If the pager is in CACHEMOD state, then there must be a copy of this
40615  ** page in the pager cache. In this case just update the pager cache,
40616  ** not the database file. The page is left marked dirty in this case.
40617  **
40618  ** An exception to the above rule: If the database is in no-sync mode
40619  ** and a page is moved during an incremental vacuum then the page may
40620  ** not be in the pager cache. Later: if a malloc() or IO error occurs
40621  ** during a Movepage() call, then the page may not be in the cache
40622  ** either. So the condition described in the above paragraph is not
40623  ** assert()able.
40624  **
40625  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
40626  ** pager cache if it exists and the main file. The page is then marked
40627  ** not dirty. Since this code is only executed in PAGER_OPEN state for
40628  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
40629  ** if the pager is in OPEN state.
40630  **
40631  ** Ticket #1171:  The statement journal might contain page content that is
40632  ** different from the page content at the start of the transaction.
40633  ** This occurs when a page is changed prior to the start of a statement
40634  ** then changed again within the statement.  When rolling back such a
40635  ** statement we must not write to the original database unless we know
40636  ** for certain that original page contents are synced into the main rollback
40637  ** journal.  Otherwise, a power loss might leave modified data in the
40638  ** database file without an entry in the rollback journal that can
40639  ** restore the database to its original form.  Two conditions must be
40640  ** met before writing to the database files. (1) the database must be
40641  ** locked.  (2) we know that the original page content is fully synced
40642  ** in the main journal either because the page is not in cache or else
40643  ** the page is marked as needSync==0.
40644  **
40645  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
40646  ** is possible to fail a statement on a database that does not yet exist.
40647  ** Do not attempt to write if database file has never been opened.
40648  */
40649  if( pagerUseWal(pPager) ){
40650    pPg = 0;
40651  }else{
40652    pPg = pager_lookup(pPager, pgno);
40653  }
40654  assert( pPg || !MEMDB );
40655  assert( pPager->eState!=PAGER_OPEN || pPg==0 );
40656  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
40657           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
40658           (isMainJrnl?"main-journal":"sub-journal")
40659  ));
40660  if( isMainJrnl ){
40661    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
40662  }else{
40663    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
40664  }
40665  if( isOpen(pPager->fd)
40666   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40667   && isSynced
40668  ){
40669    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
40670    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
40671    assert( !pagerUseWal(pPager) );
40672    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
40673    if( pgno>pPager->dbFileSize ){
40674      pPager->dbFileSize = pgno;
40675    }
40676    if( pPager->pBackup ){
40677      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
40678      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
40679      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
40680    }
40681  }else if( !isMainJrnl && pPg==0 ){
40682    /* If this is a rollback of a savepoint and data was not written to
40683    ** the database and the page is not in-memory, there is a potential
40684    ** problem. When the page is next fetched by the b-tree layer, it
40685    ** will be read from the database file, which may or may not be
40686    ** current.
40687    **
40688    ** There are a couple of different ways this can happen. All are quite
40689    ** obscure. When running in synchronous mode, this can only happen
40690    ** if the page is on the free-list at the start of the transaction, then
40691    ** populated, then moved using sqlite3PagerMovepage().
40692    **
40693    ** The solution is to add an in-memory page to the cache containing
40694    ** the data just read from the sub-journal. Mark the page as dirty
40695    ** and if the pager requires a journal-sync, then mark the page as
40696    ** requiring a journal-sync before it is written.
40697    */
40698    assert( isSavepnt );
40699    assert( pPager->doNotSpill==0 );
40700    pPager->doNotSpill++;
40701    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
40702    assert( pPager->doNotSpill==1 );
40703    pPager->doNotSpill--;
40704    if( rc!=SQLITE_OK ) return rc;
40705    pPg->flags &= ~PGHDR_NEED_READ;
40706    sqlite3PcacheMakeDirty(pPg);
40707  }
40708  if( pPg ){
40709    /* No page should ever be explicitly rolled back that is in use, except
40710    ** for page 1 which is held in use in order to keep the lock on the
40711    ** database active. However such a page may be rolled back as a result
40712    ** of an internal error resulting in an automatic call to
40713    ** sqlite3PagerRollback().
40714    */
40715    void *pData;
40716    pData = pPg->pData;
40717    memcpy(pData, (u8*)aData, pPager->pageSize);
40718    pPager->xReiniter(pPg);
40719    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
40720      /* If the contents of this page were just restored from the main
40721      ** journal file, then its content must be as they were when the
40722      ** transaction was first opened. In this case we can mark the page
40723      ** as clean, since there will be no need to write it out to the
40724      ** database.
40725      **
40726      ** There is one exception to this rule. If the page is being rolled
40727      ** back as part of a savepoint (or statement) rollback from an
40728      ** unsynced portion of the main journal file, then it is not safe
40729      ** to mark the page as clean. This is because marking the page as
40730      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
40731      ** already in the journal file (recorded in Pager.pInJournal) and
40732      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
40733      ** again within this transaction, it will be marked as dirty but
40734      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
40735      ** be written out into the database file before its journal file
40736      ** segment is synced. If a crash occurs during or following this,
40737      ** database corruption may ensue.
40738      */
40739      assert( !pagerUseWal(pPager) );
40740      sqlite3PcacheMakeClean(pPg);
40741    }
40742    pager_set_pagehash(pPg);
40743
40744    /* If this was page 1, then restore the value of Pager.dbFileVers.
40745    ** Do this before any decoding. */
40746    if( pgno==1 ){
40747      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
40748    }
40749
40750    /* Decode the page just read from disk */
40751    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
40752    sqlite3PcacheRelease(pPg);
40753  }
40754  return rc;
40755}
40756
40757/*
40758** Parameter zMaster is the name of a master journal file. A single journal
40759** file that referred to the master journal file has just been rolled back.
40760** This routine checks if it is possible to delete the master journal file,
40761** and does so if it is.
40762**
40763** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
40764** available for use within this function.
40765**
40766** When a master journal file is created, it is populated with the names
40767** of all of its child journals, one after another, formatted as utf-8
40768** encoded text. The end of each child journal file is marked with a
40769** nul-terminator byte (0x00). i.e. the entire contents of a master journal
40770** file for a transaction involving two databases might be:
40771**
40772**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
40773**
40774** A master journal file may only be deleted once all of its child
40775** journals have been rolled back.
40776**
40777** This function reads the contents of the master-journal file into
40778** memory and loops through each of the child journal names. For
40779** each child journal, it checks if:
40780**
40781**   * if the child journal exists, and if so
40782**   * if the child journal contains a reference to master journal
40783**     file zMaster
40784**
40785** If a child journal can be found that matches both of the criteria
40786** above, this function returns without doing anything. Otherwise, if
40787** no such child journal can be found, file zMaster is deleted from
40788** the file-system using sqlite3OsDelete().
40789**
40790** If an IO error within this function, an error code is returned. This
40791** function allocates memory by calling sqlite3Malloc(). If an allocation
40792** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
40793** occur, SQLITE_OK is returned.
40794**
40795** TODO: This function allocates a single block of memory to load
40796** the entire contents of the master journal file. This could be
40797** a couple of kilobytes or so - potentially larger than the page
40798** size.
40799*/
40800static int pager_delmaster(Pager *pPager, const char *zMaster){
40801  sqlite3_vfs *pVfs = pPager->pVfs;
40802  int rc;                   /* Return code */
40803  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
40804  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
40805  char *zMasterJournal = 0; /* Contents of master journal file */
40806  i64 nMasterJournal;       /* Size of master journal file */
40807  char *zJournal;           /* Pointer to one journal within MJ file */
40808  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
40809  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
40810
40811  /* Allocate space for both the pJournal and pMaster file descriptors.
40812  ** If successful, open the master journal file for reading.
40813  */
40814  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
40815  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
40816  if( !pMaster ){
40817    rc = SQLITE_NOMEM;
40818  }else{
40819    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
40820    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
40821  }
40822  if( rc!=SQLITE_OK ) goto delmaster_out;
40823
40824  /* Load the entire master journal file into space obtained from
40825  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
40826  ** sufficient space (in zMasterPtr) to hold the names of master
40827  ** journal files extracted from regular rollback-journals.
40828  */
40829  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
40830  if( rc!=SQLITE_OK ) goto delmaster_out;
40831  nMasterPtr = pVfs->mxPathname+1;
40832  zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
40833  if( !zMasterJournal ){
40834    rc = SQLITE_NOMEM;
40835    goto delmaster_out;
40836  }
40837  zMasterPtr = &zMasterJournal[nMasterJournal+1];
40838  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
40839  if( rc!=SQLITE_OK ) goto delmaster_out;
40840  zMasterJournal[nMasterJournal] = 0;
40841
40842  zJournal = zMasterJournal;
40843  while( (zJournal-zMasterJournal)<nMasterJournal ){
40844    int exists;
40845    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
40846    if( rc!=SQLITE_OK ){
40847      goto delmaster_out;
40848    }
40849    if( exists ){
40850      /* One of the journals pointed to by the master journal exists.
40851      ** Open it and check if it points at the master journal. If
40852      ** so, return without deleting the master journal file.
40853      */
40854      int c;
40855      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
40856      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
40857      if( rc!=SQLITE_OK ){
40858        goto delmaster_out;
40859      }
40860
40861      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
40862      sqlite3OsClose(pJournal);
40863      if( rc!=SQLITE_OK ){
40864        goto delmaster_out;
40865      }
40866
40867      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
40868      if( c ){
40869        /* We have a match. Do not delete the master journal file. */
40870        goto delmaster_out;
40871      }
40872    }
40873    zJournal += (sqlite3Strlen30(zJournal)+1);
40874  }
40875
40876  sqlite3OsClose(pMaster);
40877  rc = sqlite3OsDelete(pVfs, zMaster, 0);
40878
40879delmaster_out:
40880  sqlite3_free(zMasterJournal);
40881  if( pMaster ){
40882    sqlite3OsClose(pMaster);
40883    assert( !isOpen(pJournal) );
40884    sqlite3_free(pMaster);
40885  }
40886  return rc;
40887}
40888
40889
40890/*
40891** This function is used to change the actual size of the database
40892** file in the file-system. This only happens when committing a transaction,
40893** or rolling back a transaction (including rolling back a hot-journal).
40894**
40895** If the main database file is not open, or the pager is not in either
40896** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
40897** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
40898** If the file on disk is currently larger than nPage pages, then use the VFS
40899** xTruncate() method to truncate it.
40900**
40901** Or, it might might be the case that the file on disk is smaller than
40902** nPage pages. Some operating system implementations can get confused if
40903** you try to truncate a file to some size that is larger than it
40904** currently is, so detect this case and write a single zero byte to
40905** the end of the new file instead.
40906**
40907** If successful, return SQLITE_OK. If an IO error occurs while modifying
40908** the database file, return the error code to the caller.
40909*/
40910static int pager_truncate(Pager *pPager, Pgno nPage){
40911  int rc = SQLITE_OK;
40912  assert( pPager->eState!=PAGER_ERROR );
40913  assert( pPager->eState!=PAGER_READER );
40914
40915  if( isOpen(pPager->fd)
40916   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40917  ){
40918    i64 currentSize, newSize;
40919    int szPage = pPager->pageSize;
40920    assert( pPager->eLock==EXCLUSIVE_LOCK );
40921    /* TODO: Is it safe to use Pager.dbFileSize here? */
40922    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
40923    newSize = szPage*(i64)nPage;
40924    if( rc==SQLITE_OK && currentSize!=newSize ){
40925      if( currentSize>newSize ){
40926        rc = sqlite3OsTruncate(pPager->fd, newSize);
40927      }else if( (currentSize+szPage)<=newSize ){
40928        char *pTmp = pPager->pTmpSpace;
40929        memset(pTmp, 0, szPage);
40930        testcase( (newSize-szPage) == currentSize );
40931        testcase( (newSize-szPage) >  currentSize );
40932        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
40933      }
40934      if( rc==SQLITE_OK ){
40935        pPager->dbFileSize = nPage;
40936      }
40937    }
40938  }
40939  return rc;
40940}
40941
40942/*
40943** Set the value of the Pager.sectorSize variable for the given
40944** pager based on the value returned by the xSectorSize method
40945** of the open database file. The sector size will be used used
40946** to determine the size and alignment of journal header and
40947** master journal pointers within created journal files.
40948**
40949** For temporary files the effective sector size is always 512 bytes.
40950**
40951** Otherwise, for non-temporary files, the effective sector size is
40952** the value returned by the xSectorSize() method rounded up to 32 if
40953** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
40954** is greater than MAX_SECTOR_SIZE.
40955**
40956** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
40957** the effective sector size to its minimum value (512).  The purpose of
40958** pPager->sectorSize is to define the "blast radius" of bytes that
40959** might change if a crash occurs while writing to a single byte in
40960** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
40961** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
40962** size.  For backwards compatibility of the rollback journal file format,
40963** we cannot reduce the effective sector size below 512.
40964*/
40965static void setSectorSize(Pager *pPager){
40966  assert( isOpen(pPager->fd) || pPager->tempFile );
40967
40968  if( pPager->tempFile
40969   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
40970              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
40971  ){
40972    /* Sector size doesn't matter for temporary files. Also, the file
40973    ** may not have been opened yet, in which case the OsSectorSize()
40974    ** call will segfault. */
40975    pPager->sectorSize = 512;
40976  }else{
40977    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
40978    if( pPager->sectorSize<32 ){
40979      pPager->sectorSize = 512;
40980    }
40981    if( pPager->sectorSize>MAX_SECTOR_SIZE ){
40982      assert( MAX_SECTOR_SIZE>=512 );
40983      pPager->sectorSize = MAX_SECTOR_SIZE;
40984    }
40985  }
40986}
40987
40988/*
40989** Playback the journal and thus restore the database file to
40990** the state it was in before we started making changes.
40991**
40992** The journal file format is as follows:
40993**
40994**  (1)  8 byte prefix.  A copy of aJournalMagic[].
40995**  (2)  4 byte big-endian integer which is the number of valid page records
40996**       in the journal.  If this value is 0xffffffff, then compute the
40997**       number of page records from the journal size.
40998**  (3)  4 byte big-endian integer which is the initial value for the
40999**       sanity checksum.
41000**  (4)  4 byte integer which is the number of pages to truncate the
41001**       database to during a rollback.
41002**  (5)  4 byte big-endian integer which is the sector size.  The header
41003**       is this many bytes in size.
41004**  (6)  4 byte big-endian integer which is the page size.
41005**  (7)  zero padding out to the next sector size.
41006**  (8)  Zero or more pages instances, each as follows:
41007**        +  4 byte page number.
41008**        +  pPager->pageSize bytes of data.
41009**        +  4 byte checksum
41010**
41011** When we speak of the journal header, we mean the first 7 items above.
41012** Each entry in the journal is an instance of the 8th item.
41013**
41014** Call the value from the second bullet "nRec".  nRec is the number of
41015** valid page entries in the journal.  In most cases, you can compute the
41016** value of nRec from the size of the journal file.  But if a power
41017** failure occurred while the journal was being written, it could be the
41018** case that the size of the journal file had already been increased but
41019** the extra entries had not yet made it safely to disk.  In such a case,
41020** the value of nRec computed from the file size would be too large.  For
41021** that reason, we always use the nRec value in the header.
41022**
41023** If the nRec value is 0xffffffff it means that nRec should be computed
41024** from the file size.  This value is used when the user selects the
41025** no-sync option for the journal.  A power failure could lead to corruption
41026** in this case.  But for things like temporary table (which will be
41027** deleted when the power is restored) we don't care.
41028**
41029** If the file opened as the journal file is not a well-formed
41030** journal file then all pages up to the first corrupted page are rolled
41031** back (or no pages if the journal header is corrupted). The journal file
41032** is then deleted and SQLITE_OK returned, just as if no corruption had
41033** been encountered.
41034**
41035** If an I/O or malloc() error occurs, the journal-file is not deleted
41036** and an error code is returned.
41037**
41038** The isHot parameter indicates that we are trying to rollback a journal
41039** that might be a hot journal.  Or, it could be that the journal is
41040** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
41041** If the journal really is hot, reset the pager cache prior rolling
41042** back any content.  If the journal is merely persistent, no reset is
41043** needed.
41044*/
41045static int pager_playback(Pager *pPager, int isHot){
41046  sqlite3_vfs *pVfs = pPager->pVfs;
41047  i64 szJ;                 /* Size of the journal file in bytes */
41048  u32 nRec;                /* Number of Records in the journal */
41049  u32 u;                   /* Unsigned loop counter */
41050  Pgno mxPg = 0;           /* Size of the original file in pages */
41051  int rc;                  /* Result code of a subroutine */
41052  int res = 1;             /* Value returned by sqlite3OsAccess() */
41053  char *zMaster = 0;       /* Name of master journal file if any */
41054  int needPagerReset;      /* True to reset page prior to first page rollback */
41055
41056  /* Figure out how many records are in the journal.  Abort early if
41057  ** the journal is empty.
41058  */
41059  assert( isOpen(pPager->jfd) );
41060  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
41061  if( rc!=SQLITE_OK ){
41062    goto end_playback;
41063  }
41064
41065  /* Read the master journal name from the journal, if it is present.
41066  ** If a master journal file name is specified, but the file is not
41067  ** present on disk, then the journal is not hot and does not need to be
41068  ** played back.
41069  **
41070  ** TODO: Technically the following is an error because it assumes that
41071  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
41072  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
41073  **  mxPathname is 512, which is the same as the minimum allowable value
41074  ** for pageSize.
41075  */
41076  zMaster = pPager->pTmpSpace;
41077  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41078  if( rc==SQLITE_OK && zMaster[0] ){
41079    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
41080  }
41081  zMaster = 0;
41082  if( rc!=SQLITE_OK || !res ){
41083    goto end_playback;
41084  }
41085  pPager->journalOff = 0;
41086  needPagerReset = isHot;
41087
41088  /* This loop terminates either when a readJournalHdr() or
41089  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
41090  ** occurs.
41091  */
41092  while( 1 ){
41093    /* Read the next journal header from the journal file.  If there are
41094    ** not enough bytes left in the journal file for a complete header, or
41095    ** it is corrupted, then a process must have failed while writing it.
41096    ** This indicates nothing more needs to be rolled back.
41097    */
41098    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
41099    if( rc!=SQLITE_OK ){
41100      if( rc==SQLITE_DONE ){
41101        rc = SQLITE_OK;
41102      }
41103      goto end_playback;
41104    }
41105
41106    /* If nRec is 0xffffffff, then this journal was created by a process
41107    ** working in no-sync mode. This means that the rest of the journal
41108    ** file consists of pages, there are no more journal headers. Compute
41109    ** the value of nRec based on this assumption.
41110    */
41111    if( nRec==0xffffffff ){
41112      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
41113      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
41114    }
41115
41116    /* If nRec is 0 and this rollback is of a transaction created by this
41117    ** process and if this is the final header in the journal, then it means
41118    ** that this part of the journal was being filled but has not yet been
41119    ** synced to disk.  Compute the number of pages based on the remaining
41120    ** size of the file.
41121    **
41122    ** The third term of the test was added to fix ticket #2565.
41123    ** When rolling back a hot journal, nRec==0 always means that the next
41124    ** chunk of the journal contains zero pages to be rolled back.  But
41125    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
41126    ** the journal, it means that the journal might contain additional
41127    ** pages that need to be rolled back and that the number of pages
41128    ** should be computed based on the journal file size.
41129    */
41130    if( nRec==0 && !isHot &&
41131        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
41132      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
41133    }
41134
41135    /* If this is the first header read from the journal, truncate the
41136    ** database file back to its original size.
41137    */
41138    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
41139      rc = pager_truncate(pPager, mxPg);
41140      if( rc!=SQLITE_OK ){
41141        goto end_playback;
41142      }
41143      pPager->dbSize = mxPg;
41144    }
41145
41146    /* Copy original pages out of the journal and back into the
41147    ** database file and/or page cache.
41148    */
41149    for(u=0; u<nRec; u++){
41150      if( needPagerReset ){
41151        pager_reset(pPager);
41152        needPagerReset = 0;
41153      }
41154      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
41155      if( rc!=SQLITE_OK ){
41156        if( rc==SQLITE_DONE ){
41157          pPager->journalOff = szJ;
41158          break;
41159        }else if( rc==SQLITE_IOERR_SHORT_READ ){
41160          /* If the journal has been truncated, simply stop reading and
41161          ** processing the journal. This might happen if the journal was
41162          ** not completely written and synced prior to a crash.  In that
41163          ** case, the database should have never been written in the
41164          ** first place so it is OK to simply abandon the rollback. */
41165          rc = SQLITE_OK;
41166          goto end_playback;
41167        }else{
41168          /* If we are unable to rollback, quit and return the error
41169          ** code.  This will cause the pager to enter the error state
41170          ** so that no further harm will be done.  Perhaps the next
41171          ** process to come along will be able to rollback the database.
41172          */
41173          goto end_playback;
41174        }
41175      }
41176    }
41177  }
41178  /*NOTREACHED*/
41179  assert( 0 );
41180
41181end_playback:
41182  /* Following a rollback, the database file should be back in its original
41183  ** state prior to the start of the transaction, so invoke the
41184  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
41185  ** assertion that the transaction counter was modified.
41186  */
41187#ifdef SQLITE_DEBUG
41188  if( pPager->fd->pMethods ){
41189    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
41190  }
41191#endif
41192
41193  /* If this playback is happening automatically as a result of an IO or
41194  ** malloc error that occurred after the change-counter was updated but
41195  ** before the transaction was committed, then the change-counter
41196  ** modification may just have been reverted. If this happens in exclusive
41197  ** mode, then subsequent transactions performed by the connection will not
41198  ** update the change-counter at all. This may lead to cache inconsistency
41199  ** problems for other processes at some point in the future. So, just
41200  ** in case this has happened, clear the changeCountDone flag now.
41201  */
41202  pPager->changeCountDone = pPager->tempFile;
41203
41204  if( rc==SQLITE_OK ){
41205    zMaster = pPager->pTmpSpace;
41206    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41207    testcase( rc!=SQLITE_OK );
41208  }
41209  if( rc==SQLITE_OK
41210   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41211  ){
41212    rc = sqlite3PagerSync(pPager);
41213  }
41214  if( rc==SQLITE_OK ){
41215    rc = pager_end_transaction(pPager, zMaster[0]!='\0');
41216    testcase( rc!=SQLITE_OK );
41217  }
41218  if( rc==SQLITE_OK && zMaster[0] && res ){
41219    /* If there was a master journal and this routine will return success,
41220    ** see if it is possible to delete the master journal.
41221    */
41222    rc = pager_delmaster(pPager, zMaster);
41223    testcase( rc!=SQLITE_OK );
41224  }
41225
41226  /* The Pager.sectorSize variable may have been updated while rolling
41227  ** back a journal created by a process with a different sector size
41228  ** value. Reset it to the correct value for this process.
41229  */
41230  setSectorSize(pPager);
41231  return rc;
41232}
41233
41234
41235/*
41236** Read the content for page pPg out of the database file and into
41237** pPg->pData. A shared lock or greater must be held on the database
41238** file before this function is called.
41239**
41240** If page 1 is read, then the value of Pager.dbFileVers[] is set to
41241** the value read from the database file.
41242**
41243** If an IO error occurs, then the IO error is returned to the caller.
41244** Otherwise, SQLITE_OK is returned.
41245*/
41246static int readDbPage(PgHdr *pPg){
41247  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
41248  Pgno pgno = pPg->pgno;       /* Page number to read */
41249  int rc = SQLITE_OK;          /* Return code */
41250  int isInWal = 0;             /* True if page is in log file */
41251  int pgsz = pPager->pageSize; /* Number of bytes to read */
41252
41253  assert( pPager->eState>=PAGER_READER && !MEMDB );
41254  assert( isOpen(pPager->fd) );
41255
41256  if( NEVER(!isOpen(pPager->fd)) ){
41257    assert( pPager->tempFile );
41258    memset(pPg->pData, 0, pPager->pageSize);
41259    return SQLITE_OK;
41260  }
41261
41262  if( pagerUseWal(pPager) ){
41263    /* Try to pull the page from the write-ahead log. */
41264    rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
41265  }
41266  if( rc==SQLITE_OK && !isInWal ){
41267    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
41268    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
41269    if( rc==SQLITE_IOERR_SHORT_READ ){
41270      rc = SQLITE_OK;
41271    }
41272  }
41273
41274  if( pgno==1 ){
41275    if( rc ){
41276      /* If the read is unsuccessful, set the dbFileVers[] to something
41277      ** that will never be a valid file version.  dbFileVers[] is a copy
41278      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
41279      ** zero or the size of the database in page. Bytes 32..35 and 35..39
41280      ** should be page numbers which are never 0xffffffff.  So filling
41281      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
41282      **
41283      ** For an encrypted database, the situation is more complex:  bytes
41284      ** 24..39 of the database are white noise.  But the probability of
41285      ** white noising equaling 16 bytes of 0xff is vanishingly small so
41286      ** we should still be ok.
41287      */
41288      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
41289    }else{
41290      u8 *dbFileVers = &((u8*)pPg->pData)[24];
41291      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
41292    }
41293  }
41294  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
41295
41296  PAGER_INCR(sqlite3_pager_readdb_count);
41297  PAGER_INCR(pPager->nRead);
41298  IOTRACE(("PGIN %p %d\n", pPager, pgno));
41299  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
41300               PAGERID(pPager), pgno, pager_pagehash(pPg)));
41301
41302  return rc;
41303}
41304
41305/*
41306** Update the value of the change-counter at offsets 24 and 92 in
41307** the header and the sqlite version number at offset 96.
41308**
41309** This is an unconditional update.  See also the pager_incr_changecounter()
41310** routine which only updates the change-counter if the update is actually
41311** needed, as determined by the pPager->changeCountDone state variable.
41312*/
41313static void pager_write_changecounter(PgHdr *pPg){
41314  u32 change_counter;
41315
41316  /* Increment the value just read and write it back to byte 24. */
41317  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
41318  put32bits(((char*)pPg->pData)+24, change_counter);
41319
41320  /* Also store the SQLite version number in bytes 96..99 and in
41321  ** bytes 92..95 store the change counter for which the version number
41322  ** is valid. */
41323  put32bits(((char*)pPg->pData)+92, change_counter);
41324  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
41325}
41326
41327#ifndef SQLITE_OMIT_WAL
41328/*
41329** This function is invoked once for each page that has already been
41330** written into the log file when a WAL transaction is rolled back.
41331** Parameter iPg is the page number of said page. The pCtx argument
41332** is actually a pointer to the Pager structure.
41333**
41334** If page iPg is present in the cache, and has no outstanding references,
41335** it is discarded. Otherwise, if there are one or more outstanding
41336** references, the page content is reloaded from the database. If the
41337** attempt to reload content from the database is required and fails,
41338** return an SQLite error code. Otherwise, SQLITE_OK.
41339*/
41340static int pagerUndoCallback(void *pCtx, Pgno iPg){
41341  int rc = SQLITE_OK;
41342  Pager *pPager = (Pager *)pCtx;
41343  PgHdr *pPg;
41344
41345  pPg = sqlite3PagerLookup(pPager, iPg);
41346  if( pPg ){
41347    if( sqlite3PcachePageRefcount(pPg)==1 ){
41348      sqlite3PcacheDrop(pPg);
41349    }else{
41350      rc = readDbPage(pPg);
41351      if( rc==SQLITE_OK ){
41352        pPager->xReiniter(pPg);
41353      }
41354      sqlite3PagerUnref(pPg);
41355    }
41356  }
41357
41358  /* Normally, if a transaction is rolled back, any backup processes are
41359  ** updated as data is copied out of the rollback journal and into the
41360  ** database. This is not generally possible with a WAL database, as
41361  ** rollback involves simply truncating the log file. Therefore, if one
41362  ** or more frames have already been written to the log (and therefore
41363  ** also copied into the backup databases) as part of this transaction,
41364  ** the backups must be restarted.
41365  */
41366  sqlite3BackupRestart(pPager->pBackup);
41367
41368  return rc;
41369}
41370
41371/*
41372** This function is called to rollback a transaction on a WAL database.
41373*/
41374static int pagerRollbackWal(Pager *pPager){
41375  int rc;                         /* Return Code */
41376  PgHdr *pList;                   /* List of dirty pages to revert */
41377
41378  /* For all pages in the cache that are currently dirty or have already
41379  ** been written (but not committed) to the log file, do one of the
41380  ** following:
41381  **
41382  **   + Discard the cached page (if refcount==0), or
41383  **   + Reload page content from the database (if refcount>0).
41384  */
41385  pPager->dbSize = pPager->dbOrigSize;
41386  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
41387  pList = sqlite3PcacheDirtyList(pPager->pPCache);
41388  while( pList && rc==SQLITE_OK ){
41389    PgHdr *pNext = pList->pDirty;
41390    rc = pagerUndoCallback((void *)pPager, pList->pgno);
41391    pList = pNext;
41392  }
41393
41394  return rc;
41395}
41396
41397/*
41398** This function is a wrapper around sqlite3WalFrames(). As well as logging
41399** the contents of the list of pages headed by pList (connected by pDirty),
41400** this function notifies any active backup processes that the pages have
41401** changed.
41402**
41403** The list of pages passed into this routine is always sorted by page number.
41404** Hence, if page 1 appears anywhere on the list, it will be the first page.
41405*/
41406static int pagerWalFrames(
41407  Pager *pPager,                  /* Pager object */
41408  PgHdr *pList,                   /* List of frames to log */
41409  Pgno nTruncate,                 /* Database size after this commit */
41410  int isCommit                    /* True if this is a commit */
41411){
41412  int rc;                         /* Return code */
41413#if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
41414  PgHdr *p;                       /* For looping over pages */
41415#endif
41416
41417  assert( pPager->pWal );
41418  assert( pList );
41419#ifdef SQLITE_DEBUG
41420  /* Verify that the page list is in accending order */
41421  for(p=pList; p && p->pDirty; p=p->pDirty){
41422    assert( p->pgno < p->pDirty->pgno );
41423  }
41424#endif
41425
41426  if( isCommit ){
41427    /* If a WAL transaction is being committed, there is no point in writing
41428    ** any pages with page numbers greater than nTruncate into the WAL file.
41429    ** They will never be read by any client. So remove them from the pDirty
41430    ** list here. */
41431    PgHdr *p;
41432    PgHdr **ppNext = &pList;
41433    for(p=pList; (*ppNext = p); p=p->pDirty){
41434      if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
41435    }
41436    assert( pList );
41437  }
41438
41439  if( pList->pgno==1 ) pager_write_changecounter(pList);
41440  rc = sqlite3WalFrames(pPager->pWal,
41441      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
41442  );
41443  if( rc==SQLITE_OK && pPager->pBackup ){
41444    PgHdr *p;
41445    for(p=pList; p; p=p->pDirty){
41446      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
41447    }
41448  }
41449
41450#ifdef SQLITE_CHECK_PAGES
41451  pList = sqlite3PcacheDirtyList(pPager->pPCache);
41452  for(p=pList; p; p=p->pDirty){
41453    pager_set_pagehash(p);
41454  }
41455#endif
41456
41457  return rc;
41458}
41459
41460/*
41461** Begin a read transaction on the WAL.
41462**
41463** This routine used to be called "pagerOpenSnapshot()" because it essentially
41464** makes a snapshot of the database at the current point in time and preserves
41465** that snapshot for use by the reader in spite of concurrently changes by
41466** other writers or checkpointers.
41467*/
41468static int pagerBeginReadTransaction(Pager *pPager){
41469  int rc;                         /* Return code */
41470  int changed = 0;                /* True if cache must be reset */
41471
41472  assert( pagerUseWal(pPager) );
41473  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41474
41475  /* sqlite3WalEndReadTransaction() was not called for the previous
41476  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
41477  ** are in locking_mode=NORMAL and EndRead() was previously called,
41478  ** the duplicate call is harmless.
41479  */
41480  sqlite3WalEndReadTransaction(pPager->pWal);
41481
41482  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
41483  if( rc!=SQLITE_OK || changed ){
41484    pager_reset(pPager);
41485  }
41486
41487  return rc;
41488}
41489#endif
41490
41491/*
41492** This function is called as part of the transition from PAGER_OPEN
41493** to PAGER_READER state to determine the size of the database file
41494** in pages (assuming the page size currently stored in Pager.pageSize).
41495**
41496** If no error occurs, SQLITE_OK is returned and the size of the database
41497** in pages is stored in *pnPage. Otherwise, an error code (perhaps
41498** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
41499*/
41500static int pagerPagecount(Pager *pPager, Pgno *pnPage){
41501  Pgno nPage;                     /* Value to return via *pnPage */
41502
41503  /* Query the WAL sub-system for the database size. The WalDbsize()
41504  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
41505  ** if the database size is not available. The database size is not
41506  ** available from the WAL sub-system if the log file is empty or
41507  ** contains no valid committed transactions.
41508  */
41509  assert( pPager->eState==PAGER_OPEN );
41510  assert( pPager->eLock>=SHARED_LOCK );
41511  nPage = sqlite3WalDbsize(pPager->pWal);
41512
41513  /* If the database size was not available from the WAL sub-system,
41514  ** determine it based on the size of the database file. If the size
41515  ** of the database file is not an integer multiple of the page-size,
41516  ** round down to the nearest page. Except, any file larger than 0
41517  ** bytes in size is considered to contain at least one page.
41518  */
41519  if( nPage==0 ){
41520    i64 n = 0;                    /* Size of db file in bytes */
41521    assert( isOpen(pPager->fd) || pPager->tempFile );
41522    if( isOpen(pPager->fd) ){
41523      int rc = sqlite3OsFileSize(pPager->fd, &n);
41524      if( rc!=SQLITE_OK ){
41525        return rc;
41526      }
41527    }
41528    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
41529  }
41530
41531  /* If the current number of pages in the file is greater than the
41532  ** configured maximum pager number, increase the allowed limit so
41533  ** that the file can be read.
41534  */
41535  if( nPage>pPager->mxPgno ){
41536    pPager->mxPgno = (Pgno)nPage;
41537  }
41538
41539  *pnPage = nPage;
41540  return SQLITE_OK;
41541}
41542
41543#ifndef SQLITE_OMIT_WAL
41544/*
41545** Check if the *-wal file that corresponds to the database opened by pPager
41546** exists if the database is not empy, or verify that the *-wal file does
41547** not exist (by deleting it) if the database file is empty.
41548**
41549** If the database is not empty and the *-wal file exists, open the pager
41550** in WAL mode.  If the database is empty or if no *-wal file exists and
41551** if no error occurs, make sure Pager.journalMode is not set to
41552** PAGER_JOURNALMODE_WAL.
41553**
41554** Return SQLITE_OK or an error code.
41555**
41556** The caller must hold a SHARED lock on the database file to call this
41557** function. Because an EXCLUSIVE lock on the db file is required to delete
41558** a WAL on a none-empty database, this ensures there is no race condition
41559** between the xAccess() below and an xDelete() being executed by some
41560** other connection.
41561*/
41562static int pagerOpenWalIfPresent(Pager *pPager){
41563  int rc = SQLITE_OK;
41564  assert( pPager->eState==PAGER_OPEN );
41565  assert( pPager->eLock>=SHARED_LOCK );
41566
41567  if( !pPager->tempFile ){
41568    int isWal;                    /* True if WAL file exists */
41569    Pgno nPage;                   /* Size of the database file */
41570
41571    rc = pagerPagecount(pPager, &nPage);
41572    if( rc ) return rc;
41573    if( nPage==0 ){
41574      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
41575      isWal = 0;
41576    }else{
41577      rc = sqlite3OsAccess(
41578          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
41579      );
41580    }
41581    if( rc==SQLITE_OK ){
41582      if( isWal ){
41583        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
41584        rc = sqlite3PagerOpenWal(pPager, 0);
41585      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
41586        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
41587      }
41588    }
41589  }
41590  return rc;
41591}
41592#endif
41593
41594/*
41595** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
41596** the entire master journal file. The case pSavepoint==NULL occurs when
41597** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
41598** savepoint.
41599**
41600** When pSavepoint is not NULL (meaning a non-transaction savepoint is
41601** being rolled back), then the rollback consists of up to three stages,
41602** performed in the order specified:
41603**
41604**   * Pages are played back from the main journal starting at byte
41605**     offset PagerSavepoint.iOffset and continuing to
41606**     PagerSavepoint.iHdrOffset, or to the end of the main journal
41607**     file if PagerSavepoint.iHdrOffset is zero.
41608**
41609**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
41610**     back starting from the journal header immediately following
41611**     PagerSavepoint.iHdrOffset to the end of the main journal file.
41612**
41613**   * Pages are then played back from the sub-journal file, starting
41614**     with the PagerSavepoint.iSubRec and continuing to the end of
41615**     the journal file.
41616**
41617** Throughout the rollback process, each time a page is rolled back, the
41618** corresponding bit is set in a bitvec structure (variable pDone in the
41619** implementation below). This is used to ensure that a page is only
41620** rolled back the first time it is encountered in either journal.
41621**
41622** If pSavepoint is NULL, then pages are only played back from the main
41623** journal file. There is no need for a bitvec in this case.
41624**
41625** In either case, before playback commences the Pager.dbSize variable
41626** is reset to the value that it held at the start of the savepoint
41627** (or transaction). No page with a page-number greater than this value
41628** is played back. If one is encountered it is simply skipped.
41629*/
41630static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
41631  i64 szJ;                 /* Effective size of the main journal */
41632  i64 iHdrOff;             /* End of first segment of main-journal records */
41633  int rc = SQLITE_OK;      /* Return code */
41634  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
41635
41636  assert( pPager->eState!=PAGER_ERROR );
41637  assert( pPager->eState>=PAGER_WRITER_LOCKED );
41638
41639  /* Allocate a bitvec to use to store the set of pages rolled back */
41640  if( pSavepoint ){
41641    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
41642    if( !pDone ){
41643      return SQLITE_NOMEM;
41644    }
41645  }
41646
41647  /* Set the database size back to the value it was before the savepoint
41648  ** being reverted was opened.
41649  */
41650  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
41651  pPager->changeCountDone = pPager->tempFile;
41652
41653  if( !pSavepoint && pagerUseWal(pPager) ){
41654    return pagerRollbackWal(pPager);
41655  }
41656
41657  /* Use pPager->journalOff as the effective size of the main rollback
41658  ** journal.  The actual file might be larger than this in
41659  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
41660  ** past pPager->journalOff is off-limits to us.
41661  */
41662  szJ = pPager->journalOff;
41663  assert( pagerUseWal(pPager)==0 || szJ==0 );
41664
41665  /* Begin by rolling back records from the main journal starting at
41666  ** PagerSavepoint.iOffset and continuing to the next journal header.
41667  ** There might be records in the main journal that have a page number
41668  ** greater than the current database size (pPager->dbSize) but those
41669  ** will be skipped automatically.  Pages are added to pDone as they
41670  ** are played back.
41671  */
41672  if( pSavepoint && !pagerUseWal(pPager) ){
41673    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
41674    pPager->journalOff = pSavepoint->iOffset;
41675    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
41676      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
41677    }
41678    assert( rc!=SQLITE_DONE );
41679  }else{
41680    pPager->journalOff = 0;
41681  }
41682
41683  /* Continue rolling back records out of the main journal starting at
41684  ** the first journal header seen and continuing until the effective end
41685  ** of the main journal file.  Continue to skip out-of-range pages and
41686  ** continue adding pages rolled back to pDone.
41687  */
41688  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
41689    u32 ii;            /* Loop counter */
41690    u32 nJRec = 0;     /* Number of Journal Records */
41691    u32 dummy;
41692    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
41693    assert( rc!=SQLITE_DONE );
41694
41695    /*
41696    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
41697    ** test is related to ticket #2565.  See the discussion in the
41698    ** pager_playback() function for additional information.
41699    */
41700    if( nJRec==0
41701     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
41702    ){
41703      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
41704    }
41705    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
41706      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
41707    }
41708    assert( rc!=SQLITE_DONE );
41709  }
41710  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
41711
41712  /* Finally,  rollback pages from the sub-journal.  Page that were
41713  ** previously rolled back out of the main journal (and are hence in pDone)
41714  ** will be skipped.  Out-of-range pages are also skipped.
41715  */
41716  if( pSavepoint ){
41717    u32 ii;            /* Loop counter */
41718    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
41719
41720    if( pagerUseWal(pPager) ){
41721      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
41722    }
41723    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
41724      assert( offset==(i64)ii*(4+pPager->pageSize) );
41725      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
41726    }
41727    assert( rc!=SQLITE_DONE );
41728  }
41729
41730  sqlite3BitvecDestroy(pDone);
41731  if( rc==SQLITE_OK ){
41732    pPager->journalOff = szJ;
41733  }
41734
41735  return rc;
41736}
41737
41738/*
41739** Change the maximum number of in-memory pages that are allowed.
41740*/
41741SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
41742  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
41743}
41744
41745/*
41746** Free as much memory as possible from the pager.
41747*/
41748SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
41749  sqlite3PcacheShrink(pPager->pPCache);
41750}
41751
41752/*
41753** Adjust the robustness of the database to damage due to OS crashes
41754** or power failures by changing the number of syncs()s when writing
41755** the rollback journal.  There are three levels:
41756**
41757**    OFF       sqlite3OsSync() is never called.  This is the default
41758**              for temporary and transient files.
41759**
41760**    NORMAL    The journal is synced once before writes begin on the
41761**              database.  This is normally adequate protection, but
41762**              it is theoretically possible, though very unlikely,
41763**              that an inopertune power failure could leave the journal
41764**              in a state which would cause damage to the database
41765**              when it is rolled back.
41766**
41767**    FULL      The journal is synced twice before writes begin on the
41768**              database (with some additional information - the nRec field
41769**              of the journal header - being written in between the two
41770**              syncs).  If we assume that writing a
41771**              single disk sector is atomic, then this mode provides
41772**              assurance that the journal will not be corrupted to the
41773**              point of causing damage to the database during rollback.
41774**
41775** The above is for a rollback-journal mode.  For WAL mode, OFF continues
41776** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
41777** prior to the start of checkpoint and that the database file is synced
41778** at the conclusion of the checkpoint if the entire content of the WAL
41779** was written back into the database.  But no sync operations occur for
41780** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
41781** file is synced following each commit operation, in addition to the
41782** syncs associated with NORMAL.
41783**
41784** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
41785** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
41786** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
41787** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
41788** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
41789** synchronous=FULL versus synchronous=NORMAL setting determines when
41790** the xSync primitive is called and is relevant to all platforms.
41791**
41792** Numeric values associated with these states are OFF==1, NORMAL=2,
41793** and FULL=3.
41794*/
41795#ifndef SQLITE_OMIT_PAGER_PRAGMAS
41796SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
41797  Pager *pPager,        /* The pager to set safety level for */
41798  int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
41799  int bFullFsync,       /* PRAGMA fullfsync */
41800  int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
41801){
41802  assert( level>=1 && level<=3 );
41803  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
41804  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
41805  if( pPager->noSync ){
41806    pPager->syncFlags = 0;
41807    pPager->ckptSyncFlags = 0;
41808  }else if( bFullFsync ){
41809    pPager->syncFlags = SQLITE_SYNC_FULL;
41810    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
41811  }else if( bCkptFullFsync ){
41812    pPager->syncFlags = SQLITE_SYNC_NORMAL;
41813    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
41814  }else{
41815    pPager->syncFlags = SQLITE_SYNC_NORMAL;
41816    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
41817  }
41818  pPager->walSyncFlags = pPager->syncFlags;
41819  if( pPager->fullSync ){
41820    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
41821  }
41822}
41823#endif
41824
41825/*
41826** The following global variable is incremented whenever the library
41827** attempts to open a temporary file.  This information is used for
41828** testing and analysis only.
41829*/
41830#ifdef SQLITE_TEST
41831SQLITE_API int sqlite3_opentemp_count = 0;
41832#endif
41833
41834/*
41835** Open a temporary file.
41836**
41837** Write the file descriptor into *pFile. Return SQLITE_OK on success
41838** or some other error code if we fail. The OS will automatically
41839** delete the temporary file when it is closed.
41840**
41841** The flags passed to the VFS layer xOpen() call are those specified
41842** by parameter vfsFlags ORed with the following:
41843**
41844**     SQLITE_OPEN_READWRITE
41845**     SQLITE_OPEN_CREATE
41846**     SQLITE_OPEN_EXCLUSIVE
41847**     SQLITE_OPEN_DELETEONCLOSE
41848*/
41849static int pagerOpentemp(
41850  Pager *pPager,        /* The pager object */
41851  sqlite3_file *pFile,  /* Write the file descriptor here */
41852  int vfsFlags          /* Flags passed through to the VFS */
41853){
41854  int rc;               /* Return code */
41855
41856#ifdef SQLITE_TEST
41857  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
41858#endif
41859
41860  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
41861            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
41862  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
41863  assert( rc!=SQLITE_OK || isOpen(pFile) );
41864  return rc;
41865}
41866
41867/*
41868** Set the busy handler function.
41869**
41870** The pager invokes the busy-handler if sqlite3OsLock() returns
41871** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
41872** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
41873** lock. It does *not* invoke the busy handler when upgrading from
41874** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
41875** (which occurs during hot-journal rollback). Summary:
41876**
41877**   Transition                        | Invokes xBusyHandler
41878**   --------------------------------------------------------
41879**   NO_LOCK       -> SHARED_LOCK      | Yes
41880**   SHARED_LOCK   -> RESERVED_LOCK    | No
41881**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
41882**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
41883**
41884** If the busy-handler callback returns non-zero, the lock is
41885** retried. If it returns zero, then the SQLITE_BUSY error is
41886** returned to the caller of the pager API function.
41887*/
41888SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
41889  Pager *pPager,                       /* Pager object */
41890  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
41891  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
41892){
41893  pPager->xBusyHandler = xBusyHandler;
41894  pPager->pBusyHandlerArg = pBusyHandlerArg;
41895}
41896
41897/*
41898** Change the page size used by the Pager object. The new page size
41899** is passed in *pPageSize.
41900**
41901** If the pager is in the error state when this function is called, it
41902** is a no-op. The value returned is the error state error code (i.e.
41903** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
41904**
41905** Otherwise, if all of the following are true:
41906**
41907**   * the new page size (value of *pPageSize) is valid (a power
41908**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
41909**
41910**   * there are no outstanding page references, and
41911**
41912**   * the database is either not an in-memory database or it is
41913**     an in-memory database that currently consists of zero pages.
41914**
41915** then the pager object page size is set to *pPageSize.
41916**
41917** If the page size is changed, then this function uses sqlite3PagerMalloc()
41918** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
41919** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
41920** In all other cases, SQLITE_OK is returned.
41921**
41922** If the page size is not changed, either because one of the enumerated
41923** conditions above is not true, the pager was in error state when this
41924** function was called, or because the memory allocation attempt failed,
41925** then *pPageSize is set to the old, retained page size before returning.
41926*/
41927SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
41928  int rc = SQLITE_OK;
41929
41930  /* It is not possible to do a full assert_pager_state() here, as this
41931  ** function may be called from within PagerOpen(), before the state
41932  ** of the Pager object is internally consistent.
41933  **
41934  ** At one point this function returned an error if the pager was in
41935  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
41936  ** there is at least one outstanding page reference, this function
41937  ** is a no-op for that case anyhow.
41938  */
41939
41940  u32 pageSize = *pPageSize;
41941  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
41942  if( (pPager->memDb==0 || pPager->dbSize==0)
41943   && sqlite3PcacheRefCount(pPager->pPCache)==0
41944   && pageSize && pageSize!=(u32)pPager->pageSize
41945  ){
41946    char *pNew = NULL;             /* New temp space */
41947    i64 nByte = 0;
41948
41949    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
41950      rc = sqlite3OsFileSize(pPager->fd, &nByte);
41951    }
41952    if( rc==SQLITE_OK ){
41953      pNew = (char *)sqlite3PageMalloc(pageSize);
41954      if( !pNew ) rc = SQLITE_NOMEM;
41955    }
41956
41957    if( rc==SQLITE_OK ){
41958      pager_reset(pPager);
41959      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
41960      pPager->pageSize = pageSize;
41961      sqlite3PageFree(pPager->pTmpSpace);
41962      pPager->pTmpSpace = pNew;
41963      sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
41964    }
41965  }
41966
41967  *pPageSize = pPager->pageSize;
41968  if( rc==SQLITE_OK ){
41969    if( nReserve<0 ) nReserve = pPager->nReserve;
41970    assert( nReserve>=0 && nReserve<1000 );
41971    pPager->nReserve = (i16)nReserve;
41972    pagerReportSize(pPager);
41973  }
41974  return rc;
41975}
41976
41977/*
41978** Return a pointer to the "temporary page" buffer held internally
41979** by the pager.  This is a buffer that is big enough to hold the
41980** entire content of a database page.  This buffer is used internally
41981** during rollback and will be overwritten whenever a rollback
41982** occurs.  But other modules are free to use it too, as long as
41983** no rollbacks are happening.
41984*/
41985SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
41986  return pPager->pTmpSpace;
41987}
41988
41989/*
41990** Attempt to set the maximum database page count if mxPage is positive.
41991** Make no changes if mxPage is zero or negative.  And never reduce the
41992** maximum page count below the current size of the database.
41993**
41994** Regardless of mxPage, return the current maximum page count.
41995*/
41996SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
41997  if( mxPage>0 ){
41998    pPager->mxPgno = mxPage;
41999  }
42000  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
42001  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
42002  return pPager->mxPgno;
42003}
42004
42005/*
42006** The following set of routines are used to disable the simulated
42007** I/O error mechanism.  These routines are used to avoid simulated
42008** errors in places where we do not care about errors.
42009**
42010** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
42011** and generate no code.
42012*/
42013#ifdef SQLITE_TEST
42014SQLITE_API extern int sqlite3_io_error_pending;
42015SQLITE_API extern int sqlite3_io_error_hit;
42016static int saved_cnt;
42017void disable_simulated_io_errors(void){
42018  saved_cnt = sqlite3_io_error_pending;
42019  sqlite3_io_error_pending = -1;
42020}
42021void enable_simulated_io_errors(void){
42022  sqlite3_io_error_pending = saved_cnt;
42023}
42024#else
42025# define disable_simulated_io_errors()
42026# define enable_simulated_io_errors()
42027#endif
42028
42029/*
42030** Read the first N bytes from the beginning of the file into memory
42031** that pDest points to.
42032**
42033** If the pager was opened on a transient file (zFilename==""), or
42034** opened on a file less than N bytes in size, the output buffer is
42035** zeroed and SQLITE_OK returned. The rationale for this is that this
42036** function is used to read database headers, and a new transient or
42037** zero sized database has a header than consists entirely of zeroes.
42038**
42039** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
42040** the error code is returned to the caller and the contents of the
42041** output buffer undefined.
42042*/
42043SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
42044  int rc = SQLITE_OK;
42045  memset(pDest, 0, N);
42046  assert( isOpen(pPager->fd) || pPager->tempFile );
42047
42048  /* This routine is only called by btree immediately after creating
42049  ** the Pager object.  There has not been an opportunity to transition
42050  ** to WAL mode yet.
42051  */
42052  assert( !pagerUseWal(pPager) );
42053
42054  if( isOpen(pPager->fd) ){
42055    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
42056    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
42057    if( rc==SQLITE_IOERR_SHORT_READ ){
42058      rc = SQLITE_OK;
42059    }
42060  }
42061  return rc;
42062}
42063
42064/*
42065** This function may only be called when a read-transaction is open on
42066** the pager. It returns the total number of pages in the database.
42067**
42068** However, if the file is between 1 and <page-size> bytes in size, then
42069** this is considered a 1 page file.
42070*/
42071SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
42072  assert( pPager->eState>=PAGER_READER );
42073  assert( pPager->eState!=PAGER_WRITER_FINISHED );
42074  *pnPage = (int)pPager->dbSize;
42075}
42076
42077
42078/*
42079** Try to obtain a lock of type locktype on the database file. If
42080** a similar or greater lock is already held, this function is a no-op
42081** (returning SQLITE_OK immediately).
42082**
42083** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
42084** the busy callback if the lock is currently not available. Repeat
42085** until the busy callback returns false or until the attempt to
42086** obtain the lock succeeds.
42087**
42088** Return SQLITE_OK on success and an error code if we cannot obtain
42089** the lock. If the lock is obtained successfully, set the Pager.state
42090** variable to locktype before returning.
42091*/
42092static int pager_wait_on_lock(Pager *pPager, int locktype){
42093  int rc;                              /* Return code */
42094
42095  /* Check that this is either a no-op (because the requested lock is
42096  ** already held, or one of the transistions that the busy-handler
42097  ** may be invoked during, according to the comment above
42098  ** sqlite3PagerSetBusyhandler().
42099  */
42100  assert( (pPager->eLock>=locktype)
42101       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
42102       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
42103  );
42104
42105  do {
42106    rc = pagerLockDb(pPager, locktype);
42107  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
42108  return rc;
42109}
42110
42111/*
42112** Function assertTruncateConstraint(pPager) checks that one of the
42113** following is true for all dirty pages currently in the page-cache:
42114**
42115**   a) The page number is less than or equal to the size of the
42116**      current database image, in pages, OR
42117**
42118**   b) if the page content were written at this time, it would not
42119**      be necessary to write the current content out to the sub-journal
42120**      (as determined by function subjRequiresPage()).
42121**
42122** If the condition asserted by this function were not true, and the
42123** dirty page were to be discarded from the cache via the pagerStress()
42124** routine, pagerStress() would not write the current page content to
42125** the database file. If a savepoint transaction were rolled back after
42126** this happened, the correct behaviour would be to restore the current
42127** content of the page. However, since this content is not present in either
42128** the database file or the portion of the rollback journal and
42129** sub-journal rolled back the content could not be restored and the
42130** database image would become corrupt. It is therefore fortunate that
42131** this circumstance cannot arise.
42132*/
42133#if defined(SQLITE_DEBUG)
42134static void assertTruncateConstraintCb(PgHdr *pPg){
42135  assert( pPg->flags&PGHDR_DIRTY );
42136  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
42137}
42138static void assertTruncateConstraint(Pager *pPager){
42139  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
42140}
42141#else
42142# define assertTruncateConstraint(pPager)
42143#endif
42144
42145/*
42146** Truncate the in-memory database file image to nPage pages. This
42147** function does not actually modify the database file on disk. It
42148** just sets the internal state of the pager object so that the
42149** truncation will be done when the current transaction is committed.
42150*/
42151SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
42152  assert( pPager->dbSize>=nPage );
42153  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42154  pPager->dbSize = nPage;
42155  assertTruncateConstraint(pPager);
42156}
42157
42158
42159/*
42160** This function is called before attempting a hot-journal rollback. It
42161** syncs the journal file to disk, then sets pPager->journalHdr to the
42162** size of the journal file so that the pager_playback() routine knows
42163** that the entire journal file has been synced.
42164**
42165** Syncing a hot-journal to disk before attempting to roll it back ensures
42166** that if a power-failure occurs during the rollback, the process that
42167** attempts rollback following system recovery sees the same journal
42168** content as this process.
42169**
42170** If everything goes as planned, SQLITE_OK is returned. Otherwise,
42171** an SQLite error code.
42172*/
42173static int pagerSyncHotJournal(Pager *pPager){
42174  int rc = SQLITE_OK;
42175  if( !pPager->noSync ){
42176    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
42177  }
42178  if( rc==SQLITE_OK ){
42179    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
42180  }
42181  return rc;
42182}
42183
42184/*
42185** Shutdown the page cache.  Free all memory and close all files.
42186**
42187** If a transaction was in progress when this routine is called, that
42188** transaction is rolled back.  All outstanding pages are invalidated
42189** and their memory is freed.  Any attempt to use a page associated
42190** with this page cache after this function returns will likely
42191** result in a coredump.
42192**
42193** This function always succeeds. If a transaction is active an attempt
42194** is made to roll it back. If an error occurs during the rollback
42195** a hot journal may be left in the filesystem but no error is returned
42196** to the caller.
42197*/
42198SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
42199  u8 *pTmp = (u8 *)pPager->pTmpSpace;
42200
42201  assert( assert_pager_state(pPager) );
42202  disable_simulated_io_errors();
42203  sqlite3BeginBenignMalloc();
42204  /* pPager->errCode = 0; */
42205  pPager->exclusiveMode = 0;
42206#ifndef SQLITE_OMIT_WAL
42207  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
42208  pPager->pWal = 0;
42209#endif
42210  pager_reset(pPager);
42211  if( MEMDB ){
42212    pager_unlock(pPager);
42213  }else{
42214    /* If it is open, sync the journal file before calling UnlockAndRollback.
42215    ** If this is not done, then an unsynced portion of the open journal
42216    ** file may be played back into the database. If a power failure occurs
42217    ** while this is happening, the database could become corrupt.
42218    **
42219    ** If an error occurs while trying to sync the journal, shift the pager
42220    ** into the ERROR state. This causes UnlockAndRollback to unlock the
42221    ** database and close the journal file without attempting to roll it
42222    ** back or finalize it. The next database user will have to do hot-journal
42223    ** rollback before accessing the database file.
42224    */
42225    if( isOpen(pPager->jfd) ){
42226      pager_error(pPager, pagerSyncHotJournal(pPager));
42227    }
42228    pagerUnlockAndRollback(pPager);
42229  }
42230  sqlite3EndBenignMalloc();
42231  enable_simulated_io_errors();
42232  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
42233  IOTRACE(("CLOSE %p\n", pPager))
42234  sqlite3OsClose(pPager->jfd);
42235  sqlite3OsClose(pPager->fd);
42236  sqlite3PageFree(pTmp);
42237  sqlite3PcacheClose(pPager->pPCache);
42238
42239#ifdef SQLITE_HAS_CODEC
42240  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
42241#endif
42242
42243  assert( !pPager->aSavepoint && !pPager->pInJournal );
42244  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
42245
42246  sqlite3_free(pPager);
42247  return SQLITE_OK;
42248}
42249
42250#if !defined(NDEBUG) || defined(SQLITE_TEST)
42251/*
42252** Return the page number for page pPg.
42253*/
42254SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
42255  return pPg->pgno;
42256}
42257#endif
42258
42259/*
42260** Increment the reference count for page pPg.
42261*/
42262SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
42263  sqlite3PcacheRef(pPg);
42264}
42265
42266/*
42267** Sync the journal. In other words, make sure all the pages that have
42268** been written to the journal have actually reached the surface of the
42269** disk and can be restored in the event of a hot-journal rollback.
42270**
42271** If the Pager.noSync flag is set, then this function is a no-op.
42272** Otherwise, the actions required depend on the journal-mode and the
42273** device characteristics of the the file-system, as follows:
42274**
42275**   * If the journal file is an in-memory journal file, no action need
42276**     be taken.
42277**
42278**   * Otherwise, if the device does not support the SAFE_APPEND property,
42279**     then the nRec field of the most recently written journal header
42280**     is updated to contain the number of journal records that have
42281**     been written following it. If the pager is operating in full-sync
42282**     mode, then the journal file is synced before this field is updated.
42283**
42284**   * If the device does not support the SEQUENTIAL property, then
42285**     journal file is synced.
42286**
42287** Or, in pseudo-code:
42288**
42289**   if( NOT <in-memory journal> ){
42290**     if( NOT SAFE_APPEND ){
42291**       if( <full-sync mode> ) xSync(<journal file>);
42292**       <update nRec field>
42293**     }
42294**     if( NOT SEQUENTIAL ) xSync(<journal file>);
42295**   }
42296**
42297** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
42298** page currently held in memory before returning SQLITE_OK. If an IO
42299** error is encountered, then the IO error code is returned to the caller.
42300*/
42301static int syncJournal(Pager *pPager, int newHdr){
42302  int rc;                         /* Return code */
42303
42304  assert( pPager->eState==PAGER_WRITER_CACHEMOD
42305       || pPager->eState==PAGER_WRITER_DBMOD
42306  );
42307  assert( assert_pager_state(pPager) );
42308  assert( !pagerUseWal(pPager) );
42309
42310  rc = sqlite3PagerExclusiveLock(pPager);
42311  if( rc!=SQLITE_OK ) return rc;
42312
42313  if( !pPager->noSync ){
42314    assert( !pPager->tempFile );
42315    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
42316      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
42317      assert( isOpen(pPager->jfd) );
42318
42319      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
42320        /* This block deals with an obscure problem. If the last connection
42321        ** that wrote to this database was operating in persistent-journal
42322        ** mode, then the journal file may at this point actually be larger
42323        ** than Pager.journalOff bytes. If the next thing in the journal
42324        ** file happens to be a journal-header (written as part of the
42325        ** previous connection's transaction), and a crash or power-failure
42326        ** occurs after nRec is updated but before this connection writes
42327        ** anything else to the journal file (or commits/rolls back its
42328        ** transaction), then SQLite may become confused when doing the
42329        ** hot-journal rollback following recovery. It may roll back all
42330        ** of this connections data, then proceed to rolling back the old,
42331        ** out-of-date data that follows it. Database corruption.
42332        **
42333        ** To work around this, if the journal file does appear to contain
42334        ** a valid header following Pager.journalOff, then write a 0x00
42335        ** byte to the start of it to prevent it from being recognized.
42336        **
42337        ** Variable iNextHdrOffset is set to the offset at which this
42338        ** problematic header will occur, if it exists. aMagic is used
42339        ** as a temporary buffer to inspect the first couple of bytes of
42340        ** the potential journal header.
42341        */
42342        i64 iNextHdrOffset;
42343        u8 aMagic[8];
42344        u8 zHeader[sizeof(aJournalMagic)+4];
42345
42346        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
42347        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
42348
42349        iNextHdrOffset = journalHdrOffset(pPager);
42350        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
42351        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
42352          static const u8 zerobyte = 0;
42353          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
42354        }
42355        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
42356          return rc;
42357        }
42358
42359        /* Write the nRec value into the journal file header. If in
42360        ** full-synchronous mode, sync the journal first. This ensures that
42361        ** all data has really hit the disk before nRec is updated to mark
42362        ** it as a candidate for rollback.
42363        **
42364        ** This is not required if the persistent media supports the
42365        ** SAFE_APPEND property. Because in this case it is not possible
42366        ** for garbage data to be appended to the file, the nRec field
42367        ** is populated with 0xFFFFFFFF when the journal header is written
42368        ** and never needs to be updated.
42369        */
42370        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
42371          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
42372          IOTRACE(("JSYNC %p\n", pPager))
42373          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
42374          if( rc!=SQLITE_OK ) return rc;
42375        }
42376        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
42377        rc = sqlite3OsWrite(
42378            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
42379        );
42380        if( rc!=SQLITE_OK ) return rc;
42381      }
42382      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
42383        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
42384        IOTRACE(("JSYNC %p\n", pPager))
42385        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
42386          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
42387        );
42388        if( rc!=SQLITE_OK ) return rc;
42389      }
42390
42391      pPager->journalHdr = pPager->journalOff;
42392      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
42393        pPager->nRec = 0;
42394        rc = writeJournalHdr(pPager);
42395        if( rc!=SQLITE_OK ) return rc;
42396      }
42397    }else{
42398      pPager->journalHdr = pPager->journalOff;
42399    }
42400  }
42401
42402  /* Unless the pager is in noSync mode, the journal file was just
42403  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
42404  ** all pages.
42405  */
42406  sqlite3PcacheClearSyncFlags(pPager->pPCache);
42407  pPager->eState = PAGER_WRITER_DBMOD;
42408  assert( assert_pager_state(pPager) );
42409  return SQLITE_OK;
42410}
42411
42412/*
42413** The argument is the first in a linked list of dirty pages connected
42414** by the PgHdr.pDirty pointer. This function writes each one of the
42415** in-memory pages in the list to the database file. The argument may
42416** be NULL, representing an empty list. In this case this function is
42417** a no-op.
42418**
42419** The pager must hold at least a RESERVED lock when this function
42420** is called. Before writing anything to the database file, this lock
42421** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
42422** SQLITE_BUSY is returned and no data is written to the database file.
42423**
42424** If the pager is a temp-file pager and the actual file-system file
42425** is not yet open, it is created and opened before any data is
42426** written out.
42427**
42428** Once the lock has been upgraded and, if necessary, the file opened,
42429** the pages are written out to the database file in list order. Writing
42430** a page is skipped if it meets either of the following criteria:
42431**
42432**   * The page number is greater than Pager.dbSize, or
42433**   * The PGHDR_DONT_WRITE flag is set on the page.
42434**
42435** If writing out a page causes the database file to grow, Pager.dbFileSize
42436** is updated accordingly. If page 1 is written out, then the value cached
42437** in Pager.dbFileVers[] is updated to match the new value stored in
42438** the database file.
42439**
42440** If everything is successful, SQLITE_OK is returned. If an IO error
42441** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
42442** be obtained, SQLITE_BUSY is returned.
42443*/
42444static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
42445  int rc = SQLITE_OK;                  /* Return code */
42446
42447  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
42448  assert( !pagerUseWal(pPager) );
42449  assert( pPager->eState==PAGER_WRITER_DBMOD );
42450  assert( pPager->eLock==EXCLUSIVE_LOCK );
42451
42452  /* If the file is a temp-file has not yet been opened, open it now. It
42453  ** is not possible for rc to be other than SQLITE_OK if this branch
42454  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
42455  */
42456  if( !isOpen(pPager->fd) ){
42457    assert( pPager->tempFile && rc==SQLITE_OK );
42458    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
42459  }
42460
42461  /* Before the first write, give the VFS a hint of what the final
42462  ** file size will be.
42463  */
42464  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
42465  if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
42466    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
42467    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
42468    pPager->dbHintSize = pPager->dbSize;
42469  }
42470
42471  while( rc==SQLITE_OK && pList ){
42472    Pgno pgno = pList->pgno;
42473
42474    /* If there are dirty pages in the page cache with page numbers greater
42475    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
42476    ** make the file smaller (presumably by auto-vacuum code). Do not write
42477    ** any such pages to the file.
42478    **
42479    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
42480    ** set (set by sqlite3PagerDontWrite()).
42481    */
42482    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
42483      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
42484      char *pData;                                   /* Data to write */
42485
42486      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
42487      if( pList->pgno==1 ) pager_write_changecounter(pList);
42488
42489      /* Encode the database */
42490      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
42491
42492      /* Write out the page data. */
42493      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
42494
42495      /* If page 1 was just written, update Pager.dbFileVers to match
42496      ** the value now stored in the database file. If writing this
42497      ** page caused the database file to grow, update dbFileSize.
42498      */
42499      if( pgno==1 ){
42500        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
42501      }
42502      if( pgno>pPager->dbFileSize ){
42503        pPager->dbFileSize = pgno;
42504      }
42505
42506      /* Update any backup objects copying the contents of this pager. */
42507      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
42508
42509      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
42510                   PAGERID(pPager), pgno, pager_pagehash(pList)));
42511      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
42512      PAGER_INCR(sqlite3_pager_writedb_count);
42513      PAGER_INCR(pPager->nWrite);
42514    }else{
42515      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
42516    }
42517    pager_set_pagehash(pList);
42518    pList = pList->pDirty;
42519  }
42520
42521  return rc;
42522}
42523
42524/*
42525** Ensure that the sub-journal file is open. If it is already open, this
42526** function is a no-op.
42527**
42528** SQLITE_OK is returned if everything goes according to plan. An
42529** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
42530** fails.
42531*/
42532static int openSubJournal(Pager *pPager){
42533  int rc = SQLITE_OK;
42534  if( !isOpen(pPager->sjfd) ){
42535    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
42536      sqlite3MemJournalOpen(pPager->sjfd);
42537    }else{
42538      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
42539    }
42540  }
42541  return rc;
42542}
42543
42544/*
42545** Append a record of the current state of page pPg to the sub-journal.
42546** It is the callers responsibility to use subjRequiresPage() to check
42547** that it is really required before calling this function.
42548**
42549** If successful, set the bit corresponding to pPg->pgno in the bitvecs
42550** for all open savepoints before returning.
42551**
42552** This function returns SQLITE_OK if everything is successful, an IO
42553** error code if the attempt to write to the sub-journal fails, or
42554** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
42555** bitvec.
42556*/
42557static int subjournalPage(PgHdr *pPg){
42558  int rc = SQLITE_OK;
42559  Pager *pPager = pPg->pPager;
42560  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
42561
42562    /* Open the sub-journal, if it has not already been opened */
42563    assert( pPager->useJournal );
42564    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
42565    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
42566    assert( pagerUseWal(pPager)
42567         || pageInJournal(pPg)
42568         || pPg->pgno>pPager->dbOrigSize
42569    );
42570    rc = openSubJournal(pPager);
42571
42572    /* If the sub-journal was opened successfully (or was already open),
42573    ** write the journal record into the file.  */
42574    if( rc==SQLITE_OK ){
42575      void *pData = pPg->pData;
42576      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
42577      char *pData2;
42578
42579      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42580      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
42581      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
42582      if( rc==SQLITE_OK ){
42583        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
42584      }
42585    }
42586  }
42587  if( rc==SQLITE_OK ){
42588    pPager->nSubRec++;
42589    assert( pPager->nSavepoint>0 );
42590    rc = addToSavepointBitvecs(pPager, pPg->pgno);
42591  }
42592  return rc;
42593}
42594
42595/*
42596** This function is called by the pcache layer when it has reached some
42597** soft memory limit. The first argument is a pointer to a Pager object
42598** (cast as a void*). The pager is always 'purgeable' (not an in-memory
42599** database). The second argument is a reference to a page that is
42600** currently dirty but has no outstanding references. The page
42601** is always associated with the Pager object passed as the first
42602** argument.
42603**
42604** The job of this function is to make pPg clean by writing its contents
42605** out to the database file, if possible. This may involve syncing the
42606** journal file.
42607**
42608** If successful, sqlite3PcacheMakeClean() is called on the page and
42609** SQLITE_OK returned. If an IO error occurs while trying to make the
42610** page clean, the IO error code is returned. If the page cannot be
42611** made clean for some other reason, but no error occurs, then SQLITE_OK
42612** is returned by sqlite3PcacheMakeClean() is not called.
42613*/
42614static int pagerStress(void *p, PgHdr *pPg){
42615  Pager *pPager = (Pager *)p;
42616  int rc = SQLITE_OK;
42617
42618  assert( pPg->pPager==pPager );
42619  assert( pPg->flags&PGHDR_DIRTY );
42620
42621  /* The doNotSyncSpill flag is set during times when doing a sync of
42622  ** journal (and adding a new header) is not allowed.  This occurs
42623  ** during calls to sqlite3PagerWrite() while trying to journal multiple
42624  ** pages belonging to the same sector.
42625  **
42626  ** The doNotSpill flag inhibits all cache spilling regardless of whether
42627  ** or not a sync is required.  This is set during a rollback.
42628  **
42629  ** Spilling is also prohibited when in an error state since that could
42630  ** lead to database corruption.   In the current implementaton it
42631  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
42632  ** while in the error state, hence it is impossible for this routine to
42633  ** be called in the error state.  Nevertheless, we include a NEVER()
42634  ** test for the error state as a safeguard against future changes.
42635  */
42636  if( NEVER(pPager->errCode) ) return SQLITE_OK;
42637  if( pPager->doNotSpill ) return SQLITE_OK;
42638  if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
42639    return SQLITE_OK;
42640  }
42641
42642  pPg->pDirty = 0;
42643  if( pagerUseWal(pPager) ){
42644    /* Write a single frame for this page to the log. */
42645    if( subjRequiresPage(pPg) ){
42646      rc = subjournalPage(pPg);
42647    }
42648    if( rc==SQLITE_OK ){
42649      rc = pagerWalFrames(pPager, pPg, 0, 0);
42650    }
42651  }else{
42652
42653    /* Sync the journal file if required. */
42654    if( pPg->flags&PGHDR_NEED_SYNC
42655     || pPager->eState==PAGER_WRITER_CACHEMOD
42656    ){
42657      rc = syncJournal(pPager, 1);
42658    }
42659
42660    /* If the page number of this page is larger than the current size of
42661    ** the database image, it may need to be written to the sub-journal.
42662    ** This is because the call to pager_write_pagelist() below will not
42663    ** actually write data to the file in this case.
42664    **
42665    ** Consider the following sequence of events:
42666    **
42667    **   BEGIN;
42668    **     <journal page X>
42669    **     <modify page X>
42670    **     SAVEPOINT sp;
42671    **       <shrink database file to Y pages>
42672    **       pagerStress(page X)
42673    **     ROLLBACK TO sp;
42674    **
42675    ** If (X>Y), then when pagerStress is called page X will not be written
42676    ** out to the database file, but will be dropped from the cache. Then,
42677    ** following the "ROLLBACK TO sp" statement, reading page X will read
42678    ** data from the database file. This will be the copy of page X as it
42679    ** was when the transaction started, not as it was when "SAVEPOINT sp"
42680    ** was executed.
42681    **
42682    ** The solution is to write the current data for page X into the
42683    ** sub-journal file now (if it is not already there), so that it will
42684    ** be restored to its current value when the "ROLLBACK TO sp" is
42685    ** executed.
42686    */
42687    if( NEVER(
42688        rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
42689    ) ){
42690      rc = subjournalPage(pPg);
42691    }
42692
42693    /* Write the contents of the page out to the database file. */
42694    if( rc==SQLITE_OK ){
42695      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
42696      rc = pager_write_pagelist(pPager, pPg);
42697    }
42698  }
42699
42700  /* Mark the page as clean. */
42701  if( rc==SQLITE_OK ){
42702    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
42703    sqlite3PcacheMakeClean(pPg);
42704  }
42705
42706  return pager_error(pPager, rc);
42707}
42708
42709
42710/*
42711** Allocate and initialize a new Pager object and put a pointer to it
42712** in *ppPager. The pager should eventually be freed by passing it
42713** to sqlite3PagerClose().
42714**
42715** The zFilename argument is the path to the database file to open.
42716** If zFilename is NULL then a randomly-named temporary file is created
42717** and used as the file to be cached. Temporary files are be deleted
42718** automatically when they are closed. If zFilename is ":memory:" then
42719** all information is held in cache. It is never written to disk.
42720** This can be used to implement an in-memory database.
42721**
42722** The nExtra parameter specifies the number of bytes of space allocated
42723** along with each page reference. This space is available to the user
42724** via the sqlite3PagerGetExtra() API.
42725**
42726** The flags argument is used to specify properties that affect the
42727** operation of the pager. It should be passed some bitwise combination
42728** of the PAGER_* flags.
42729**
42730** The vfsFlags parameter is a bitmask to pass to the flags parameter
42731** of the xOpen() method of the supplied VFS when opening files.
42732**
42733** If the pager object is allocated and the specified file opened
42734** successfully, SQLITE_OK is returned and *ppPager set to point to
42735** the new pager object. If an error occurs, *ppPager is set to NULL
42736** and error code returned. This function may return SQLITE_NOMEM
42737** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
42738** various SQLITE_IO_XXX errors.
42739*/
42740SQLITE_PRIVATE int sqlite3PagerOpen(
42741  sqlite3_vfs *pVfs,       /* The virtual file system to use */
42742  Pager **ppPager,         /* OUT: Return the Pager structure here */
42743  const char *zFilename,   /* Name of the database file to open */
42744  int nExtra,              /* Extra bytes append to each in-memory page */
42745  int flags,               /* flags controlling this file */
42746  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
42747  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
42748){
42749  u8 *pPtr;
42750  Pager *pPager = 0;       /* Pager object to allocate and return */
42751  int rc = SQLITE_OK;      /* Return code */
42752  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
42753  int memDb = 0;           /* True if this is an in-memory file */
42754  int readOnly = 0;        /* True if this is a read-only file */
42755  int journalFileSize;     /* Bytes to allocate for each journal fd */
42756  char *zPathname = 0;     /* Full path to database file */
42757  int nPathname = 0;       /* Number of bytes in zPathname */
42758  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
42759  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
42760  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
42761  const char *zUri = 0;    /* URI args to copy */
42762  int nUri = 0;            /* Number of bytes of URI args at *zUri */
42763
42764  /* Figure out how much space is required for each journal file-handle
42765  ** (there are two of them, the main journal and the sub-journal). This
42766  ** is the maximum space required for an in-memory journal file handle
42767  ** and a regular journal file-handle. Note that a "regular journal-handle"
42768  ** may be a wrapper capable of caching the first portion of the journal
42769  ** file in memory to implement the atomic-write optimization (see
42770  ** source file journal.c).
42771  */
42772  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
42773    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
42774  }else{
42775    journalFileSize = ROUND8(sqlite3MemJournalSize());
42776  }
42777
42778  /* Set the output variable to NULL in case an error occurs. */
42779  *ppPager = 0;
42780
42781#ifndef SQLITE_OMIT_MEMORYDB
42782  if( flags & PAGER_MEMORY ){
42783    memDb = 1;
42784    zFilename = 0;
42785  }
42786#endif
42787
42788  /* Compute and store the full pathname in an allocated buffer pointed
42789  ** to by zPathname, length nPathname. Or, if this is a temporary file,
42790  ** leave both nPathname and zPathname set to 0.
42791  */
42792  if( zFilename && zFilename[0] ){
42793    const char *z;
42794    nPathname = pVfs->mxPathname+1;
42795    zPathname = sqlite3Malloc(nPathname*2);
42796    if( zPathname==0 ){
42797      return SQLITE_NOMEM;
42798    }
42799    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
42800    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
42801    nPathname = sqlite3Strlen30(zPathname);
42802    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
42803    while( *z ){
42804      z += sqlite3Strlen30(z)+1;
42805      z += sqlite3Strlen30(z)+1;
42806    }
42807    nUri = (int)(&z[1] - zUri);
42808    assert( nUri>=0 );
42809    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
42810      /* This branch is taken when the journal path required by
42811      ** the database being opened will be more than pVfs->mxPathname
42812      ** bytes in length. This means the database cannot be opened,
42813      ** as it will not be possible to open the journal file or even
42814      ** check for a hot-journal before reading.
42815      */
42816      rc = SQLITE_CANTOPEN_BKPT;
42817    }
42818    if( rc!=SQLITE_OK ){
42819      sqlite3_free(zPathname);
42820      return rc;
42821    }
42822  }
42823
42824  /* Allocate memory for the Pager structure, PCache object, the
42825  ** three file descriptors, the database file name and the journal
42826  ** file name. The layout in memory is as follows:
42827  **
42828  **     Pager object                    (sizeof(Pager) bytes)
42829  **     PCache object                   (sqlite3PcacheSize() bytes)
42830  **     Database file handle            (pVfs->szOsFile bytes)
42831  **     Sub-journal file handle         (journalFileSize bytes)
42832  **     Main journal file handle        (journalFileSize bytes)
42833  **     Database file name              (nPathname+1 bytes)
42834  **     Journal file name               (nPathname+8+1 bytes)
42835  */
42836  pPtr = (u8 *)sqlite3MallocZero(
42837    ROUND8(sizeof(*pPager)) +      /* Pager structure */
42838    ROUND8(pcacheSize) +           /* PCache object */
42839    ROUND8(pVfs->szOsFile) +       /* The main db file */
42840    journalFileSize * 2 +          /* The two journal files */
42841    nPathname + 1 + nUri +         /* zFilename */
42842    nPathname + 8 + 2              /* zJournal */
42843#ifndef SQLITE_OMIT_WAL
42844    + nPathname + 4 + 2            /* zWal */
42845#endif
42846  );
42847  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
42848  if( !pPtr ){
42849    sqlite3_free(zPathname);
42850    return SQLITE_NOMEM;
42851  }
42852  pPager =              (Pager*)(pPtr);
42853  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
42854  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
42855  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
42856  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
42857  pPager->zFilename =    (char*)(pPtr += journalFileSize);
42858  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
42859
42860  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
42861  if( zPathname ){
42862    assert( nPathname>0 );
42863    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
42864    memcpy(pPager->zFilename, zPathname, nPathname);
42865    memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
42866    memcpy(pPager->zJournal, zPathname, nPathname);
42867    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+1);
42868    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
42869#ifndef SQLITE_OMIT_WAL
42870    pPager->zWal = &pPager->zJournal[nPathname+8+1];
42871    memcpy(pPager->zWal, zPathname, nPathname);
42872    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
42873    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
42874#endif
42875    sqlite3_free(zPathname);
42876  }
42877  pPager->pVfs = pVfs;
42878  pPager->vfsFlags = vfsFlags;
42879
42880  /* Open the pager file.
42881  */
42882  if( zFilename && zFilename[0] ){
42883    int fout = 0;                    /* VFS flags returned by xOpen() */
42884    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
42885    assert( !memDb );
42886    readOnly = (fout&SQLITE_OPEN_READONLY);
42887
42888    /* If the file was successfully opened for read/write access,
42889    ** choose a default page size in case we have to create the
42890    ** database file. The default page size is the maximum of:
42891    **
42892    **    + SQLITE_DEFAULT_PAGE_SIZE,
42893    **    + The value returned by sqlite3OsSectorSize()
42894    **    + The largest page size that can be written atomically.
42895    */
42896    if( rc==SQLITE_OK && !readOnly ){
42897      setSectorSize(pPager);
42898      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
42899      if( szPageDflt<pPager->sectorSize ){
42900        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
42901          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
42902        }else{
42903          szPageDflt = (u32)pPager->sectorSize;
42904        }
42905      }
42906#ifdef SQLITE_ENABLE_ATOMIC_WRITE
42907      {
42908        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
42909        int ii;
42910        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
42911        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
42912        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
42913        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
42914          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
42915            szPageDflt = ii;
42916          }
42917        }
42918      }
42919#endif
42920    }
42921  }else{
42922    /* If a temporary file is requested, it is not opened immediately.
42923    ** In this case we accept the default page size and delay actually
42924    ** opening the file until the first call to OsWrite().
42925    **
42926    ** This branch is also run for an in-memory database. An in-memory
42927    ** database is the same as a temp-file that is never written out to
42928    ** disk and uses an in-memory rollback journal.
42929    */
42930    tempFile = 1;
42931    pPager->eState = PAGER_READER;
42932    pPager->eLock = EXCLUSIVE_LOCK;
42933    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
42934  }
42935
42936  /* The following call to PagerSetPagesize() serves to set the value of
42937  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
42938  */
42939  if( rc==SQLITE_OK ){
42940    assert( pPager->memDb==0 );
42941    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
42942    testcase( rc!=SQLITE_OK );
42943  }
42944
42945  /* If an error occurred in either of the blocks above, free the
42946  ** Pager structure and close the file.
42947  */
42948  if( rc!=SQLITE_OK ){
42949    assert( !pPager->pTmpSpace );
42950    sqlite3OsClose(pPager->fd);
42951    sqlite3_free(pPager);
42952    return rc;
42953  }
42954
42955  /* Initialize the PCache object. */
42956  assert( nExtra<1000 );
42957  nExtra = ROUND8(nExtra);
42958  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
42959                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
42960
42961  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
42962  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
42963
42964  pPager->useJournal = (u8)useJournal;
42965  /* pPager->stmtOpen = 0; */
42966  /* pPager->stmtInUse = 0; */
42967  /* pPager->nRef = 0; */
42968  /* pPager->stmtSize = 0; */
42969  /* pPager->stmtJSize = 0; */
42970  /* pPager->nPage = 0; */
42971  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
42972  /* pPager->state = PAGER_UNLOCK; */
42973#if 0
42974  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
42975#endif
42976  /* pPager->errMask = 0; */
42977  pPager->tempFile = (u8)tempFile;
42978  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
42979          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
42980  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
42981  pPager->exclusiveMode = (u8)tempFile;
42982  pPager->changeCountDone = pPager->tempFile;
42983  pPager->memDb = (u8)memDb;
42984  pPager->readOnly = (u8)readOnly;
42985  assert( useJournal || pPager->tempFile );
42986  pPager->noSync = pPager->tempFile;
42987  if( pPager->noSync ){
42988    assert( pPager->fullSync==0 );
42989    assert( pPager->syncFlags==0 );
42990    assert( pPager->walSyncFlags==0 );
42991    assert( pPager->ckptSyncFlags==0 );
42992  }else{
42993    pPager->fullSync = 1;
42994    pPager->syncFlags = SQLITE_SYNC_NORMAL;
42995    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
42996    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
42997  }
42998  /* pPager->pFirst = 0; */
42999  /* pPager->pFirstSynced = 0; */
43000  /* pPager->pLast = 0; */
43001  pPager->nExtra = (u16)nExtra;
43002  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
43003  assert( isOpen(pPager->fd) || tempFile );
43004  setSectorSize(pPager);
43005  if( !useJournal ){
43006    pPager->journalMode = PAGER_JOURNALMODE_OFF;
43007  }else if( memDb ){
43008    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
43009  }
43010  /* pPager->xBusyHandler = 0; */
43011  /* pPager->pBusyHandlerArg = 0; */
43012  pPager->xReiniter = xReinit;
43013  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
43014
43015  *ppPager = pPager;
43016  return SQLITE_OK;
43017}
43018
43019
43020
43021/*
43022** This function is called after transitioning from PAGER_UNLOCK to
43023** PAGER_SHARED state. It tests if there is a hot journal present in
43024** the file-system for the given pager. A hot journal is one that
43025** needs to be played back. According to this function, a hot-journal
43026** file exists if the following criteria are met:
43027**
43028**   * The journal file exists in the file system, and
43029**   * No process holds a RESERVED or greater lock on the database file, and
43030**   * The database file itself is greater than 0 bytes in size, and
43031**   * The first byte of the journal file exists and is not 0x00.
43032**
43033** If the current size of the database file is 0 but a journal file
43034** exists, that is probably an old journal left over from a prior
43035** database with the same name. In this case the journal file is
43036** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
43037** is returned.
43038**
43039** This routine does not check if there is a master journal filename
43040** at the end of the file. If there is, and that master journal file
43041** does not exist, then the journal file is not really hot. In this
43042** case this routine will return a false-positive. The pager_playback()
43043** routine will discover that the journal file is not really hot and
43044** will not roll it back.
43045**
43046** If a hot-journal file is found to exist, *pExists is set to 1 and
43047** SQLITE_OK returned. If no hot-journal file is present, *pExists is
43048** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
43049** to determine whether or not a hot-journal file exists, the IO error
43050** code is returned and the value of *pExists is undefined.
43051*/
43052static int hasHotJournal(Pager *pPager, int *pExists){
43053  sqlite3_vfs * const pVfs = pPager->pVfs;
43054  int rc = SQLITE_OK;           /* Return code */
43055  int exists = 1;               /* True if a journal file is present */
43056  int jrnlOpen = !!isOpen(pPager->jfd);
43057
43058  assert( pPager->useJournal );
43059  assert( isOpen(pPager->fd) );
43060  assert( pPager->eState==PAGER_OPEN );
43061
43062  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
43063    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
43064  ));
43065
43066  *pExists = 0;
43067  if( !jrnlOpen ){
43068    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
43069  }
43070  if( rc==SQLITE_OK && exists ){
43071    int locked = 0;             /* True if some process holds a RESERVED lock */
43072
43073    /* Race condition here:  Another process might have been holding the
43074    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
43075    ** call above, but then delete the journal and drop the lock before
43076    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
43077    ** is the case, this routine might think there is a hot journal when
43078    ** in fact there is none.  This results in a false-positive which will
43079    ** be dealt with by the playback routine.  Ticket #3883.
43080    */
43081    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
43082    if( rc==SQLITE_OK && !locked ){
43083      Pgno nPage;                 /* Number of pages in database file */
43084
43085      /* Check the size of the database file. If it consists of 0 pages,
43086      ** then delete the journal file. See the header comment above for
43087      ** the reasoning here.  Delete the obsolete journal file under
43088      ** a RESERVED lock to avoid race conditions and to avoid violating
43089      ** [H33020].
43090      */
43091      rc = pagerPagecount(pPager, &nPage);
43092      if( rc==SQLITE_OK ){
43093        if( nPage==0 ){
43094          sqlite3BeginBenignMalloc();
43095          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
43096            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
43097            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
43098          }
43099          sqlite3EndBenignMalloc();
43100        }else{
43101          /* The journal file exists and no other connection has a reserved
43102          ** or greater lock on the database file. Now check that there is
43103          ** at least one non-zero bytes at the start of the journal file.
43104          ** If there is, then we consider this journal to be hot. If not,
43105          ** it can be ignored.
43106          */
43107          if( !jrnlOpen ){
43108            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
43109            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
43110          }
43111          if( rc==SQLITE_OK ){
43112            u8 first = 0;
43113            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
43114            if( rc==SQLITE_IOERR_SHORT_READ ){
43115              rc = SQLITE_OK;
43116            }
43117            if( !jrnlOpen ){
43118              sqlite3OsClose(pPager->jfd);
43119            }
43120            *pExists = (first!=0);
43121          }else if( rc==SQLITE_CANTOPEN ){
43122            /* If we cannot open the rollback journal file in order to see if
43123            ** its has a zero header, that might be due to an I/O error, or
43124            ** it might be due to the race condition described above and in
43125            ** ticket #3883.  Either way, assume that the journal is hot.
43126            ** This might be a false positive.  But if it is, then the
43127            ** automatic journal playback and recovery mechanism will deal
43128            ** with it under an EXCLUSIVE lock where we do not need to
43129            ** worry so much with race conditions.
43130            */
43131            *pExists = 1;
43132            rc = SQLITE_OK;
43133          }
43134        }
43135      }
43136    }
43137  }
43138
43139  return rc;
43140}
43141
43142/*
43143** This function is called to obtain a shared lock on the database file.
43144** It is illegal to call sqlite3PagerAcquire() until after this function
43145** has been successfully called. If a shared-lock is already held when
43146** this function is called, it is a no-op.
43147**
43148** The following operations are also performed by this function.
43149**
43150**   1) If the pager is currently in PAGER_OPEN state (no lock held
43151**      on the database file), then an attempt is made to obtain a
43152**      SHARED lock on the database file. Immediately after obtaining
43153**      the SHARED lock, the file-system is checked for a hot-journal,
43154**      which is played back if present. Following any hot-journal
43155**      rollback, the contents of the cache are validated by checking
43156**      the 'change-counter' field of the database file header and
43157**      discarded if they are found to be invalid.
43158**
43159**   2) If the pager is running in exclusive-mode, and there are currently
43160**      no outstanding references to any pages, and is in the error state,
43161**      then an attempt is made to clear the error state by discarding
43162**      the contents of the page cache and rolling back any open journal
43163**      file.
43164**
43165** If everything is successful, SQLITE_OK is returned. If an IO error
43166** occurs while locking the database, checking for a hot-journal file or
43167** rolling back a journal file, the IO error code is returned.
43168*/
43169SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
43170  int rc = SQLITE_OK;                /* Return code */
43171
43172  /* This routine is only called from b-tree and only when there are no
43173  ** outstanding pages. This implies that the pager state should either
43174  ** be OPEN or READER. READER is only possible if the pager is or was in
43175  ** exclusive access mode.
43176  */
43177  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
43178  assert( assert_pager_state(pPager) );
43179  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
43180  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
43181
43182  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
43183    int bHotJournal = 1;          /* True if there exists a hot journal-file */
43184
43185    assert( !MEMDB );
43186
43187    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
43188    if( rc!=SQLITE_OK ){
43189      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
43190      goto failed;
43191    }
43192
43193    /* If a journal file exists, and there is no RESERVED lock on the
43194    ** database file, then it either needs to be played back or deleted.
43195    */
43196    if( pPager->eLock<=SHARED_LOCK ){
43197      rc = hasHotJournal(pPager, &bHotJournal);
43198    }
43199    if( rc!=SQLITE_OK ){
43200      goto failed;
43201    }
43202    if( bHotJournal ){
43203      /* Get an EXCLUSIVE lock on the database file. At this point it is
43204      ** important that a RESERVED lock is not obtained on the way to the
43205      ** EXCLUSIVE lock. If it were, another process might open the
43206      ** database file, detect the RESERVED lock, and conclude that the
43207      ** database is safe to read while this process is still rolling the
43208      ** hot-journal back.
43209      **
43210      ** Because the intermediate RESERVED lock is not requested, any
43211      ** other process attempting to access the database file will get to
43212      ** this point in the code and fail to obtain its own EXCLUSIVE lock
43213      ** on the database file.
43214      **
43215      ** Unless the pager is in locking_mode=exclusive mode, the lock is
43216      ** downgraded to SHARED_LOCK before this function returns.
43217      */
43218      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43219      if( rc!=SQLITE_OK ){
43220        goto failed;
43221      }
43222
43223      /* If it is not already open and the file exists on disk, open the
43224      ** journal for read/write access. Write access is required because
43225      ** in exclusive-access mode the file descriptor will be kept open
43226      ** and possibly used for a transaction later on. Also, write-access
43227      ** is usually required to finalize the journal in journal_mode=persist
43228      ** mode (and also for journal_mode=truncate on some systems).
43229      **
43230      ** If the journal does not exist, it usually means that some
43231      ** other connection managed to get in and roll it back before
43232      ** this connection obtained the exclusive lock above. Or, it
43233      ** may mean that the pager was in the error-state when this
43234      ** function was called and the journal file does not exist.
43235      */
43236      if( !isOpen(pPager->jfd) ){
43237        sqlite3_vfs * const pVfs = pPager->pVfs;
43238        int bExists;              /* True if journal file exists */
43239        rc = sqlite3OsAccess(
43240            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
43241        if( rc==SQLITE_OK && bExists ){
43242          int fout = 0;
43243          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
43244          assert( !pPager->tempFile );
43245          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
43246          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
43247          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
43248            rc = SQLITE_CANTOPEN_BKPT;
43249            sqlite3OsClose(pPager->jfd);
43250          }
43251        }
43252      }
43253
43254      /* Playback and delete the journal.  Drop the database write
43255      ** lock and reacquire the read lock. Purge the cache before
43256      ** playing back the hot-journal so that we don't end up with
43257      ** an inconsistent cache.  Sync the hot journal before playing
43258      ** it back since the process that crashed and left the hot journal
43259      ** probably did not sync it and we are required to always sync
43260      ** the journal before playing it back.
43261      */
43262      if( isOpen(pPager->jfd) ){
43263        assert( rc==SQLITE_OK );
43264        rc = pagerSyncHotJournal(pPager);
43265        if( rc==SQLITE_OK ){
43266          rc = pager_playback(pPager, 1);
43267          pPager->eState = PAGER_OPEN;
43268        }
43269      }else if( !pPager->exclusiveMode ){
43270        pagerUnlockDb(pPager, SHARED_LOCK);
43271      }
43272
43273      if( rc!=SQLITE_OK ){
43274        /* This branch is taken if an error occurs while trying to open
43275        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
43276        ** pager_unlock() routine will be called before returning to unlock
43277        ** the file. If the unlock attempt fails, then Pager.eLock must be
43278        ** set to UNKNOWN_LOCK (see the comment above the #define for
43279        ** UNKNOWN_LOCK above for an explanation).
43280        **
43281        ** In order to get pager_unlock() to do this, set Pager.eState to
43282        ** PAGER_ERROR now. This is not actually counted as a transition
43283        ** to ERROR state in the state diagram at the top of this file,
43284        ** since we know that the same call to pager_unlock() will very
43285        ** shortly transition the pager object to the OPEN state. Calling
43286        ** assert_pager_state() would fail now, as it should not be possible
43287        ** to be in ERROR state when there are zero outstanding page
43288        ** references.
43289        */
43290        pager_error(pPager, rc);
43291        goto failed;
43292      }
43293
43294      assert( pPager->eState==PAGER_OPEN );
43295      assert( (pPager->eLock==SHARED_LOCK)
43296           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
43297      );
43298    }
43299
43300    if( !pPager->tempFile
43301     && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
43302    ){
43303      /* The shared-lock has just been acquired on the database file
43304      ** and there are already pages in the cache (from a previous
43305      ** read or write transaction).  Check to see if the database
43306      ** has been modified.  If the database has changed, flush the
43307      ** cache.
43308      **
43309      ** Database changes is detected by looking at 15 bytes beginning
43310      ** at offset 24 into the file.  The first 4 of these 16 bytes are
43311      ** a 32-bit counter that is incremented with each change.  The
43312      ** other bytes change randomly with each file change when
43313      ** a codec is in use.
43314      **
43315      ** There is a vanishingly small chance that a change will not be
43316      ** detected.  The chance of an undetected change is so small that
43317      ** it can be neglected.
43318      */
43319      Pgno nPage = 0;
43320      char dbFileVers[sizeof(pPager->dbFileVers)];
43321
43322      rc = pagerPagecount(pPager, &nPage);
43323      if( rc ) goto failed;
43324
43325      if( nPage>0 ){
43326        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
43327        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
43328        if( rc!=SQLITE_OK ){
43329          goto failed;
43330        }
43331      }else{
43332        memset(dbFileVers, 0, sizeof(dbFileVers));
43333      }
43334
43335      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
43336        pager_reset(pPager);
43337      }
43338    }
43339
43340    /* If there is a WAL file in the file-system, open this database in WAL
43341    ** mode. Otherwise, the following function call is a no-op.
43342    */
43343    rc = pagerOpenWalIfPresent(pPager);
43344#ifndef SQLITE_OMIT_WAL
43345    assert( pPager->pWal==0 || rc==SQLITE_OK );
43346#endif
43347  }
43348
43349  if( pagerUseWal(pPager) ){
43350    assert( rc==SQLITE_OK );
43351    rc = pagerBeginReadTransaction(pPager);
43352  }
43353
43354  if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
43355    rc = pagerPagecount(pPager, &pPager->dbSize);
43356  }
43357
43358 failed:
43359  if( rc!=SQLITE_OK ){
43360    assert( !MEMDB );
43361    pager_unlock(pPager);
43362    assert( pPager->eState==PAGER_OPEN );
43363  }else{
43364    pPager->eState = PAGER_READER;
43365  }
43366  return rc;
43367}
43368
43369/*
43370** If the reference count has reached zero, rollback any active
43371** transaction and unlock the pager.
43372**
43373** Except, in locking_mode=EXCLUSIVE when there is nothing to in
43374** the rollback journal, the unlock is not performed and there is
43375** nothing to rollback, so this routine is a no-op.
43376*/
43377static void pagerUnlockIfUnused(Pager *pPager){
43378  if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
43379    pagerUnlockAndRollback(pPager);
43380  }
43381}
43382
43383/*
43384** Acquire a reference to page number pgno in pager pPager (a page
43385** reference has type DbPage*). If the requested reference is
43386** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
43387**
43388** If the requested page is already in the cache, it is returned.
43389** Otherwise, a new page object is allocated and populated with data
43390** read from the database file. In some cases, the pcache module may
43391** choose not to allocate a new page object and may reuse an existing
43392** object with no outstanding references.
43393**
43394** The extra data appended to a page is always initialized to zeros the
43395** first time a page is loaded into memory. If the page requested is
43396** already in the cache when this function is called, then the extra
43397** data is left as it was when the page object was last used.
43398**
43399** If the database image is smaller than the requested page or if a
43400** non-zero value is passed as the noContent parameter and the
43401** requested page is not already stored in the cache, then no
43402** actual disk read occurs. In this case the memory image of the
43403** page is initialized to all zeros.
43404**
43405** If noContent is true, it means that we do not care about the contents
43406** of the page. This occurs in two seperate scenarios:
43407**
43408**   a) When reading a free-list leaf page from the database, and
43409**
43410**   b) When a savepoint is being rolled back and we need to load
43411**      a new page into the cache to be filled with the data read
43412**      from the savepoint journal.
43413**
43414** If noContent is true, then the data returned is zeroed instead of
43415** being read from the database. Additionally, the bits corresponding
43416** to pgno in Pager.pInJournal (bitvec of pages already written to the
43417** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
43418** savepoints are set. This means if the page is made writable at any
43419** point in the future, using a call to sqlite3PagerWrite(), its contents
43420** will not be journaled. This saves IO.
43421**
43422** The acquisition might fail for several reasons.  In all cases,
43423** an appropriate error code is returned and *ppPage is set to NULL.
43424**
43425** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
43426** to find a page in the in-memory cache first.  If the page is not already
43427** in memory, this routine goes to disk to read it in whereas Lookup()
43428** just returns 0.  This routine acquires a read-lock the first time it
43429** has to go to disk, and could also playback an old journal if necessary.
43430** Since Lookup() never goes to disk, it never has to deal with locks
43431** or journal files.
43432*/
43433SQLITE_PRIVATE int sqlite3PagerAcquire(
43434  Pager *pPager,      /* The pager open on the database file */
43435  Pgno pgno,          /* Page number to fetch */
43436  DbPage **ppPage,    /* Write a pointer to the page here */
43437  int noContent       /* Do not bother reading content from disk if true */
43438){
43439  int rc;
43440  PgHdr *pPg;
43441
43442  assert( pPager->eState>=PAGER_READER );
43443  assert( assert_pager_state(pPager) );
43444
43445  if( pgno==0 ){
43446    return SQLITE_CORRUPT_BKPT;
43447  }
43448
43449  /* If the pager is in the error state, return an error immediately.
43450  ** Otherwise, request the page from the PCache layer. */
43451  if( pPager->errCode!=SQLITE_OK ){
43452    rc = pPager->errCode;
43453  }else{
43454    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
43455  }
43456
43457  if( rc!=SQLITE_OK ){
43458    /* Either the call to sqlite3PcacheFetch() returned an error or the
43459    ** pager was already in the error-state when this function was called.
43460    ** Set pPg to 0 and jump to the exception handler.  */
43461    pPg = 0;
43462    goto pager_acquire_err;
43463  }
43464  assert( (*ppPage)->pgno==pgno );
43465  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
43466
43467  if( (*ppPage)->pPager && !noContent ){
43468    /* In this case the pcache already contains an initialized copy of
43469    ** the page. Return without further ado.  */
43470    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
43471    pPager->nHit++;
43472    return SQLITE_OK;
43473
43474  }else{
43475    /* The pager cache has created a new page. Its content needs to
43476    ** be initialized.  */
43477
43478    pPg = *ppPage;
43479    pPg->pPager = pPager;
43480
43481    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
43482    ** number greater than this, or the unused locking-page, is requested. */
43483    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
43484      rc = SQLITE_CORRUPT_BKPT;
43485      goto pager_acquire_err;
43486    }
43487
43488    if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
43489      if( pgno>pPager->mxPgno ){
43490        rc = SQLITE_FULL;
43491        goto pager_acquire_err;
43492      }
43493      if( noContent ){
43494        /* Failure to set the bits in the InJournal bit-vectors is benign.
43495        ** It merely means that we might do some extra work to journal a
43496        ** page that does not need to be journaled.  Nevertheless, be sure
43497        ** to test the case where a malloc error occurs while trying to set
43498        ** a bit in a bit vector.
43499        */
43500        sqlite3BeginBenignMalloc();
43501        if( pgno<=pPager->dbOrigSize ){
43502          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
43503          testcase( rc==SQLITE_NOMEM );
43504        }
43505        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
43506        testcase( rc==SQLITE_NOMEM );
43507        sqlite3EndBenignMalloc();
43508      }
43509      memset(pPg->pData, 0, pPager->pageSize);
43510      IOTRACE(("ZERO %p %d\n", pPager, pgno));
43511    }else{
43512      assert( pPg->pPager==pPager );
43513      pPager->nMiss++;
43514      rc = readDbPage(pPg);
43515      if( rc!=SQLITE_OK ){
43516        goto pager_acquire_err;
43517      }
43518    }
43519    pager_set_pagehash(pPg);
43520  }
43521
43522  return SQLITE_OK;
43523
43524pager_acquire_err:
43525  assert( rc!=SQLITE_OK );
43526  if( pPg ){
43527    sqlite3PcacheDrop(pPg);
43528  }
43529  pagerUnlockIfUnused(pPager);
43530
43531  *ppPage = 0;
43532  return rc;
43533}
43534
43535/*
43536** Acquire a page if it is already in the in-memory cache.  Do
43537** not read the page from disk.  Return a pointer to the page,
43538** or 0 if the page is not in cache.
43539**
43540** See also sqlite3PagerGet().  The difference between this routine
43541** and sqlite3PagerGet() is that _get() will go to the disk and read
43542** in the page if the page is not already in cache.  This routine
43543** returns NULL if the page is not in cache or if a disk I/O error
43544** has ever happened.
43545*/
43546SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
43547  PgHdr *pPg = 0;
43548  assert( pPager!=0 );
43549  assert( pgno!=0 );
43550  assert( pPager->pPCache!=0 );
43551  assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
43552  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
43553  return pPg;
43554}
43555
43556/*
43557** Release a page reference.
43558**
43559** If the number of references to the page drop to zero, then the
43560** page is added to the LRU list.  When all references to all pages
43561** are released, a rollback occurs and the lock on the database is
43562** removed.
43563*/
43564SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
43565  if( pPg ){
43566    Pager *pPager = pPg->pPager;
43567    sqlite3PcacheRelease(pPg);
43568    pagerUnlockIfUnused(pPager);
43569  }
43570}
43571
43572/*
43573** This function is called at the start of every write transaction.
43574** There must already be a RESERVED or EXCLUSIVE lock on the database
43575** file when this routine is called.
43576**
43577** Open the journal file for pager pPager and write a journal header
43578** to the start of it. If there are active savepoints, open the sub-journal
43579** as well. This function is only used when the journal file is being
43580** opened to write a rollback log for a transaction. It is not used
43581** when opening a hot journal file to roll it back.
43582**
43583** If the journal file is already open (as it may be in exclusive mode),
43584** then this function just writes a journal header to the start of the
43585** already open file.
43586**
43587** Whether or not the journal file is opened by this function, the
43588** Pager.pInJournal bitvec structure is allocated.
43589**
43590** Return SQLITE_OK if everything is successful. Otherwise, return
43591** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
43592** an IO error code if opening or writing the journal file fails.
43593*/
43594static int pager_open_journal(Pager *pPager){
43595  int rc = SQLITE_OK;                        /* Return code */
43596  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
43597
43598  assert( pPager->eState==PAGER_WRITER_LOCKED );
43599  assert( assert_pager_state(pPager) );
43600  assert( pPager->pInJournal==0 );
43601
43602  /* If already in the error state, this function is a no-op.  But on
43603  ** the other hand, this routine is never called if we are already in
43604  ** an error state. */
43605  if( NEVER(pPager->errCode) ) return pPager->errCode;
43606
43607  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
43608    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
43609    if( pPager->pInJournal==0 ){
43610      return SQLITE_NOMEM;
43611    }
43612
43613    /* Open the journal file if it is not already open. */
43614    if( !isOpen(pPager->jfd) ){
43615      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
43616        sqlite3MemJournalOpen(pPager->jfd);
43617      }else{
43618        const int flags =                   /* VFS flags to open journal file */
43619          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
43620          (pPager->tempFile ?
43621            (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
43622            (SQLITE_OPEN_MAIN_JOURNAL)
43623          );
43624  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43625        rc = sqlite3JournalOpen(
43626            pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
43627        );
43628  #else
43629        rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
43630  #endif
43631      }
43632      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
43633    }
43634
43635
43636    /* Write the first journal header to the journal file and open
43637    ** the sub-journal if necessary.
43638    */
43639    if( rc==SQLITE_OK ){
43640      /* TODO: Check if all of these are really required. */
43641      pPager->nRec = 0;
43642      pPager->journalOff = 0;
43643      pPager->setMaster = 0;
43644      pPager->journalHdr = 0;
43645      rc = writeJournalHdr(pPager);
43646    }
43647  }
43648
43649  if( rc!=SQLITE_OK ){
43650    sqlite3BitvecDestroy(pPager->pInJournal);
43651    pPager->pInJournal = 0;
43652  }else{
43653    assert( pPager->eState==PAGER_WRITER_LOCKED );
43654    pPager->eState = PAGER_WRITER_CACHEMOD;
43655  }
43656
43657  return rc;
43658}
43659
43660/*
43661** Begin a write-transaction on the specified pager object. If a
43662** write-transaction has already been opened, this function is a no-op.
43663**
43664** If the exFlag argument is false, then acquire at least a RESERVED
43665** lock on the database file. If exFlag is true, then acquire at least
43666** an EXCLUSIVE lock. If such a lock is already held, no locking
43667** functions need be called.
43668**
43669** If the subjInMemory argument is non-zero, then any sub-journal opened
43670** within this transaction will be opened as an in-memory file. This
43671** has no effect if the sub-journal is already opened (as it may be when
43672** running in exclusive mode) or if the transaction does not require a
43673** sub-journal. If the subjInMemory argument is zero, then any required
43674** sub-journal is implemented in-memory if pPager is an in-memory database,
43675** or using a temporary file otherwise.
43676*/
43677SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
43678  int rc = SQLITE_OK;
43679
43680  if( pPager->errCode ) return pPager->errCode;
43681  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
43682  pPager->subjInMemory = (u8)subjInMemory;
43683
43684  if( ALWAYS(pPager->eState==PAGER_READER) ){
43685    assert( pPager->pInJournal==0 );
43686
43687    if( pagerUseWal(pPager) ){
43688      /* If the pager is configured to use locking_mode=exclusive, and an
43689      ** exclusive lock on the database is not already held, obtain it now.
43690      */
43691      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
43692        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43693        if( rc!=SQLITE_OK ){
43694          return rc;
43695        }
43696        sqlite3WalExclusiveMode(pPager->pWal, 1);
43697      }
43698
43699      /* Grab the write lock on the log file. If successful, upgrade to
43700      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
43701      ** The busy-handler is not invoked if another connection already
43702      ** holds the write-lock. If possible, the upper layer will call it.
43703      */
43704      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
43705    }else{
43706      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
43707      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
43708      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
43709      ** lock, but not when obtaining the RESERVED lock.
43710      */
43711      rc = pagerLockDb(pPager, RESERVED_LOCK);
43712      if( rc==SQLITE_OK && exFlag ){
43713        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
43714      }
43715    }
43716
43717    if( rc==SQLITE_OK ){
43718      /* Change to WRITER_LOCKED state.
43719      **
43720      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
43721      ** when it has an open transaction, but never to DBMOD or FINISHED.
43722      ** This is because in those states the code to roll back savepoint
43723      ** transactions may copy data from the sub-journal into the database
43724      ** file as well as into the page cache. Which would be incorrect in
43725      ** WAL mode.
43726      */
43727      pPager->eState = PAGER_WRITER_LOCKED;
43728      pPager->dbHintSize = pPager->dbSize;
43729      pPager->dbFileSize = pPager->dbSize;
43730      pPager->dbOrigSize = pPager->dbSize;
43731      pPager->journalOff = 0;
43732    }
43733
43734    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
43735    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
43736    assert( assert_pager_state(pPager) );
43737  }
43738
43739  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
43740  return rc;
43741}
43742
43743/*
43744** Mark a single data page as writeable. The page is written into the
43745** main journal or sub-journal as required. If the page is written into
43746** one of the journals, the corresponding bit is set in the
43747** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
43748** of any open savepoints as appropriate.
43749*/
43750static int pager_write(PgHdr *pPg){
43751  void *pData = pPg->pData;
43752  Pager *pPager = pPg->pPager;
43753  int rc = SQLITE_OK;
43754
43755  /* This routine is not called unless a write-transaction has already
43756  ** been started. The journal file may or may not be open at this point.
43757  ** It is never called in the ERROR state.
43758  */
43759  assert( pPager->eState==PAGER_WRITER_LOCKED
43760       || pPager->eState==PAGER_WRITER_CACHEMOD
43761       || pPager->eState==PAGER_WRITER_DBMOD
43762  );
43763  assert( assert_pager_state(pPager) );
43764
43765  /* If an error has been previously detected, report the same error
43766  ** again. This should not happen, but the check provides robustness. */
43767  if( NEVER(pPager->errCode) )  return pPager->errCode;
43768
43769  /* Higher-level routines never call this function if database is not
43770  ** writable.  But check anyway, just for robustness. */
43771  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
43772
43773  CHECK_PAGE(pPg);
43774
43775  /* The journal file needs to be opened. Higher level routines have already
43776  ** obtained the necessary locks to begin the write-transaction, but the
43777  ** rollback journal might not yet be open. Open it now if this is the case.
43778  **
43779  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
43780  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
43781  ** an error might occur and the pager would end up in WRITER_LOCKED state
43782  ** with pages marked as dirty in the cache.
43783  */
43784  if( pPager->eState==PAGER_WRITER_LOCKED ){
43785    rc = pager_open_journal(pPager);
43786    if( rc!=SQLITE_OK ) return rc;
43787  }
43788  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
43789  assert( assert_pager_state(pPager) );
43790
43791  /* Mark the page as dirty.  If the page has already been written
43792  ** to the journal then we can return right away.
43793  */
43794  sqlite3PcacheMakeDirty(pPg);
43795  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
43796    assert( !pagerUseWal(pPager) );
43797  }else{
43798
43799    /* The transaction journal now exists and we have a RESERVED or an
43800    ** EXCLUSIVE lock on the main database file.  Write the current page to
43801    ** the transaction journal if it is not there already.
43802    */
43803    if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
43804      assert( pagerUseWal(pPager)==0 );
43805      if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
43806        u32 cksum;
43807        char *pData2;
43808        i64 iOff = pPager->journalOff;
43809
43810        /* We should never write to the journal file the page that
43811        ** contains the database locks.  The following assert verifies
43812        ** that we do not. */
43813        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
43814
43815        assert( pPager->journalHdr<=pPager->journalOff );
43816        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
43817        cksum = pager_cksum(pPager, (u8*)pData2);
43818
43819        /* Even if an IO or diskfull error occurs while journalling the
43820        ** page in the block above, set the need-sync flag for the page.
43821        ** Otherwise, when the transaction is rolled back, the logic in
43822        ** playback_one_page() will think that the page needs to be restored
43823        ** in the database file. And if an IO error occurs while doing so,
43824        ** then corruption may follow.
43825        */
43826        pPg->flags |= PGHDR_NEED_SYNC;
43827
43828        rc = write32bits(pPager->jfd, iOff, pPg->pgno);
43829        if( rc!=SQLITE_OK ) return rc;
43830        rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
43831        if( rc!=SQLITE_OK ) return rc;
43832        rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
43833        if( rc!=SQLITE_OK ) return rc;
43834
43835        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
43836                 pPager->journalOff, pPager->pageSize));
43837        PAGER_INCR(sqlite3_pager_writej_count);
43838        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
43839             PAGERID(pPager), pPg->pgno,
43840             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
43841
43842        pPager->journalOff += 8 + pPager->pageSize;
43843        pPager->nRec++;
43844        assert( pPager->pInJournal!=0 );
43845        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
43846        testcase( rc==SQLITE_NOMEM );
43847        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
43848        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
43849        if( rc!=SQLITE_OK ){
43850          assert( rc==SQLITE_NOMEM );
43851          return rc;
43852        }
43853      }else{
43854        if( pPager->eState!=PAGER_WRITER_DBMOD ){
43855          pPg->flags |= PGHDR_NEED_SYNC;
43856        }
43857        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
43858                PAGERID(pPager), pPg->pgno,
43859               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
43860      }
43861    }
43862
43863    /* If the statement journal is open and the page is not in it,
43864    ** then write the current page to the statement journal.  Note that
43865    ** the statement journal format differs from the standard journal format
43866    ** in that it omits the checksums and the header.
43867    */
43868    if( subjRequiresPage(pPg) ){
43869      rc = subjournalPage(pPg);
43870    }
43871  }
43872
43873  /* Update the database size and return.
43874  */
43875  if( pPager->dbSize<pPg->pgno ){
43876    pPager->dbSize = pPg->pgno;
43877  }
43878  return rc;
43879}
43880
43881/*
43882** Mark a data page as writeable. This routine must be called before
43883** making changes to a page. The caller must check the return value
43884** of this function and be careful not to change any page data unless
43885** this routine returns SQLITE_OK.
43886**
43887** The difference between this function and pager_write() is that this
43888** function also deals with the special case where 2 or more pages
43889** fit on a single disk sector. In this case all co-resident pages
43890** must have been written to the journal file before returning.
43891**
43892** If an error occurs, SQLITE_NOMEM or an IO error code is returned
43893** as appropriate. Otherwise, SQLITE_OK.
43894*/
43895SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
43896  int rc = SQLITE_OK;
43897
43898  PgHdr *pPg = pDbPage;
43899  Pager *pPager = pPg->pPager;
43900  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
43901
43902  assert( pPager->eState>=PAGER_WRITER_LOCKED );
43903  assert( pPager->eState!=PAGER_ERROR );
43904  assert( assert_pager_state(pPager) );
43905
43906  if( nPagePerSector>1 ){
43907    Pgno nPageCount;          /* Total number of pages in database file */
43908    Pgno pg1;                 /* First page of the sector pPg is located on. */
43909    int nPage = 0;            /* Number of pages starting at pg1 to journal */
43910    int ii;                   /* Loop counter */
43911    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
43912
43913    /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
43914    ** a journal header to be written between the pages journaled by
43915    ** this function.
43916    */
43917    assert( !MEMDB );
43918    assert( pPager->doNotSyncSpill==0 );
43919    pPager->doNotSyncSpill++;
43920
43921    /* This trick assumes that both the page-size and sector-size are
43922    ** an integer power of 2. It sets variable pg1 to the identifier
43923    ** of the first page of the sector pPg is located on.
43924    */
43925    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
43926
43927    nPageCount = pPager->dbSize;
43928    if( pPg->pgno>nPageCount ){
43929      nPage = (pPg->pgno - pg1)+1;
43930    }else if( (pg1+nPagePerSector-1)>nPageCount ){
43931      nPage = nPageCount+1-pg1;
43932    }else{
43933      nPage = nPagePerSector;
43934    }
43935    assert(nPage>0);
43936    assert(pg1<=pPg->pgno);
43937    assert((pg1+nPage)>pPg->pgno);
43938
43939    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
43940      Pgno pg = pg1+ii;
43941      PgHdr *pPage;
43942      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
43943        if( pg!=PAGER_MJ_PGNO(pPager) ){
43944          rc = sqlite3PagerGet(pPager, pg, &pPage);
43945          if( rc==SQLITE_OK ){
43946            rc = pager_write(pPage);
43947            if( pPage->flags&PGHDR_NEED_SYNC ){
43948              needSync = 1;
43949            }
43950            sqlite3PagerUnref(pPage);
43951          }
43952        }
43953      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
43954        if( pPage->flags&PGHDR_NEED_SYNC ){
43955          needSync = 1;
43956        }
43957        sqlite3PagerUnref(pPage);
43958      }
43959    }
43960
43961    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
43962    ** starting at pg1, then it needs to be set for all of them. Because
43963    ** writing to any of these nPage pages may damage the others, the
43964    ** journal file must contain sync()ed copies of all of them
43965    ** before any of them can be written out to the database file.
43966    */
43967    if( rc==SQLITE_OK && needSync ){
43968      assert( !MEMDB );
43969      for(ii=0; ii<nPage; ii++){
43970        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
43971        if( pPage ){
43972          pPage->flags |= PGHDR_NEED_SYNC;
43973          sqlite3PagerUnref(pPage);
43974        }
43975      }
43976    }
43977
43978    assert( pPager->doNotSyncSpill==1 );
43979    pPager->doNotSyncSpill--;
43980  }else{
43981    rc = pager_write(pDbPage);
43982  }
43983  return rc;
43984}
43985
43986/*
43987** Return TRUE if the page given in the argument was previously passed
43988** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
43989** to change the content of the page.
43990*/
43991#ifndef NDEBUG
43992SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
43993  return pPg->flags&PGHDR_DIRTY;
43994}
43995#endif
43996
43997/*
43998** A call to this routine tells the pager that it is not necessary to
43999** write the information on page pPg back to the disk, even though
44000** that page might be marked as dirty.  This happens, for example, when
44001** the page has been added as a leaf of the freelist and so its
44002** content no longer matters.
44003**
44004** The overlying software layer calls this routine when all of the data
44005** on the given page is unused. The pager marks the page as clean so
44006** that it does not get written to disk.
44007**
44008** Tests show that this optimization can quadruple the speed of large
44009** DELETE operations.
44010*/
44011SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
44012  Pager *pPager = pPg->pPager;
44013  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
44014    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
44015    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
44016    pPg->flags |= PGHDR_DONT_WRITE;
44017    pager_set_pagehash(pPg);
44018  }
44019}
44020
44021/*
44022** This routine is called to increment the value of the database file
44023** change-counter, stored as a 4-byte big-endian integer starting at
44024** byte offset 24 of the pager file.  The secondary change counter at
44025** 92 is also updated, as is the SQLite version number at offset 96.
44026**
44027** But this only happens if the pPager->changeCountDone flag is false.
44028** To avoid excess churning of page 1, the update only happens once.
44029** See also the pager_write_changecounter() routine that does an
44030** unconditional update of the change counters.
44031**
44032** If the isDirectMode flag is zero, then this is done by calling
44033** sqlite3PagerWrite() on page 1, then modifying the contents of the
44034** page data. In this case the file will be updated when the current
44035** transaction is committed.
44036**
44037** The isDirectMode flag may only be non-zero if the library was compiled
44038** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
44039** if isDirect is non-zero, then the database file is updated directly
44040** by writing an updated version of page 1 using a call to the
44041** sqlite3OsWrite() function.
44042*/
44043static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
44044  int rc = SQLITE_OK;
44045
44046  assert( pPager->eState==PAGER_WRITER_CACHEMOD
44047       || pPager->eState==PAGER_WRITER_DBMOD
44048  );
44049  assert( assert_pager_state(pPager) );
44050
44051  /* Declare and initialize constant integer 'isDirect'. If the
44052  ** atomic-write optimization is enabled in this build, then isDirect
44053  ** is initialized to the value passed as the isDirectMode parameter
44054  ** to this function. Otherwise, it is always set to zero.
44055  **
44056  ** The idea is that if the atomic-write optimization is not
44057  ** enabled at compile time, the compiler can omit the tests of
44058  ** 'isDirect' below, as well as the block enclosed in the
44059  ** "if( isDirect )" condition.
44060  */
44061#ifndef SQLITE_ENABLE_ATOMIC_WRITE
44062# define DIRECT_MODE 0
44063  assert( isDirectMode==0 );
44064  UNUSED_PARAMETER(isDirectMode);
44065#else
44066# define DIRECT_MODE isDirectMode
44067#endif
44068
44069  if( !pPager->changeCountDone && pPager->dbSize>0 ){
44070    PgHdr *pPgHdr;                /* Reference to page 1 */
44071
44072    assert( !pPager->tempFile && isOpen(pPager->fd) );
44073
44074    /* Open page 1 of the file for writing. */
44075    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
44076    assert( pPgHdr==0 || rc==SQLITE_OK );
44077
44078    /* If page one was fetched successfully, and this function is not
44079    ** operating in direct-mode, make page 1 writable.  When not in
44080    ** direct mode, page 1 is always held in cache and hence the PagerGet()
44081    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
44082    */
44083    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
44084      rc = sqlite3PagerWrite(pPgHdr);
44085    }
44086
44087    if( rc==SQLITE_OK ){
44088      /* Actually do the update of the change counter */
44089      pager_write_changecounter(pPgHdr);
44090
44091      /* If running in direct mode, write the contents of page 1 to the file. */
44092      if( DIRECT_MODE ){
44093        const void *zBuf;
44094        assert( pPager->dbFileSize>0 );
44095        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
44096        if( rc==SQLITE_OK ){
44097          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
44098        }
44099        if( rc==SQLITE_OK ){
44100          pPager->changeCountDone = 1;
44101        }
44102      }else{
44103        pPager->changeCountDone = 1;
44104      }
44105    }
44106
44107    /* Release the page reference. */
44108    sqlite3PagerUnref(pPgHdr);
44109  }
44110  return rc;
44111}
44112
44113/*
44114** Sync the database file to disk. This is a no-op for in-memory databases
44115** or pages with the Pager.noSync flag set.
44116**
44117** If successful, or if called on a pager for which it is a no-op, this
44118** function returns SQLITE_OK. Otherwise, an IO error code is returned.
44119*/
44120SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
44121  int rc = SQLITE_OK;
44122  if( !pPager->noSync ){
44123    assert( !MEMDB );
44124    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
44125  }else if( isOpen(pPager->fd) ){
44126    assert( !MEMDB );
44127    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
44128    if( rc==SQLITE_NOTFOUND ){
44129      rc = SQLITE_OK;
44130    }
44131  }
44132  return rc;
44133}
44134
44135/*
44136** This function may only be called while a write-transaction is active in
44137** rollback. If the connection is in WAL mode, this call is a no-op.
44138** Otherwise, if the connection does not already have an EXCLUSIVE lock on
44139** the database file, an attempt is made to obtain one.
44140**
44141** If the EXCLUSIVE lock is already held or the attempt to obtain it is
44142** successful, or the connection is in WAL mode, SQLITE_OK is returned.
44143** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
44144** returned.
44145*/
44146SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
44147  int rc = SQLITE_OK;
44148  assert( pPager->eState==PAGER_WRITER_CACHEMOD
44149       || pPager->eState==PAGER_WRITER_DBMOD
44150       || pPager->eState==PAGER_WRITER_LOCKED
44151  );
44152  assert( assert_pager_state(pPager) );
44153  if( 0==pagerUseWal(pPager) ){
44154    rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
44155  }
44156  return rc;
44157}
44158
44159/*
44160** Sync the database file for the pager pPager. zMaster points to the name
44161** of a master journal file that should be written into the individual
44162** journal file. zMaster may be NULL, which is interpreted as no master
44163** journal (a single database transaction).
44164**
44165** This routine ensures that:
44166**
44167**   * The database file change-counter is updated,
44168**   * the journal is synced (unless the atomic-write optimization is used),
44169**   * all dirty pages are written to the database file,
44170**   * the database file is truncated (if required), and
44171**   * the database file synced.
44172**
44173** The only thing that remains to commit the transaction is to finalize
44174** (delete, truncate or zero the first part of) the journal file (or
44175** delete the master journal file if specified).
44176**
44177** Note that if zMaster==NULL, this does not overwrite a previous value
44178** passed to an sqlite3PagerCommitPhaseOne() call.
44179**
44180** If the final parameter - noSync - is true, then the database file itself
44181** is not synced. The caller must call sqlite3PagerSync() directly to
44182** sync the database file before calling CommitPhaseTwo() to delete the
44183** journal file in this case.
44184*/
44185SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
44186  Pager *pPager,                  /* Pager object */
44187  const char *zMaster,            /* If not NULL, the master journal name */
44188  int noSync                      /* True to omit the xSync on the db file */
44189){
44190  int rc = SQLITE_OK;             /* Return code */
44191
44192  assert( pPager->eState==PAGER_WRITER_LOCKED
44193       || pPager->eState==PAGER_WRITER_CACHEMOD
44194       || pPager->eState==PAGER_WRITER_DBMOD
44195       || pPager->eState==PAGER_ERROR
44196  );
44197  assert( assert_pager_state(pPager) );
44198
44199  /* If a prior error occurred, report that error again. */
44200  if( NEVER(pPager->errCode) ) return pPager->errCode;
44201
44202  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
44203      pPager->zFilename, zMaster, pPager->dbSize));
44204
44205  /* If no database changes have been made, return early. */
44206  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
44207
44208  if( MEMDB ){
44209    /* If this is an in-memory db, or no pages have been written to, or this
44210    ** function has already been called, it is mostly a no-op.  However, any
44211    ** backup in progress needs to be restarted.
44212    */
44213    sqlite3BackupRestart(pPager->pBackup);
44214  }else{
44215    if( pagerUseWal(pPager) ){
44216      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
44217      PgHdr *pPageOne = 0;
44218      if( pList==0 ){
44219        /* Must have at least one page for the WAL commit flag.
44220        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
44221        rc = sqlite3PagerGet(pPager, 1, &pPageOne);
44222        pList = pPageOne;
44223        pList->pDirty = 0;
44224      }
44225      assert( rc==SQLITE_OK );
44226      if( ALWAYS(pList) ){
44227        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
44228      }
44229      sqlite3PagerUnref(pPageOne);
44230      if( rc==SQLITE_OK ){
44231        sqlite3PcacheCleanAll(pPager->pPCache);
44232      }
44233    }else{
44234      /* The following block updates the change-counter. Exactly how it
44235      ** does this depends on whether or not the atomic-update optimization
44236      ** was enabled at compile time, and if this transaction meets the
44237      ** runtime criteria to use the operation:
44238      **
44239      **    * The file-system supports the atomic-write property for
44240      **      blocks of size page-size, and
44241      **    * This commit is not part of a multi-file transaction, and
44242      **    * Exactly one page has been modified and store in the journal file.
44243      **
44244      ** If the optimization was not enabled at compile time, then the
44245      ** pager_incr_changecounter() function is called to update the change
44246      ** counter in 'indirect-mode'. If the optimization is compiled in but
44247      ** is not applicable to this transaction, call sqlite3JournalCreate()
44248      ** to make sure the journal file has actually been created, then call
44249      ** pager_incr_changecounter() to update the change-counter in indirect
44250      ** mode.
44251      **
44252      ** Otherwise, if the optimization is both enabled and applicable,
44253      ** then call pager_incr_changecounter() to update the change-counter
44254      ** in 'direct' mode. In this case the journal file will never be
44255      ** created for this transaction.
44256      */
44257  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
44258      PgHdr *pPg;
44259      assert( isOpen(pPager->jfd)
44260           || pPager->journalMode==PAGER_JOURNALMODE_OFF
44261           || pPager->journalMode==PAGER_JOURNALMODE_WAL
44262      );
44263      if( !zMaster && isOpen(pPager->jfd)
44264       && pPager->journalOff==jrnlBufferSize(pPager)
44265       && pPager->dbSize>=pPager->dbOrigSize
44266       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
44267      ){
44268        /* Update the db file change counter via the direct-write method. The
44269        ** following call will modify the in-memory representation of page 1
44270        ** to include the updated change counter and then write page 1
44271        ** directly to the database file. Because of the atomic-write
44272        ** property of the host file-system, this is safe.
44273        */
44274        rc = pager_incr_changecounter(pPager, 1);
44275      }else{
44276        rc = sqlite3JournalCreate(pPager->jfd);
44277        if( rc==SQLITE_OK ){
44278          rc = pager_incr_changecounter(pPager, 0);
44279        }
44280      }
44281  #else
44282      rc = pager_incr_changecounter(pPager, 0);
44283  #endif
44284      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44285
44286      /* If this transaction has made the database smaller, then all pages
44287      ** being discarded by the truncation must be written to the journal
44288      ** file. This can only happen in auto-vacuum mode.
44289      **
44290      ** Before reading the pages with page numbers larger than the
44291      ** current value of Pager.dbSize, set dbSize back to the value
44292      ** that it took at the start of the transaction. Otherwise, the
44293      ** calls to sqlite3PagerGet() return zeroed pages instead of
44294      ** reading data from the database file.
44295      */
44296  #ifndef SQLITE_OMIT_AUTOVACUUM
44297      if( pPager->dbSize<pPager->dbOrigSize
44298       && pPager->journalMode!=PAGER_JOURNALMODE_OFF
44299      ){
44300        Pgno i;                                   /* Iterator variable */
44301        const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
44302        const Pgno dbSize = pPager->dbSize;       /* Database image size */
44303        pPager->dbSize = pPager->dbOrigSize;
44304        for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
44305          if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
44306            PgHdr *pPage;             /* Page to journal */
44307            rc = sqlite3PagerGet(pPager, i, &pPage);
44308            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44309            rc = sqlite3PagerWrite(pPage);
44310            sqlite3PagerUnref(pPage);
44311            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44312          }
44313        }
44314        pPager->dbSize = dbSize;
44315      }
44316  #endif
44317
44318      /* Write the master journal name into the journal file. If a master
44319      ** journal file name has already been written to the journal file,
44320      ** or if zMaster is NULL (no master journal), then this call is a no-op.
44321      */
44322      rc = writeMasterJournal(pPager, zMaster);
44323      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44324
44325      /* Sync the journal file and write all dirty pages to the database.
44326      ** If the atomic-update optimization is being used, this sync will not
44327      ** create the journal file or perform any real IO.
44328      **
44329      ** Because the change-counter page was just modified, unless the
44330      ** atomic-update optimization is used it is almost certain that the
44331      ** journal requires a sync here. However, in locking_mode=exclusive
44332      ** on a system under memory pressure it is just possible that this is
44333      ** not the case. In this case it is likely enough that the redundant
44334      ** xSync() call will be changed to a no-op by the OS anyhow.
44335      */
44336      rc = syncJournal(pPager, 0);
44337      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44338
44339      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
44340      if( rc!=SQLITE_OK ){
44341        assert( rc!=SQLITE_IOERR_BLOCKED );
44342        goto commit_phase_one_exit;
44343      }
44344      sqlite3PcacheCleanAll(pPager->pPCache);
44345
44346      /* If the file on disk is not the same size as the database image,
44347      ** then use pager_truncate to grow or shrink the file here.
44348      */
44349      if( pPager->dbSize!=pPager->dbFileSize ){
44350        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
44351        assert( pPager->eState==PAGER_WRITER_DBMOD );
44352        rc = pager_truncate(pPager, nNew);
44353        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44354      }
44355
44356      /* Finally, sync the database file. */
44357      if( !noSync ){
44358        rc = sqlite3PagerSync(pPager);
44359      }
44360      IOTRACE(("DBSYNC %p\n", pPager))
44361    }
44362  }
44363
44364commit_phase_one_exit:
44365  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
44366    pPager->eState = PAGER_WRITER_FINISHED;
44367  }
44368  return rc;
44369}
44370
44371
44372/*
44373** When this function is called, the database file has been completely
44374** updated to reflect the changes made by the current transaction and
44375** synced to disk. The journal file still exists in the file-system
44376** though, and if a failure occurs at this point it will eventually
44377** be used as a hot-journal and the current transaction rolled back.
44378**
44379** This function finalizes the journal file, either by deleting,
44380** truncating or partially zeroing it, so that it cannot be used
44381** for hot-journal rollback. Once this is done the transaction is
44382** irrevocably committed.
44383**
44384** If an error occurs, an IO error code is returned and the pager
44385** moves into the error state. Otherwise, SQLITE_OK is returned.
44386*/
44387SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
44388  int rc = SQLITE_OK;                  /* Return code */
44389
44390  /* This routine should not be called if a prior error has occurred.
44391  ** But if (due to a coding error elsewhere in the system) it does get
44392  ** called, just return the same error code without doing anything. */
44393  if( NEVER(pPager->errCode) ) return pPager->errCode;
44394
44395  assert( pPager->eState==PAGER_WRITER_LOCKED
44396       || pPager->eState==PAGER_WRITER_FINISHED
44397       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
44398  );
44399  assert( assert_pager_state(pPager) );
44400
44401  /* An optimization. If the database was not actually modified during
44402  ** this transaction, the pager is running in exclusive-mode and is
44403  ** using persistent journals, then this function is a no-op.
44404  **
44405  ** The start of the journal file currently contains a single journal
44406  ** header with the nRec field set to 0. If such a journal is used as
44407  ** a hot-journal during hot-journal rollback, 0 changes will be made
44408  ** to the database file. So there is no need to zero the journal
44409  ** header. Since the pager is in exclusive mode, there is no need
44410  ** to drop any locks either.
44411  */
44412  if( pPager->eState==PAGER_WRITER_LOCKED
44413   && pPager->exclusiveMode
44414   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
44415  ){
44416    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
44417    pPager->eState = PAGER_READER;
44418    return SQLITE_OK;
44419  }
44420
44421  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
44422  rc = pager_end_transaction(pPager, pPager->setMaster);
44423  return pager_error(pPager, rc);
44424}
44425
44426/*
44427** If a write transaction is open, then all changes made within the
44428** transaction are reverted and the current write-transaction is closed.
44429** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
44430** state if an error occurs.
44431**
44432** If the pager is already in PAGER_ERROR state when this function is called,
44433** it returns Pager.errCode immediately. No work is performed in this case.
44434**
44435** Otherwise, in rollback mode, this function performs two functions:
44436**
44437**   1) It rolls back the journal file, restoring all database file and
44438**      in-memory cache pages to the state they were in when the transaction
44439**      was opened, and
44440**
44441**   2) It finalizes the journal file, so that it is not used for hot
44442**      rollback at any point in the future.
44443**
44444** Finalization of the journal file (task 2) is only performed if the
44445** rollback is successful.
44446**
44447** In WAL mode, all cache-entries containing data modified within the
44448** current transaction are either expelled from the cache or reverted to
44449** their pre-transaction state by re-reading data from the database or
44450** WAL files. The WAL transaction is then closed.
44451*/
44452SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
44453  int rc = SQLITE_OK;                  /* Return code */
44454  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
44455
44456  /* PagerRollback() is a no-op if called in READER or OPEN state. If
44457  ** the pager is already in the ERROR state, the rollback is not
44458  ** attempted here. Instead, the error code is returned to the caller.
44459  */
44460  assert( assert_pager_state(pPager) );
44461  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
44462  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
44463
44464  if( pagerUseWal(pPager) ){
44465    int rc2;
44466    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
44467    rc2 = pager_end_transaction(pPager, pPager->setMaster);
44468    if( rc==SQLITE_OK ) rc = rc2;
44469  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
44470    int eState = pPager->eState;
44471    rc = pager_end_transaction(pPager, 0);
44472    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
44473      /* This can happen using journal_mode=off. Move the pager to the error
44474      ** state to indicate that the contents of the cache may not be trusted.
44475      ** Any active readers will get SQLITE_ABORT.
44476      */
44477      pPager->errCode = SQLITE_ABORT;
44478      pPager->eState = PAGER_ERROR;
44479      return rc;
44480    }
44481  }else{
44482    rc = pager_playback(pPager, 0);
44483  }
44484
44485  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
44486  assert( rc==SQLITE_OK || rc==SQLITE_FULL
44487          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
44488
44489  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
44490  ** cache. So call pager_error() on the way out to make any error persistent.
44491  */
44492  return pager_error(pPager, rc);
44493}
44494
44495/*
44496** Return TRUE if the database file is opened read-only.  Return FALSE
44497** if the database is (in theory) writable.
44498*/
44499SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
44500  return pPager->readOnly;
44501}
44502
44503/*
44504** Return the number of references to the pager.
44505*/
44506SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
44507  return sqlite3PcacheRefCount(pPager->pPCache);
44508}
44509
44510/*
44511** Return the approximate number of bytes of memory currently
44512** used by the pager and its associated cache.
44513*/
44514SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
44515  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
44516                                     + 5*sizeof(void*);
44517  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
44518           + sqlite3MallocSize(pPager)
44519           + pPager->pageSize;
44520}
44521
44522/*
44523** Return the number of references to the specified page.
44524*/
44525SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
44526  return sqlite3PcachePageRefcount(pPage);
44527}
44528
44529#ifdef SQLITE_TEST
44530/*
44531** This routine is used for testing and analysis only.
44532*/
44533SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
44534  static int a[11];
44535  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
44536  a[1] = sqlite3PcachePagecount(pPager->pPCache);
44537  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
44538  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
44539  a[4] = pPager->eState;
44540  a[5] = pPager->errCode;
44541  a[6] = pPager->nHit;
44542  a[7] = pPager->nMiss;
44543  a[8] = 0;  /* Used to be pPager->nOvfl */
44544  a[9] = pPager->nRead;
44545  a[10] = pPager->nWrite;
44546  return a;
44547}
44548#endif
44549
44550/*
44551** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
44552** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
44553** current cache hit or miss count, according to the value of eStat. If the
44554** reset parameter is non-zero, the cache hit or miss count is zeroed before
44555** returning.
44556*/
44557SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
44558  int *piStat;
44559
44560  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
44561       || eStat==SQLITE_DBSTATUS_CACHE_MISS
44562  );
44563  if( eStat==SQLITE_DBSTATUS_CACHE_HIT ){
44564    piStat = &pPager->nHit;
44565  }else{
44566    piStat = &pPager->nMiss;
44567  }
44568
44569  *pnVal += *piStat;
44570  if( reset ){
44571    *piStat = 0;
44572  }
44573}
44574
44575/*
44576** Return true if this is an in-memory pager.
44577*/
44578SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
44579  return MEMDB;
44580}
44581
44582/*
44583** Check that there are at least nSavepoint savepoints open. If there are
44584** currently less than nSavepoints open, then open one or more savepoints
44585** to make up the difference. If the number of savepoints is already
44586** equal to nSavepoint, then this function is a no-op.
44587**
44588** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
44589** occurs while opening the sub-journal file, then an IO error code is
44590** returned. Otherwise, SQLITE_OK.
44591*/
44592SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
44593  int rc = SQLITE_OK;                       /* Return code */
44594  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
44595
44596  assert( pPager->eState>=PAGER_WRITER_LOCKED );
44597  assert( assert_pager_state(pPager) );
44598
44599  if( nSavepoint>nCurrent && pPager->useJournal ){
44600    int ii;                                 /* Iterator variable */
44601    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
44602
44603    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
44604    ** if the allocation fails. Otherwise, zero the new portion in case a
44605    ** malloc failure occurs while populating it in the for(...) loop below.
44606    */
44607    aNew = (PagerSavepoint *)sqlite3Realloc(
44608        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
44609    );
44610    if( !aNew ){
44611      return SQLITE_NOMEM;
44612    }
44613    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
44614    pPager->aSavepoint = aNew;
44615
44616    /* Populate the PagerSavepoint structures just allocated. */
44617    for(ii=nCurrent; ii<nSavepoint; ii++){
44618      aNew[ii].nOrig = pPager->dbSize;
44619      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
44620        aNew[ii].iOffset = pPager->journalOff;
44621      }else{
44622        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
44623      }
44624      aNew[ii].iSubRec = pPager->nSubRec;
44625      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
44626      if( !aNew[ii].pInSavepoint ){
44627        return SQLITE_NOMEM;
44628      }
44629      if( pagerUseWal(pPager) ){
44630        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
44631      }
44632      pPager->nSavepoint = ii+1;
44633    }
44634    assert( pPager->nSavepoint==nSavepoint );
44635    assertTruncateConstraint(pPager);
44636  }
44637
44638  return rc;
44639}
44640
44641/*
44642** This function is called to rollback or release (commit) a savepoint.
44643** The savepoint to release or rollback need not be the most recently
44644** created savepoint.
44645**
44646** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
44647** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
44648** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
44649** that have occurred since the specified savepoint was created.
44650**
44651** The savepoint to rollback or release is identified by parameter
44652** iSavepoint. A value of 0 means to operate on the outermost savepoint
44653** (the first created). A value of (Pager.nSavepoint-1) means operate
44654** on the most recently created savepoint. If iSavepoint is greater than
44655** (Pager.nSavepoint-1), then this function is a no-op.
44656**
44657** If a negative value is passed to this function, then the current
44658** transaction is rolled back. This is different to calling
44659** sqlite3PagerRollback() because this function does not terminate
44660** the transaction or unlock the database, it just restores the
44661** contents of the database to its original state.
44662**
44663** In any case, all savepoints with an index greater than iSavepoint
44664** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
44665** then savepoint iSavepoint is also destroyed.
44666**
44667** This function may return SQLITE_NOMEM if a memory allocation fails,
44668** or an IO error code if an IO error occurs while rolling back a
44669** savepoint. If no errors occur, SQLITE_OK is returned.
44670*/
44671SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
44672  int rc = pPager->errCode;       /* Return code */
44673
44674  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
44675  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
44676
44677  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
44678    int ii;            /* Iterator variable */
44679    int nNew;          /* Number of remaining savepoints after this op. */
44680
44681    /* Figure out how many savepoints will still be active after this
44682    ** operation. Store this value in nNew. Then free resources associated
44683    ** with any savepoints that are destroyed by this operation.
44684    */
44685    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
44686    for(ii=nNew; ii<pPager->nSavepoint; ii++){
44687      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
44688    }
44689    pPager->nSavepoint = nNew;
44690
44691    /* If this is a release of the outermost savepoint, truncate
44692    ** the sub-journal to zero bytes in size. */
44693    if( op==SAVEPOINT_RELEASE ){
44694      if( nNew==0 && isOpen(pPager->sjfd) ){
44695        /* Only truncate if it is an in-memory sub-journal. */
44696        if( sqlite3IsMemJournal(pPager->sjfd) ){
44697          rc = sqlite3OsTruncate(pPager->sjfd, 0);
44698          assert( rc==SQLITE_OK );
44699        }
44700        pPager->nSubRec = 0;
44701      }
44702    }
44703    /* Else this is a rollback operation, playback the specified savepoint.
44704    ** If this is a temp-file, it is possible that the journal file has
44705    ** not yet been opened. In this case there have been no changes to
44706    ** the database file, so the playback operation can be skipped.
44707    */
44708    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
44709      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
44710      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
44711      assert(rc!=SQLITE_DONE);
44712    }
44713  }
44714
44715  return rc;
44716}
44717
44718/*
44719** Return the full pathname of the database file.
44720*/
44721SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
44722  return pPager->zFilename;
44723}
44724
44725/*
44726** Return the VFS structure for the pager.
44727*/
44728SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
44729  return pPager->pVfs;
44730}
44731
44732/*
44733** Return the file handle for the database file associated
44734** with the pager.  This might return NULL if the file has
44735** not yet been opened.
44736*/
44737SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
44738  return pPager->fd;
44739}
44740
44741/*
44742** Return the full pathname of the journal file.
44743*/
44744SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
44745  return pPager->zJournal;
44746}
44747
44748/*
44749** Return true if fsync() calls are disabled for this pager.  Return FALSE
44750** if fsync()s are executed normally.
44751*/
44752SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
44753  return pPager->noSync;
44754}
44755
44756#ifdef SQLITE_HAS_CODEC
44757/*
44758** Set or retrieve the codec for this pager
44759*/
44760SQLITE_PRIVATE void sqlite3PagerSetCodec(
44761  Pager *pPager,
44762  void *(*xCodec)(void*,void*,Pgno,int),
44763  void (*xCodecSizeChng)(void*,int,int),
44764  void (*xCodecFree)(void*),
44765  void *pCodec
44766){
44767  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
44768  pPager->xCodec = pPager->memDb ? 0 : xCodec;
44769  pPager->xCodecSizeChng = xCodecSizeChng;
44770  pPager->xCodecFree = xCodecFree;
44771  pPager->pCodec = pCodec;
44772  pagerReportSize(pPager);
44773}
44774SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
44775  return pPager->pCodec;
44776}
44777#endif
44778
44779#ifndef SQLITE_OMIT_AUTOVACUUM
44780/*
44781** Move the page pPg to location pgno in the file.
44782**
44783** There must be no references to the page previously located at
44784** pgno (which we call pPgOld) though that page is allowed to be
44785** in cache.  If the page previously located at pgno is not already
44786** in the rollback journal, it is not put there by by this routine.
44787**
44788** References to the page pPg remain valid. Updating any
44789** meta-data associated with pPg (i.e. data stored in the nExtra bytes
44790** allocated along with the page) is the responsibility of the caller.
44791**
44792** A transaction must be active when this routine is called. It used to be
44793** required that a statement transaction was not active, but this restriction
44794** has been removed (CREATE INDEX needs to move a page when a statement
44795** transaction is active).
44796**
44797** If the fourth argument, isCommit, is non-zero, then this page is being
44798** moved as part of a database reorganization just before the transaction
44799** is being committed. In this case, it is guaranteed that the database page
44800** pPg refers to will not be written to again within this transaction.
44801**
44802** This function may return SQLITE_NOMEM or an IO error code if an error
44803** occurs. Otherwise, it returns SQLITE_OK.
44804*/
44805SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
44806  PgHdr *pPgOld;               /* The page being overwritten. */
44807  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
44808  int rc;                      /* Return code */
44809  Pgno origPgno;               /* The original page number */
44810
44811  assert( pPg->nRef>0 );
44812  assert( pPager->eState==PAGER_WRITER_CACHEMOD
44813       || pPager->eState==PAGER_WRITER_DBMOD
44814  );
44815  assert( assert_pager_state(pPager) );
44816
44817  /* In order to be able to rollback, an in-memory database must journal
44818  ** the page we are moving from.
44819  */
44820  if( MEMDB ){
44821    rc = sqlite3PagerWrite(pPg);
44822    if( rc ) return rc;
44823  }
44824
44825  /* If the page being moved is dirty and has not been saved by the latest
44826  ** savepoint, then save the current contents of the page into the
44827  ** sub-journal now. This is required to handle the following scenario:
44828  **
44829  **   BEGIN;
44830  **     <journal page X, then modify it in memory>
44831  **     SAVEPOINT one;
44832  **       <Move page X to location Y>
44833  **     ROLLBACK TO one;
44834  **
44835  ** If page X were not written to the sub-journal here, it would not
44836  ** be possible to restore its contents when the "ROLLBACK TO one"
44837  ** statement were is processed.
44838  **
44839  ** subjournalPage() may need to allocate space to store pPg->pgno into
44840  ** one or more savepoint bitvecs. This is the reason this function
44841  ** may return SQLITE_NOMEM.
44842  */
44843  if( pPg->flags&PGHDR_DIRTY
44844   && subjRequiresPage(pPg)
44845   && SQLITE_OK!=(rc = subjournalPage(pPg))
44846  ){
44847    return rc;
44848  }
44849
44850  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
44851      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
44852  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
44853
44854  /* If the journal needs to be sync()ed before page pPg->pgno can
44855  ** be written to, store pPg->pgno in local variable needSyncPgno.
44856  **
44857  ** If the isCommit flag is set, there is no need to remember that
44858  ** the journal needs to be sync()ed before database page pPg->pgno
44859  ** can be written to. The caller has already promised not to write to it.
44860  */
44861  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
44862    needSyncPgno = pPg->pgno;
44863    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
44864    assert( pPg->flags&PGHDR_DIRTY );
44865  }
44866
44867  /* If the cache contains a page with page-number pgno, remove it
44868  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
44869  ** page pgno before the 'move' operation, it needs to be retained
44870  ** for the page moved there.
44871  */
44872  pPg->flags &= ~PGHDR_NEED_SYNC;
44873  pPgOld = pager_lookup(pPager, pgno);
44874  assert( !pPgOld || pPgOld->nRef==1 );
44875  if( pPgOld ){
44876    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
44877    if( MEMDB ){
44878      /* Do not discard pages from an in-memory database since we might
44879      ** need to rollback later.  Just move the page out of the way. */
44880      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
44881    }else{
44882      sqlite3PcacheDrop(pPgOld);
44883    }
44884  }
44885
44886  origPgno = pPg->pgno;
44887  sqlite3PcacheMove(pPg, pgno);
44888  sqlite3PcacheMakeDirty(pPg);
44889
44890  /* For an in-memory database, make sure the original page continues
44891  ** to exist, in case the transaction needs to roll back.  Use pPgOld
44892  ** as the original page since it has already been allocated.
44893  */
44894  if( MEMDB ){
44895    assert( pPgOld );
44896    sqlite3PcacheMove(pPgOld, origPgno);
44897    sqlite3PagerUnref(pPgOld);
44898  }
44899
44900  if( needSyncPgno ){
44901    /* If needSyncPgno is non-zero, then the journal file needs to be
44902    ** sync()ed before any data is written to database file page needSyncPgno.
44903    ** Currently, no such page exists in the page-cache and the
44904    ** "is journaled" bitvec flag has been set. This needs to be remedied by
44905    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
44906    ** flag.
44907    **
44908    ** If the attempt to load the page into the page-cache fails, (due
44909    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
44910    ** array. Otherwise, if the page is loaded and written again in
44911    ** this transaction, it may be written to the database file before
44912    ** it is synced into the journal file. This way, it may end up in
44913    ** the journal file twice, but that is not a problem.
44914    */
44915    PgHdr *pPgHdr;
44916    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
44917    if( rc!=SQLITE_OK ){
44918      if( needSyncPgno<=pPager->dbOrigSize ){
44919        assert( pPager->pTmpSpace!=0 );
44920        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
44921      }
44922      return rc;
44923    }
44924    pPgHdr->flags |= PGHDR_NEED_SYNC;
44925    sqlite3PcacheMakeDirty(pPgHdr);
44926    sqlite3PagerUnref(pPgHdr);
44927  }
44928
44929  return SQLITE_OK;
44930}
44931#endif
44932
44933/*
44934** Return a pointer to the data for the specified page.
44935*/
44936SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
44937  assert( pPg->nRef>0 || pPg->pPager->memDb );
44938  return pPg->pData;
44939}
44940
44941/*
44942** Return a pointer to the Pager.nExtra bytes of "extra" space
44943** allocated along with the specified page.
44944*/
44945SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
44946  return pPg->pExtra;
44947}
44948
44949/*
44950** Get/set the locking-mode for this pager. Parameter eMode must be one
44951** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
44952** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
44953** the locking-mode is set to the value specified.
44954**
44955** The returned value is either PAGER_LOCKINGMODE_NORMAL or
44956** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
44957** locking-mode.
44958*/
44959SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
44960  assert( eMode==PAGER_LOCKINGMODE_QUERY
44961            || eMode==PAGER_LOCKINGMODE_NORMAL
44962            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
44963  assert( PAGER_LOCKINGMODE_QUERY<0 );
44964  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
44965  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
44966  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
44967    pPager->exclusiveMode = (u8)eMode;
44968  }
44969  return (int)pPager->exclusiveMode;
44970}
44971
44972/*
44973** Set the journal-mode for this pager. Parameter eMode must be one of:
44974**
44975**    PAGER_JOURNALMODE_DELETE
44976**    PAGER_JOURNALMODE_TRUNCATE
44977**    PAGER_JOURNALMODE_PERSIST
44978**    PAGER_JOURNALMODE_OFF
44979**    PAGER_JOURNALMODE_MEMORY
44980**    PAGER_JOURNALMODE_WAL
44981**
44982** The journalmode is set to the value specified if the change is allowed.
44983** The change may be disallowed for the following reasons:
44984**
44985**   *  An in-memory database can only have its journal_mode set to _OFF
44986**      or _MEMORY.
44987**
44988**   *  Temporary databases cannot have _WAL journalmode.
44989**
44990** The returned indicate the current (possibly updated) journal-mode.
44991*/
44992SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
44993  u8 eOld = pPager->journalMode;    /* Prior journalmode */
44994
44995#ifdef SQLITE_DEBUG
44996  /* The print_pager_state() routine is intended to be used by the debugger
44997  ** only.  We invoke it once here to suppress a compiler warning. */
44998  print_pager_state(pPager);
44999#endif
45000
45001
45002  /* The eMode parameter is always valid */
45003  assert(      eMode==PAGER_JOURNALMODE_DELETE
45004            || eMode==PAGER_JOURNALMODE_TRUNCATE
45005            || eMode==PAGER_JOURNALMODE_PERSIST
45006            || eMode==PAGER_JOURNALMODE_OFF
45007            || eMode==PAGER_JOURNALMODE_WAL
45008            || eMode==PAGER_JOURNALMODE_MEMORY );
45009
45010  /* This routine is only called from the OP_JournalMode opcode, and
45011  ** the logic there will never allow a temporary file to be changed
45012  ** to WAL mode.
45013  */
45014  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
45015
45016  /* Do allow the journalmode of an in-memory database to be set to
45017  ** anything other than MEMORY or OFF
45018  */
45019  if( MEMDB ){
45020    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
45021    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
45022      eMode = eOld;
45023    }
45024  }
45025
45026  if( eMode!=eOld ){
45027
45028    /* Change the journal mode. */
45029    assert( pPager->eState!=PAGER_ERROR );
45030    pPager->journalMode = (u8)eMode;
45031
45032    /* When transistioning from TRUNCATE or PERSIST to any other journal
45033    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
45034    ** delete the journal file.
45035    */
45036    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
45037    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
45038    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
45039    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
45040    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
45041    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
45042
45043    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
45044    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
45045
45046      /* In this case we would like to delete the journal file. If it is
45047      ** not possible, then that is not a problem. Deleting the journal file
45048      ** here is an optimization only.
45049      **
45050      ** Before deleting the journal file, obtain a RESERVED lock on the
45051      ** database file. This ensures that the journal file is not deleted
45052      ** while it is in use by some other client.
45053      */
45054      sqlite3OsClose(pPager->jfd);
45055      if( pPager->eLock>=RESERVED_LOCK ){
45056        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45057      }else{
45058        int rc = SQLITE_OK;
45059        int state = pPager->eState;
45060        assert( state==PAGER_OPEN || state==PAGER_READER );
45061        if( state==PAGER_OPEN ){
45062          rc = sqlite3PagerSharedLock(pPager);
45063        }
45064        if( pPager->eState==PAGER_READER ){
45065          assert( rc==SQLITE_OK );
45066          rc = pagerLockDb(pPager, RESERVED_LOCK);
45067        }
45068        if( rc==SQLITE_OK ){
45069          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45070        }
45071        if( rc==SQLITE_OK && state==PAGER_READER ){
45072          pagerUnlockDb(pPager, SHARED_LOCK);
45073        }else if( state==PAGER_OPEN ){
45074          pager_unlock(pPager);
45075        }
45076        assert( state==pPager->eState );
45077      }
45078    }
45079  }
45080
45081  /* Return the new journal mode */
45082  return (int)pPager->journalMode;
45083}
45084
45085/*
45086** Return the current journal mode.
45087*/
45088SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
45089  return (int)pPager->journalMode;
45090}
45091
45092/*
45093** Return TRUE if the pager is in a state where it is OK to change the
45094** journalmode.  Journalmode changes can only happen when the database
45095** is unmodified.
45096*/
45097SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
45098  assert( assert_pager_state(pPager) );
45099  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
45100  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
45101  return 1;
45102}
45103
45104/*
45105** Get/set the size-limit used for persistent journal files.
45106**
45107** Setting the size limit to -1 means no limit is enforced.
45108** An attempt to set a limit smaller than -1 is a no-op.
45109*/
45110SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
45111  if( iLimit>=-1 ){
45112    pPager->journalSizeLimit = iLimit;
45113    sqlite3WalLimit(pPager->pWal, iLimit);
45114  }
45115  return pPager->journalSizeLimit;
45116}
45117
45118/*
45119** Return a pointer to the pPager->pBackup variable. The backup module
45120** in backup.c maintains the content of this variable. This module
45121** uses it opaquely as an argument to sqlite3BackupRestart() and
45122** sqlite3BackupUpdate() only.
45123*/
45124SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
45125  return &pPager->pBackup;
45126}
45127
45128#ifndef SQLITE_OMIT_VACUUM
45129/*
45130** Unless this is an in-memory or temporary database, clear the pager cache.
45131*/
45132SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
45133  if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
45134}
45135#endif
45136
45137#ifndef SQLITE_OMIT_WAL
45138/*
45139** This function is called when the user invokes "PRAGMA wal_checkpoint",
45140** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
45141** or wal_blocking_checkpoint() API functions.
45142**
45143** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
45144*/
45145SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
45146  int rc = SQLITE_OK;
45147  if( pPager->pWal ){
45148    rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
45149        pPager->xBusyHandler, pPager->pBusyHandlerArg,
45150        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
45151        pnLog, pnCkpt
45152    );
45153  }
45154  return rc;
45155}
45156
45157SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
45158  return sqlite3WalCallback(pPager->pWal);
45159}
45160
45161/*
45162** Return true if the underlying VFS for the given pager supports the
45163** primitives necessary for write-ahead logging.
45164*/
45165SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
45166  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
45167  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
45168}
45169
45170/*
45171** Attempt to take an exclusive lock on the database file. If a PENDING lock
45172** is obtained instead, immediately release it.
45173*/
45174static int pagerExclusiveLock(Pager *pPager){
45175  int rc;                         /* Return code */
45176
45177  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
45178  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
45179  if( rc!=SQLITE_OK ){
45180    /* If the attempt to grab the exclusive lock failed, release the
45181    ** pending lock that may have been obtained instead.  */
45182    pagerUnlockDb(pPager, SHARED_LOCK);
45183  }
45184
45185  return rc;
45186}
45187
45188/*
45189** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
45190** exclusive-locking mode when this function is called, take an EXCLUSIVE
45191** lock on the database file and use heap-memory to store the wal-index
45192** in. Otherwise, use the normal shared-memory.
45193*/
45194static int pagerOpenWal(Pager *pPager){
45195  int rc = SQLITE_OK;
45196
45197  assert( pPager->pWal==0 && pPager->tempFile==0 );
45198  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
45199
45200  /* If the pager is already in exclusive-mode, the WAL module will use
45201  ** heap-memory for the wal-index instead of the VFS shared-memory
45202  ** implementation. Take the exclusive lock now, before opening the WAL
45203  ** file, to make sure this is safe.
45204  */
45205  if( pPager->exclusiveMode ){
45206    rc = pagerExclusiveLock(pPager);
45207  }
45208
45209  /* Open the connection to the log file. If this operation fails,
45210  ** (e.g. due to malloc() failure), return an error code.
45211  */
45212  if( rc==SQLITE_OK ){
45213    rc = sqlite3WalOpen(pPager->pVfs,
45214        pPager->fd, pPager->zWal, pPager->exclusiveMode,
45215        pPager->journalSizeLimit, &pPager->pWal
45216    );
45217  }
45218
45219  return rc;
45220}
45221
45222
45223/*
45224** The caller must be holding a SHARED lock on the database file to call
45225** this function.
45226**
45227** If the pager passed as the first argument is open on a real database
45228** file (not a temp file or an in-memory database), and the WAL file
45229** is not already open, make an attempt to open it now. If successful,
45230** return SQLITE_OK. If an error occurs or the VFS used by the pager does
45231** not support the xShmXXX() methods, return an error code. *pbOpen is
45232** not modified in either case.
45233**
45234** If the pager is open on a temp-file (or in-memory database), or if
45235** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
45236** without doing anything.
45237*/
45238SQLITE_PRIVATE int sqlite3PagerOpenWal(
45239  Pager *pPager,                  /* Pager object */
45240  int *pbOpen                     /* OUT: Set to true if call is a no-op */
45241){
45242  int rc = SQLITE_OK;             /* Return code */
45243
45244  assert( assert_pager_state(pPager) );
45245  assert( pPager->eState==PAGER_OPEN   || pbOpen );
45246  assert( pPager->eState==PAGER_READER || !pbOpen );
45247  assert( pbOpen==0 || *pbOpen==0 );
45248  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
45249
45250  if( !pPager->tempFile && !pPager->pWal ){
45251    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
45252
45253    /* Close any rollback journal previously open */
45254    sqlite3OsClose(pPager->jfd);
45255
45256    rc = pagerOpenWal(pPager);
45257    if( rc==SQLITE_OK ){
45258      pPager->journalMode = PAGER_JOURNALMODE_WAL;
45259      pPager->eState = PAGER_OPEN;
45260    }
45261  }else{
45262    *pbOpen = 1;
45263  }
45264
45265  return rc;
45266}
45267
45268/*
45269** This function is called to close the connection to the log file prior
45270** to switching from WAL to rollback mode.
45271**
45272** Before closing the log file, this function attempts to take an
45273** EXCLUSIVE lock on the database file. If this cannot be obtained, an
45274** error (SQLITE_BUSY) is returned and the log connection is not closed.
45275** If successful, the EXCLUSIVE lock is not released before returning.
45276*/
45277SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
45278  int rc = SQLITE_OK;
45279
45280  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
45281
45282  /* If the log file is not already open, but does exist in the file-system,
45283  ** it may need to be checkpointed before the connection can switch to
45284  ** rollback mode. Open it now so this can happen.
45285  */
45286  if( !pPager->pWal ){
45287    int logexists = 0;
45288    rc = pagerLockDb(pPager, SHARED_LOCK);
45289    if( rc==SQLITE_OK ){
45290      rc = sqlite3OsAccess(
45291          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
45292      );
45293    }
45294    if( rc==SQLITE_OK && logexists ){
45295      rc = pagerOpenWal(pPager);
45296    }
45297  }
45298
45299  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
45300  ** the database file, the log and log-summary files will be deleted.
45301  */
45302  if( rc==SQLITE_OK && pPager->pWal ){
45303    rc = pagerExclusiveLock(pPager);
45304    if( rc==SQLITE_OK ){
45305      rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
45306                           pPager->pageSize, (u8*)pPager->pTmpSpace);
45307      pPager->pWal = 0;
45308    }
45309  }
45310  return rc;
45311}
45312
45313#ifdef SQLITE_ENABLE_ZIPVFS
45314/*
45315** A read-lock must be held on the pager when this function is called. If
45316** the pager is in WAL mode and the WAL file currently contains one or more
45317** frames, return the size in bytes of the page images stored within the
45318** WAL frames. Otherwise, if this is not a WAL database or the WAL file
45319** is empty, return 0.
45320*/
45321SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
45322  assert( pPager->eState==PAGER_READER );
45323  return sqlite3WalFramesize(pPager->pWal);
45324}
45325#endif
45326
45327#ifdef SQLITE_HAS_CODEC
45328/*
45329** This function is called by the wal module when writing page content
45330** into the log file.
45331**
45332** This function returns a pointer to a buffer containing the encrypted
45333** page content. If a malloc fails, this function may return NULL.
45334*/
45335SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
45336  void *aData = 0;
45337  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
45338  return aData;
45339}
45340#endif /* SQLITE_HAS_CODEC */
45341
45342#endif /* !SQLITE_OMIT_WAL */
45343
45344#endif /* SQLITE_OMIT_DISKIO */
45345
45346/************** End of pager.c ***********************************************/
45347/************** Begin file wal.c *********************************************/
45348/*
45349** 2010 February 1
45350**
45351** The author disclaims copyright to this source code.  In place of
45352** a legal notice, here is a blessing:
45353**
45354**    May you do good and not evil.
45355**    May you find forgiveness for yourself and forgive others.
45356**    May you share freely, never taking more than you give.
45357**
45358*************************************************************************
45359**
45360** This file contains the implementation of a write-ahead log (WAL) used in
45361** "journal_mode=WAL" mode.
45362**
45363** WRITE-AHEAD LOG (WAL) FILE FORMAT
45364**
45365** A WAL file consists of a header followed by zero or more "frames".
45366** Each frame records the revised content of a single page from the
45367** database file.  All changes to the database are recorded by writing
45368** frames into the WAL.  Transactions commit when a frame is written that
45369** contains a commit marker.  A single WAL can and usually does record
45370** multiple transactions.  Periodically, the content of the WAL is
45371** transferred back into the database file in an operation called a
45372** "checkpoint".
45373**
45374** A single WAL file can be used multiple times.  In other words, the
45375** WAL can fill up with frames and then be checkpointed and then new
45376** frames can overwrite the old ones.  A WAL always grows from beginning
45377** toward the end.  Checksums and counters attached to each frame are
45378** used to determine which frames within the WAL are valid and which
45379** are leftovers from prior checkpoints.
45380**
45381** The WAL header is 32 bytes in size and consists of the following eight
45382** big-endian 32-bit unsigned integer values:
45383**
45384**     0: Magic number.  0x377f0682 or 0x377f0683
45385**     4: File format version.  Currently 3007000
45386**     8: Database page size.  Example: 1024
45387**    12: Checkpoint sequence number
45388**    16: Salt-1, random integer incremented with each checkpoint
45389**    20: Salt-2, a different random integer changing with each ckpt
45390**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
45391**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
45392**
45393** Immediately following the wal-header are zero or more frames. Each
45394** frame consists of a 24-byte frame-header followed by a <page-size> bytes
45395** of page data. The frame-header is six big-endian 32-bit unsigned
45396** integer values, as follows:
45397**
45398**     0: Page number.
45399**     4: For commit records, the size of the database image in pages
45400**        after the commit. For all other records, zero.
45401**     8: Salt-1 (copied from the header)
45402**    12: Salt-2 (copied from the header)
45403**    16: Checksum-1.
45404**    20: Checksum-2.
45405**
45406** A frame is considered valid if and only if the following conditions are
45407** true:
45408**
45409**    (1) The salt-1 and salt-2 values in the frame-header match
45410**        salt values in the wal-header
45411**
45412**    (2) The checksum values in the final 8 bytes of the frame-header
45413**        exactly match the checksum computed consecutively on the
45414**        WAL header and the first 8 bytes and the content of all frames
45415**        up to and including the current frame.
45416**
45417** The checksum is computed using 32-bit big-endian integers if the
45418** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
45419** is computed using little-endian if the magic number is 0x377f0682.
45420** The checksum values are always stored in the frame header in a
45421** big-endian format regardless of which byte order is used to compute
45422** the checksum.  The checksum is computed by interpreting the input as
45423** an even number of unsigned 32-bit integers: x[0] through x[N].  The
45424** algorithm used for the checksum is as follows:
45425**
45426**   for i from 0 to n-1 step 2:
45427**     s0 += x[i] + s1;
45428**     s1 += x[i+1] + s0;
45429**   endfor
45430**
45431** Note that s0 and s1 are both weighted checksums using fibonacci weights
45432** in reverse order (the largest fibonacci weight occurs on the first element
45433** of the sequence being summed.)  The s1 value spans all 32-bit
45434** terms of the sequence whereas s0 omits the final term.
45435**
45436** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
45437** WAL is transferred into the database, then the database is VFS.xSync-ed.
45438** The VFS.xSync operations serve as write barriers - all writes launched
45439** before the xSync must complete before any write that launches after the
45440** xSync begins.
45441**
45442** After each checkpoint, the salt-1 value is incremented and the salt-2
45443** value is randomized.  This prevents old and new frames in the WAL from
45444** being considered valid at the same time and being checkpointing together
45445** following a crash.
45446**
45447** READER ALGORITHM
45448**
45449** To read a page from the database (call it page number P), a reader
45450** first checks the WAL to see if it contains page P.  If so, then the
45451** last valid instance of page P that is a followed by a commit frame
45452** or is a commit frame itself becomes the value read.  If the WAL
45453** contains no copies of page P that are valid and which are a commit
45454** frame or are followed by a commit frame, then page P is read from
45455** the database file.
45456**
45457** To start a read transaction, the reader records the index of the last
45458** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
45459** for all subsequent read operations.  New transactions can be appended
45460** to the WAL, but as long as the reader uses its original mxFrame value
45461** and ignores the newly appended content, it will see a consistent snapshot
45462** of the database from a single point in time.  This technique allows
45463** multiple concurrent readers to view different versions of the database
45464** content simultaneously.
45465**
45466** The reader algorithm in the previous paragraphs works correctly, but
45467** because frames for page P can appear anywhere within the WAL, the
45468** reader has to scan the entire WAL looking for page P frames.  If the
45469** WAL is large (multiple megabytes is typical) that scan can be slow,
45470** and read performance suffers.  To overcome this problem, a separate
45471** data structure called the wal-index is maintained to expedite the
45472** search for frames of a particular page.
45473**
45474** WAL-INDEX FORMAT
45475**
45476** Conceptually, the wal-index is shared memory, though VFS implementations
45477** might choose to implement the wal-index using a mmapped file.  Because
45478** the wal-index is shared memory, SQLite does not support journal_mode=WAL
45479** on a network filesystem.  All users of the database must be able to
45480** share memory.
45481**
45482** The wal-index is transient.  After a crash, the wal-index can (and should
45483** be) reconstructed from the original WAL file.  In fact, the VFS is required
45484** to either truncate or zero the header of the wal-index when the last
45485** connection to it closes.  Because the wal-index is transient, it can
45486** use an architecture-specific format; it does not have to be cross-platform.
45487** Hence, unlike the database and WAL file formats which store all values
45488** as big endian, the wal-index can store multi-byte values in the native
45489** byte order of the host computer.
45490**
45491** The purpose of the wal-index is to answer this question quickly:  Given
45492** a page number P, return the index of the last frame for page P in the WAL,
45493** or return NULL if there are no frames for page P in the WAL.
45494**
45495** The wal-index consists of a header region, followed by an one or
45496** more index blocks.
45497**
45498** The wal-index header contains the total number of frames within the WAL
45499** in the the mxFrame field.
45500**
45501** Each index block except for the first contains information on
45502** HASHTABLE_NPAGE frames. The first index block contains information on
45503** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
45504** HASHTABLE_NPAGE are selected so that together the wal-index header and
45505** first index block are the same size as all other index blocks in the
45506** wal-index.
45507**
45508** Each index block contains two sections, a page-mapping that contains the
45509** database page number associated with each wal frame, and a hash-table
45510** that allows readers to query an index block for a specific page number.
45511** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
45512** for the first index block) 32-bit page numbers. The first entry in the
45513** first index-block contains the database page number corresponding to the
45514** first frame in the WAL file. The first entry in the second index block
45515** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
45516** the log, and so on.
45517**
45518** The last index block in a wal-index usually contains less than the full
45519** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
45520** depending on the contents of the WAL file. This does not change the
45521** allocated size of the page-mapping array - the page-mapping array merely
45522** contains unused entries.
45523**
45524** Even without using the hash table, the last frame for page P
45525** can be found by scanning the page-mapping sections of each index block
45526** starting with the last index block and moving toward the first, and
45527** within each index block, starting at the end and moving toward the
45528** beginning.  The first entry that equals P corresponds to the frame
45529** holding the content for that page.
45530**
45531** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
45532** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
45533** hash table for each page number in the mapping section, so the hash
45534** table is never more than half full.  The expected number of collisions
45535** prior to finding a match is 1.  Each entry of the hash table is an
45536** 1-based index of an entry in the mapping section of the same
45537** index block.   Let K be the 1-based index of the largest entry in
45538** the mapping section.  (For index blocks other than the last, K will
45539** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
45540** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
45541** contain a value of 0.
45542**
45543** To look for page P in the hash table, first compute a hash iKey on
45544** P as follows:
45545**
45546**      iKey = (P * 383) % HASHTABLE_NSLOT
45547**
45548** Then start scanning entries of the hash table, starting with iKey
45549** (wrapping around to the beginning when the end of the hash table is
45550** reached) until an unused hash slot is found. Let the first unused slot
45551** be at index iUnused.  (iUnused might be less than iKey if there was
45552** wrap-around.) Because the hash table is never more than half full,
45553** the search is guaranteed to eventually hit an unused entry.  Let
45554** iMax be the value between iKey and iUnused, closest to iUnused,
45555** where aHash[iMax]==P.  If there is no iMax entry (if there exists
45556** no hash slot such that aHash[i]==p) then page P is not in the
45557** current index block.  Otherwise the iMax-th mapping entry of the
45558** current index block corresponds to the last entry that references
45559** page P.
45560**
45561** A hash search begins with the last index block and moves toward the
45562** first index block, looking for entries corresponding to page P.  On
45563** average, only two or three slots in each index block need to be
45564** examined in order to either find the last entry for page P, or to
45565** establish that no such entry exists in the block.  Each index block
45566** holds over 4000 entries.  So two or three index blocks are sufficient
45567** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
45568** comparisons (on average) suffice to either locate a frame in the
45569** WAL or to establish that the frame does not exist in the WAL.  This
45570** is much faster than scanning the entire 10MB WAL.
45571**
45572** Note that entries are added in order of increasing K.  Hence, one
45573** reader might be using some value K0 and a second reader that started
45574** at a later time (after additional transactions were added to the WAL
45575** and to the wal-index) might be using a different value K1, where K1>K0.
45576** Both readers can use the same hash table and mapping section to get
45577** the correct result.  There may be entries in the hash table with
45578** K>K0 but to the first reader, those entries will appear to be unused
45579** slots in the hash table and so the first reader will get an answer as
45580** if no values greater than K0 had ever been inserted into the hash table
45581** in the first place - which is what reader one wants.  Meanwhile, the
45582** second reader using K1 will see additional values that were inserted
45583** later, which is exactly what reader two wants.
45584**
45585** When a rollback occurs, the value of K is decreased. Hash table entries
45586** that correspond to frames greater than the new K value are removed
45587** from the hash table at this point.
45588*/
45589#ifndef SQLITE_OMIT_WAL
45590
45591
45592/*
45593** Trace output macros
45594*/
45595#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45596SQLITE_PRIVATE int sqlite3WalTrace = 0;
45597# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
45598#else
45599# define WALTRACE(X)
45600#endif
45601
45602/*
45603** The maximum (and only) versions of the wal and wal-index formats
45604** that may be interpreted by this version of SQLite.
45605**
45606** If a client begins recovering a WAL file and finds that (a) the checksum
45607** values in the wal-header are correct and (b) the version field is not
45608** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
45609**
45610** Similarly, if a client successfully reads a wal-index header (i.e. the
45611** checksum test is successful) and finds that the version field is not
45612** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
45613** returns SQLITE_CANTOPEN.
45614*/
45615#define WAL_MAX_VERSION      3007000
45616#define WALINDEX_MAX_VERSION 3007000
45617
45618/*
45619** Indices of various locking bytes.   WAL_NREADER is the number
45620** of available reader locks and should be at least 3.
45621*/
45622#define WAL_WRITE_LOCK         0
45623#define WAL_ALL_BUT_WRITE      1
45624#define WAL_CKPT_LOCK          1
45625#define WAL_RECOVER_LOCK       2
45626#define WAL_READ_LOCK(I)       (3+(I))
45627#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
45628
45629
45630/* Object declarations */
45631typedef struct WalIndexHdr WalIndexHdr;
45632typedef struct WalIterator WalIterator;
45633typedef struct WalCkptInfo WalCkptInfo;
45634
45635
45636/*
45637** The following object holds a copy of the wal-index header content.
45638**
45639** The actual header in the wal-index consists of two copies of this
45640** object.
45641**
45642** The szPage value can be any power of 2 between 512 and 32768, inclusive.
45643** Or it can be 1 to represent a 65536-byte page.  The latter case was
45644** added in 3.7.1 when support for 64K pages was added.
45645*/
45646struct WalIndexHdr {
45647  u32 iVersion;                   /* Wal-index version */
45648  u32 unused;                     /* Unused (padding) field */
45649  u32 iChange;                    /* Counter incremented each transaction */
45650  u8 isInit;                      /* 1 when initialized */
45651  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
45652  u16 szPage;                     /* Database page size in bytes. 1==64K */
45653  u32 mxFrame;                    /* Index of last valid frame in the WAL */
45654  u32 nPage;                      /* Size of database in pages */
45655  u32 aFrameCksum[2];             /* Checksum of last frame in log */
45656  u32 aSalt[2];                   /* Two salt values copied from WAL header */
45657  u32 aCksum[2];                  /* Checksum over all prior fields */
45658};
45659
45660/*
45661** A copy of the following object occurs in the wal-index immediately
45662** following the second copy of the WalIndexHdr.  This object stores
45663** information used by checkpoint.
45664**
45665** nBackfill is the number of frames in the WAL that have been written
45666** back into the database. (We call the act of moving content from WAL to
45667** database "backfilling".)  The nBackfill number is never greater than
45668** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
45669** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
45670** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
45671** mxFrame back to zero when the WAL is reset.
45672**
45673** There is one entry in aReadMark[] for each reader lock.  If a reader
45674** holds read-lock K, then the value in aReadMark[K] is no greater than
45675** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
45676** for any aReadMark[] means that entry is unused.  aReadMark[0] is
45677** a special case; its value is never used and it exists as a place-holder
45678** to avoid having to offset aReadMark[] indexs by one.  Readers holding
45679** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
45680** directly from the database.
45681**
45682** The value of aReadMark[K] may only be changed by a thread that
45683** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
45684** aReadMark[K] cannot changed while there is a reader is using that mark
45685** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
45686**
45687** The checkpointer may only transfer frames from WAL to database where
45688** the frame numbers are less than or equal to every aReadMark[] that is
45689** in use (that is, every aReadMark[j] for which there is a corresponding
45690** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
45691** largest value and will increase an unused aReadMark[] to mxFrame if there
45692** is not already an aReadMark[] equal to mxFrame.  The exception to the
45693** previous sentence is when nBackfill equals mxFrame (meaning that everything
45694** in the WAL has been backfilled into the database) then new readers
45695** will choose aReadMark[0] which has value 0 and hence such reader will
45696** get all their all content directly from the database file and ignore
45697** the WAL.
45698**
45699** Writers normally append new frames to the end of the WAL.  However,
45700** if nBackfill equals mxFrame (meaning that all WAL content has been
45701** written back into the database) and if no readers are using the WAL
45702** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
45703** the writer will first "reset" the WAL back to the beginning and start
45704** writing new content beginning at frame 1.
45705**
45706** We assume that 32-bit loads are atomic and so no locks are needed in
45707** order to read from any aReadMark[] entries.
45708*/
45709struct WalCkptInfo {
45710  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
45711  u32 aReadMark[WAL_NREADER];     /* Reader marks */
45712};
45713#define READMARK_NOT_USED  0xffffffff
45714
45715
45716/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
45717** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
45718** only support mandatory file-locks, we do not read or write data
45719** from the region of the file on which locks are applied.
45720*/
45721#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
45722#define WALINDEX_LOCK_RESERVED 16
45723#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
45724
45725/* Size of header before each frame in wal */
45726#define WAL_FRAME_HDRSIZE 24
45727
45728/* Size of write ahead log header, including checksum. */
45729/* #define WAL_HDRSIZE 24 */
45730#define WAL_HDRSIZE 32
45731
45732/* WAL magic value. Either this value, or the same value with the least
45733** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
45734** big-endian format in the first 4 bytes of a WAL file.
45735**
45736** If the LSB is set, then the checksums for each frame within the WAL
45737** file are calculated by treating all data as an array of 32-bit
45738** big-endian words. Otherwise, they are calculated by interpreting
45739** all data as 32-bit little-endian words.
45740*/
45741#define WAL_MAGIC 0x377f0682
45742
45743/*
45744** Return the offset of frame iFrame in the write-ahead log file,
45745** assuming a database page size of szPage bytes. The offset returned
45746** is to the start of the write-ahead log frame-header.
45747*/
45748#define walFrameOffset(iFrame, szPage) (                               \
45749  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
45750)
45751
45752/*
45753** An open write-ahead log file is represented by an instance of the
45754** following object.
45755*/
45756struct Wal {
45757  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
45758  sqlite3_file *pDbFd;       /* File handle for the database file */
45759  sqlite3_file *pWalFd;      /* File handle for WAL file */
45760  u32 iCallback;             /* Value to pass to log callback (or 0) */
45761  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
45762  int nWiData;               /* Size of array apWiData */
45763  int szFirstBlock;          /* Size of first block written to WAL file */
45764  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
45765  u32 szPage;                /* Database page size */
45766  i16 readLock;              /* Which read lock is being held.  -1 for none */
45767  u8 syncFlags;              /* Flags to use to sync header writes */
45768  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
45769  u8 writeLock;              /* True if in a write transaction */
45770  u8 ckptLock;               /* True if holding a checkpoint lock */
45771  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
45772  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
45773  u8 syncHeader;             /* Fsync the WAL header if true */
45774  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
45775  WalIndexHdr hdr;           /* Wal-index header for current transaction */
45776  const char *zWalName;      /* Name of WAL file */
45777  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
45778#ifdef SQLITE_DEBUG
45779  u8 lockError;              /* True if a locking error has occurred */
45780#endif
45781};
45782
45783/*
45784** Candidate values for Wal.exclusiveMode.
45785*/
45786#define WAL_NORMAL_MODE     0
45787#define WAL_EXCLUSIVE_MODE  1
45788#define WAL_HEAPMEMORY_MODE 2
45789
45790/*
45791** Possible values for WAL.readOnly
45792*/
45793#define WAL_RDWR        0    /* Normal read/write connection */
45794#define WAL_RDONLY      1    /* The WAL file is readonly */
45795#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
45796
45797/*
45798** Each page of the wal-index mapping contains a hash-table made up of
45799** an array of HASHTABLE_NSLOT elements of the following type.
45800*/
45801typedef u16 ht_slot;
45802
45803/*
45804** This structure is used to implement an iterator that loops through
45805** all frames in the WAL in database page order. Where two or more frames
45806** correspond to the same database page, the iterator visits only the
45807** frame most recently written to the WAL (in other words, the frame with
45808** the largest index).
45809**
45810** The internals of this structure are only accessed by:
45811**
45812**   walIteratorInit() - Create a new iterator,
45813**   walIteratorNext() - Step an iterator,
45814**   walIteratorFree() - Free an iterator.
45815**
45816** This functionality is used by the checkpoint code (see walCheckpoint()).
45817*/
45818struct WalIterator {
45819  int iPrior;                     /* Last result returned from the iterator */
45820  int nSegment;                   /* Number of entries in aSegment[] */
45821  struct WalSegment {
45822    int iNext;                    /* Next slot in aIndex[] not yet returned */
45823    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
45824    u32 *aPgno;                   /* Array of page numbers. */
45825    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
45826    int iZero;                    /* Frame number associated with aPgno[0] */
45827  } aSegment[1];                  /* One for every 32KB page in the wal-index */
45828};
45829
45830/*
45831** Define the parameters of the hash tables in the wal-index file. There
45832** is a hash-table following every HASHTABLE_NPAGE page numbers in the
45833** wal-index.
45834**
45835** Changing any of these constants will alter the wal-index format and
45836** create incompatibilities.
45837*/
45838#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
45839#define HASHTABLE_HASH_1     383                  /* Should be prime */
45840#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
45841
45842/*
45843** The block of page numbers associated with the first hash-table in a
45844** wal-index is smaller than usual. This is so that there is a complete
45845** hash-table on each aligned 32KB page of the wal-index.
45846*/
45847#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
45848
45849/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
45850#define WALINDEX_PGSZ   (                                         \
45851    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
45852)
45853
45854/*
45855** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
45856** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
45857** numbered from zero.
45858**
45859** If this call is successful, *ppPage is set to point to the wal-index
45860** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
45861** then an SQLite error code is returned and *ppPage is set to 0.
45862*/
45863static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
45864  int rc = SQLITE_OK;
45865
45866  /* Enlarge the pWal->apWiData[] array if required */
45867  if( pWal->nWiData<=iPage ){
45868    int nByte = sizeof(u32*)*(iPage+1);
45869    volatile u32 **apNew;
45870    apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
45871    if( !apNew ){
45872      *ppPage = 0;
45873      return SQLITE_NOMEM;
45874    }
45875    memset((void*)&apNew[pWal->nWiData], 0,
45876           sizeof(u32*)*(iPage+1-pWal->nWiData));
45877    pWal->apWiData = apNew;
45878    pWal->nWiData = iPage+1;
45879  }
45880
45881  /* Request a pointer to the required page from the VFS */
45882  if( pWal->apWiData[iPage]==0 ){
45883    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
45884      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
45885      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
45886    }else{
45887      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
45888          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
45889      );
45890      if( rc==SQLITE_READONLY ){
45891        pWal->readOnly |= WAL_SHM_RDONLY;
45892        rc = SQLITE_OK;
45893      }
45894    }
45895  }
45896
45897  *ppPage = pWal->apWiData[iPage];
45898  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
45899  return rc;
45900}
45901
45902/*
45903** Return a pointer to the WalCkptInfo structure in the wal-index.
45904*/
45905static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
45906  assert( pWal->nWiData>0 && pWal->apWiData[0] );
45907  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
45908}
45909
45910/*
45911** Return a pointer to the WalIndexHdr structure in the wal-index.
45912*/
45913static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
45914  assert( pWal->nWiData>0 && pWal->apWiData[0] );
45915  return (volatile WalIndexHdr*)pWal->apWiData[0];
45916}
45917
45918/*
45919** The argument to this macro must be of type u32. On a little-endian
45920** architecture, it returns the u32 value that results from interpreting
45921** the 4 bytes as a big-endian value. On a big-endian architecture, it
45922** returns the value that would be produced by intepreting the 4 bytes
45923** of the input value as a little-endian integer.
45924*/
45925#define BYTESWAP32(x) ( \
45926    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
45927  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
45928)
45929
45930/*
45931** Generate or extend an 8 byte checksum based on the data in
45932** array aByte[] and the initial values of aIn[0] and aIn[1] (or
45933** initial values of 0 and 0 if aIn==NULL).
45934**
45935** The checksum is written back into aOut[] before returning.
45936**
45937** nByte must be a positive multiple of 8.
45938*/
45939static void walChecksumBytes(
45940  int nativeCksum, /* True for native byte-order, false for non-native */
45941  u8 *a,           /* Content to be checksummed */
45942  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
45943  const u32 *aIn,  /* Initial checksum value input */
45944  u32 *aOut        /* OUT: Final checksum value output */
45945){
45946  u32 s1, s2;
45947  u32 *aData = (u32 *)a;
45948  u32 *aEnd = (u32 *)&a[nByte];
45949
45950  if( aIn ){
45951    s1 = aIn[0];
45952    s2 = aIn[1];
45953  }else{
45954    s1 = s2 = 0;
45955  }
45956
45957  assert( nByte>=8 );
45958  assert( (nByte&0x00000007)==0 );
45959
45960  if( nativeCksum ){
45961    do {
45962      s1 += *aData++ + s2;
45963      s2 += *aData++ + s1;
45964    }while( aData<aEnd );
45965  }else{
45966    do {
45967      s1 += BYTESWAP32(aData[0]) + s2;
45968      s2 += BYTESWAP32(aData[1]) + s1;
45969      aData += 2;
45970    }while( aData<aEnd );
45971  }
45972
45973  aOut[0] = s1;
45974  aOut[1] = s2;
45975}
45976
45977static void walShmBarrier(Wal *pWal){
45978  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
45979    sqlite3OsShmBarrier(pWal->pDbFd);
45980  }
45981}
45982
45983/*
45984** Write the header information in pWal->hdr into the wal-index.
45985**
45986** The checksum on pWal->hdr is updated before it is written.
45987*/
45988static void walIndexWriteHdr(Wal *pWal){
45989  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
45990  const int nCksum = offsetof(WalIndexHdr, aCksum);
45991
45992  assert( pWal->writeLock );
45993  pWal->hdr.isInit = 1;
45994  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
45995  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
45996  memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
45997  walShmBarrier(pWal);
45998  memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
45999}
46000
46001/*
46002** This function encodes a single frame header and writes it to a buffer
46003** supplied by the caller. A frame-header is made up of a series of
46004** 4-byte big-endian integers, as follows:
46005**
46006**     0: Page number.
46007**     4: For commit records, the size of the database image in pages
46008**        after the commit. For all other records, zero.
46009**     8: Salt-1 (copied from the wal-header)
46010**    12: Salt-2 (copied from the wal-header)
46011**    16: Checksum-1.
46012**    20: Checksum-2.
46013*/
46014static void walEncodeFrame(
46015  Wal *pWal,                      /* The write-ahead log */
46016  u32 iPage,                      /* Database page number for frame */
46017  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
46018  u8 *aData,                      /* Pointer to page data */
46019  u8 *aFrame                      /* OUT: Write encoded frame here */
46020){
46021  int nativeCksum;                /* True for native byte-order checksums */
46022  u32 *aCksum = pWal->hdr.aFrameCksum;
46023  assert( WAL_FRAME_HDRSIZE==24 );
46024  sqlite3Put4byte(&aFrame[0], iPage);
46025  sqlite3Put4byte(&aFrame[4], nTruncate);
46026  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
46027
46028  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46029  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46030  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46031
46032  sqlite3Put4byte(&aFrame[16], aCksum[0]);
46033  sqlite3Put4byte(&aFrame[20], aCksum[1]);
46034}
46035
46036/*
46037** Check to see if the frame with header in aFrame[] and content
46038** in aData[] is valid.  If it is a valid frame, fill *piPage and
46039** *pnTruncate and return true.  Return if the frame is not valid.
46040*/
46041static int walDecodeFrame(
46042  Wal *pWal,                      /* The write-ahead log */
46043  u32 *piPage,                    /* OUT: Database page number for frame */
46044  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
46045  u8 *aData,                      /* Pointer to page data (for checksum) */
46046  u8 *aFrame                      /* Frame data */
46047){
46048  int nativeCksum;                /* True for native byte-order checksums */
46049  u32 *aCksum = pWal->hdr.aFrameCksum;
46050  u32 pgno;                       /* Page number of the frame */
46051  assert( WAL_FRAME_HDRSIZE==24 );
46052
46053  /* A frame is only valid if the salt values in the frame-header
46054  ** match the salt values in the wal-header.
46055  */
46056  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
46057    return 0;
46058  }
46059
46060  /* A frame is only valid if the page number is creater than zero.
46061  */
46062  pgno = sqlite3Get4byte(&aFrame[0]);
46063  if( pgno==0 ){
46064    return 0;
46065  }
46066
46067  /* A frame is only valid if a checksum of the WAL header,
46068  ** all prior frams, the first 16 bytes of this frame-header,
46069  ** and the frame-data matches the checksum in the last 8
46070  ** bytes of this frame-header.
46071  */
46072  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46073  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46074  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46075  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
46076   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
46077  ){
46078    /* Checksum failed. */
46079    return 0;
46080  }
46081
46082  /* If we reach this point, the frame is valid.  Return the page number
46083  ** and the new database size.
46084  */
46085  *piPage = pgno;
46086  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
46087  return 1;
46088}
46089
46090
46091#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46092/*
46093** Names of locks.  This routine is used to provide debugging output and is not
46094** a part of an ordinary build.
46095*/
46096static const char *walLockName(int lockIdx){
46097  if( lockIdx==WAL_WRITE_LOCK ){
46098    return "WRITE-LOCK";
46099  }else if( lockIdx==WAL_CKPT_LOCK ){
46100    return "CKPT-LOCK";
46101  }else if( lockIdx==WAL_RECOVER_LOCK ){
46102    return "RECOVER-LOCK";
46103  }else{
46104    static char zName[15];
46105    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
46106                     lockIdx-WAL_READ_LOCK(0));
46107    return zName;
46108  }
46109}
46110#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
46111
46112
46113/*
46114** Set or release locks on the WAL.  Locks are either shared or exclusive.
46115** A lock cannot be moved directly between shared and exclusive - it must go
46116** through the unlocked state first.
46117**
46118** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
46119*/
46120static int walLockShared(Wal *pWal, int lockIdx){
46121  int rc;
46122  if( pWal->exclusiveMode ) return SQLITE_OK;
46123  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46124                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
46125  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
46126            walLockName(lockIdx), rc ? "failed" : "ok"));
46127  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46128  return rc;
46129}
46130static void walUnlockShared(Wal *pWal, int lockIdx){
46131  if( pWal->exclusiveMode ) return;
46132  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46133                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
46134  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
46135}
46136static int walLockExclusive(Wal *pWal, int lockIdx, int n){
46137  int rc;
46138  if( pWal->exclusiveMode ) return SQLITE_OK;
46139  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46140                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
46141  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
46142            walLockName(lockIdx), n, rc ? "failed" : "ok"));
46143  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46144  return rc;
46145}
46146static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
46147  if( pWal->exclusiveMode ) return;
46148  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46149                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
46150  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
46151             walLockName(lockIdx), n));
46152}
46153
46154/*
46155** Compute a hash on a page number.  The resulting hash value must land
46156** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
46157** the hash to the next value in the event of a collision.
46158*/
46159static int walHash(u32 iPage){
46160  assert( iPage>0 );
46161  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
46162  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
46163}
46164static int walNextHash(int iPriorHash){
46165  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
46166}
46167
46168/*
46169** Return pointers to the hash table and page number array stored on
46170** page iHash of the wal-index. The wal-index is broken into 32KB pages
46171** numbered starting from 0.
46172**
46173** Set output variable *paHash to point to the start of the hash table
46174** in the wal-index file. Set *piZero to one less than the frame
46175** number of the first frame indexed by this hash table. If a
46176** slot in the hash table is set to N, it refers to frame number
46177** (*piZero+N) in the log.
46178**
46179** Finally, set *paPgno so that *paPgno[1] is the page number of the
46180** first frame indexed by the hash table, frame (*piZero+1).
46181*/
46182static int walHashGet(
46183  Wal *pWal,                      /* WAL handle */
46184  int iHash,                      /* Find the iHash'th table */
46185  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
46186  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
46187  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
46188){
46189  int rc;                         /* Return code */
46190  volatile u32 *aPgno;
46191
46192  rc = walIndexPage(pWal, iHash, &aPgno);
46193  assert( rc==SQLITE_OK || iHash>0 );
46194
46195  if( rc==SQLITE_OK ){
46196    u32 iZero;
46197    volatile ht_slot *aHash;
46198
46199    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
46200    if( iHash==0 ){
46201      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
46202      iZero = 0;
46203    }else{
46204      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
46205    }
46206
46207    *paPgno = &aPgno[-1];
46208    *paHash = aHash;
46209    *piZero = iZero;
46210  }
46211  return rc;
46212}
46213
46214/*
46215** Return the number of the wal-index page that contains the hash-table
46216** and page-number array that contain entries corresponding to WAL frame
46217** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
46218** are numbered starting from 0.
46219*/
46220static int walFramePage(u32 iFrame){
46221  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
46222  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
46223       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
46224       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
46225       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
46226       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
46227  );
46228  return iHash;
46229}
46230
46231/*
46232** Return the page number associated with frame iFrame in this WAL.
46233*/
46234static u32 walFramePgno(Wal *pWal, u32 iFrame){
46235  int iHash = walFramePage(iFrame);
46236  if( iHash==0 ){
46237    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
46238  }
46239  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
46240}
46241
46242/*
46243** Remove entries from the hash table that point to WAL slots greater
46244** than pWal->hdr.mxFrame.
46245**
46246** This function is called whenever pWal->hdr.mxFrame is decreased due
46247** to a rollback or savepoint.
46248**
46249** At most only the hash table containing pWal->hdr.mxFrame needs to be
46250** updated.  Any later hash tables will be automatically cleared when
46251** pWal->hdr.mxFrame advances to the point where those hash tables are
46252** actually needed.
46253*/
46254static void walCleanupHash(Wal *pWal){
46255  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
46256  volatile u32 *aPgno = 0;        /* Page number array for hash table */
46257  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
46258  int iLimit = 0;                 /* Zero values greater than this */
46259  int nByte;                      /* Number of bytes to zero in aPgno[] */
46260  int i;                          /* Used to iterate through aHash[] */
46261
46262  assert( pWal->writeLock );
46263  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
46264  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
46265  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
46266
46267  if( pWal->hdr.mxFrame==0 ) return;
46268
46269  /* Obtain pointers to the hash-table and page-number array containing
46270  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
46271  ** that the page said hash-table and array reside on is already mapped.
46272  */
46273  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
46274  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
46275  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
46276
46277  /* Zero all hash-table entries that correspond to frame numbers greater
46278  ** than pWal->hdr.mxFrame.
46279  */
46280  iLimit = pWal->hdr.mxFrame - iZero;
46281  assert( iLimit>0 );
46282  for(i=0; i<HASHTABLE_NSLOT; i++){
46283    if( aHash[i]>iLimit ){
46284      aHash[i] = 0;
46285    }
46286  }
46287
46288  /* Zero the entries in the aPgno array that correspond to frames with
46289  ** frame numbers greater than pWal->hdr.mxFrame.
46290  */
46291  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
46292  memset((void *)&aPgno[iLimit+1], 0, nByte);
46293
46294#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46295  /* Verify that the every entry in the mapping region is still reachable
46296  ** via the hash table even after the cleanup.
46297  */
46298  if( iLimit ){
46299    int i;           /* Loop counter */
46300    int iKey;        /* Hash key */
46301    for(i=1; i<=iLimit; i++){
46302      for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
46303        if( aHash[iKey]==i ) break;
46304      }
46305      assert( aHash[iKey]==i );
46306    }
46307  }
46308#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
46309}
46310
46311
46312/*
46313** Set an entry in the wal-index that will map database page number
46314** pPage into WAL frame iFrame.
46315*/
46316static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
46317  int rc;                         /* Return code */
46318  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
46319  volatile u32 *aPgno = 0;        /* Page number array */
46320  volatile ht_slot *aHash = 0;    /* Hash table */
46321
46322  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
46323
46324  /* Assuming the wal-index file was successfully mapped, populate the
46325  ** page number array and hash table entry.
46326  */
46327  if( rc==SQLITE_OK ){
46328    int iKey;                     /* Hash table key */
46329    int idx;                      /* Value to write to hash-table slot */
46330    int nCollide;                 /* Number of hash collisions */
46331
46332    idx = iFrame - iZero;
46333    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
46334
46335    /* If this is the first entry to be added to this hash-table, zero the
46336    ** entire hash table and aPgno[] array before proceding.
46337    */
46338    if( idx==1 ){
46339      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
46340      memset((void*)&aPgno[1], 0, nByte);
46341    }
46342
46343    /* If the entry in aPgno[] is already set, then the previous writer
46344    ** must have exited unexpectedly in the middle of a transaction (after
46345    ** writing one or more dirty pages to the WAL to free up memory).
46346    ** Remove the remnants of that writers uncommitted transaction from
46347    ** the hash-table before writing any new entries.
46348    */
46349    if( aPgno[idx] ){
46350      walCleanupHash(pWal);
46351      assert( !aPgno[idx] );
46352    }
46353
46354    /* Write the aPgno[] array entry and the hash-table slot. */
46355    nCollide = idx;
46356    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
46357      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
46358    }
46359    aPgno[idx] = iPage;
46360    aHash[iKey] = (ht_slot)idx;
46361
46362#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46363    /* Verify that the number of entries in the hash table exactly equals
46364    ** the number of entries in the mapping region.
46365    */
46366    {
46367      int i;           /* Loop counter */
46368      int nEntry = 0;  /* Number of entries in the hash table */
46369      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
46370      assert( nEntry==idx );
46371    }
46372
46373    /* Verify that the every entry in the mapping region is reachable
46374    ** via the hash table.  This turns out to be a really, really expensive
46375    ** thing to check, so only do this occasionally - not on every
46376    ** iteration.
46377    */
46378    if( (idx&0x3ff)==0 ){
46379      int i;           /* Loop counter */
46380      for(i=1; i<=idx; i++){
46381        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
46382          if( aHash[iKey]==i ) break;
46383        }
46384        assert( aHash[iKey]==i );
46385      }
46386    }
46387#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
46388  }
46389
46390
46391  return rc;
46392}
46393
46394
46395/*
46396** Recover the wal-index by reading the write-ahead log file.
46397**
46398** This routine first tries to establish an exclusive lock on the
46399** wal-index to prevent other threads/processes from doing anything
46400** with the WAL or wal-index while recovery is running.  The
46401** WAL_RECOVER_LOCK is also held so that other threads will know
46402** that this thread is running recovery.  If unable to establish
46403** the necessary locks, this routine returns SQLITE_BUSY.
46404*/
46405static int walIndexRecover(Wal *pWal){
46406  int rc;                         /* Return Code */
46407  i64 nSize;                      /* Size of log file */
46408  u32 aFrameCksum[2] = {0, 0};
46409  int iLock;                      /* Lock offset to lock for checkpoint */
46410  int nLock;                      /* Number of locks to hold */
46411
46412  /* Obtain an exclusive lock on all byte in the locking range not already
46413  ** locked by the caller. The caller is guaranteed to have locked the
46414  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
46415  ** If successful, the same bytes that are locked here are unlocked before
46416  ** this function returns.
46417  */
46418  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
46419  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
46420  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
46421  assert( pWal->writeLock );
46422  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
46423  nLock = SQLITE_SHM_NLOCK - iLock;
46424  rc = walLockExclusive(pWal, iLock, nLock);
46425  if( rc ){
46426    return rc;
46427  }
46428  WALTRACE(("WAL%p: recovery begin...\n", pWal));
46429
46430  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
46431
46432  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
46433  if( rc!=SQLITE_OK ){
46434    goto recovery_error;
46435  }
46436
46437  if( nSize>WAL_HDRSIZE ){
46438    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
46439    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
46440    int szFrame;                  /* Number of bytes in buffer aFrame[] */
46441    u8 *aData;                    /* Pointer to data part of aFrame buffer */
46442    int iFrame;                   /* Index of last frame read */
46443    i64 iOffset;                  /* Next offset to read from log file */
46444    int szPage;                   /* Page size according to the log */
46445    u32 magic;                    /* Magic value read from WAL header */
46446    u32 version;                  /* Magic value read from WAL header */
46447    int isValid;                  /* True if this frame is valid */
46448
46449    /* Read in the WAL header. */
46450    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
46451    if( rc!=SQLITE_OK ){
46452      goto recovery_error;
46453    }
46454
46455    /* If the database page size is not a power of two, or is greater than
46456    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
46457    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
46458    ** WAL file.
46459    */
46460    magic = sqlite3Get4byte(&aBuf[0]);
46461    szPage = sqlite3Get4byte(&aBuf[8]);
46462    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
46463     || szPage&(szPage-1)
46464     || szPage>SQLITE_MAX_PAGE_SIZE
46465     || szPage<512
46466    ){
46467      goto finished;
46468    }
46469    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
46470    pWal->szPage = szPage;
46471    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
46472    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
46473
46474    /* Verify that the WAL header checksum is correct */
46475    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
46476        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
46477    );
46478    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
46479     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
46480    ){
46481      goto finished;
46482    }
46483
46484    /* Verify that the version number on the WAL format is one that
46485    ** are able to understand */
46486    version = sqlite3Get4byte(&aBuf[4]);
46487    if( version!=WAL_MAX_VERSION ){
46488      rc = SQLITE_CANTOPEN_BKPT;
46489      goto finished;
46490    }
46491
46492    /* Malloc a buffer to read frames into. */
46493    szFrame = szPage + WAL_FRAME_HDRSIZE;
46494    aFrame = (u8 *)sqlite3_malloc(szFrame);
46495    if( !aFrame ){
46496      rc = SQLITE_NOMEM;
46497      goto recovery_error;
46498    }
46499    aData = &aFrame[WAL_FRAME_HDRSIZE];
46500
46501    /* Read all frames from the log file. */
46502    iFrame = 0;
46503    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
46504      u32 pgno;                   /* Database page number for frame */
46505      u32 nTruncate;              /* dbsize field from frame header */
46506
46507      /* Read and decode the next log frame. */
46508      iFrame++;
46509      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
46510      if( rc!=SQLITE_OK ) break;
46511      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
46512      if( !isValid ) break;
46513      rc = walIndexAppend(pWal, iFrame, pgno);
46514      if( rc!=SQLITE_OK ) break;
46515
46516      /* If nTruncate is non-zero, this is a commit record. */
46517      if( nTruncate ){
46518        pWal->hdr.mxFrame = iFrame;
46519        pWal->hdr.nPage = nTruncate;
46520        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
46521        testcase( szPage<=32768 );
46522        testcase( szPage>=65536 );
46523        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
46524        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
46525      }
46526    }
46527
46528    sqlite3_free(aFrame);
46529  }
46530
46531finished:
46532  if( rc==SQLITE_OK ){
46533    volatile WalCkptInfo *pInfo;
46534    int i;
46535    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
46536    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
46537    walIndexWriteHdr(pWal);
46538
46539    /* Reset the checkpoint-header. This is safe because this thread is
46540    ** currently holding locks that exclude all other readers, writers and
46541    ** checkpointers.
46542    */
46543    pInfo = walCkptInfo(pWal);
46544    pInfo->nBackfill = 0;
46545    pInfo->aReadMark[0] = 0;
46546    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46547
46548    /* If more than one frame was recovered from the log file, report an
46549    ** event via sqlite3_log(). This is to help with identifying performance
46550    ** problems caused by applications routinely shutting down without
46551    ** checkpointing the log file.
46552    */
46553    if( pWal->hdr.nPage ){
46554      sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
46555          pWal->hdr.nPage, pWal->zWalName
46556      );
46557    }
46558  }
46559
46560recovery_error:
46561  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
46562  walUnlockExclusive(pWal, iLock, nLock);
46563  return rc;
46564}
46565
46566/*
46567** Close an open wal-index.
46568*/
46569static void walIndexClose(Wal *pWal, int isDelete){
46570  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
46571    int i;
46572    for(i=0; i<pWal->nWiData; i++){
46573      sqlite3_free((void *)pWal->apWiData[i]);
46574      pWal->apWiData[i] = 0;
46575    }
46576  }else{
46577    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
46578  }
46579}
46580
46581/*
46582** Open a connection to the WAL file zWalName. The database file must
46583** already be opened on connection pDbFd. The buffer that zWalName points
46584** to must remain valid for the lifetime of the returned Wal* handle.
46585**
46586** A SHARED lock should be held on the database file when this function
46587** is called. The purpose of this SHARED lock is to prevent any other
46588** client from unlinking the WAL or wal-index file. If another process
46589** were to do this just after this client opened one of these files, the
46590** system would be badly broken.
46591**
46592** If the log file is successfully opened, SQLITE_OK is returned and
46593** *ppWal is set to point to a new WAL handle. If an error occurs,
46594** an SQLite error code is returned and *ppWal is left unmodified.
46595*/
46596SQLITE_PRIVATE int sqlite3WalOpen(
46597  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
46598  sqlite3_file *pDbFd,            /* The open database file */
46599  const char *zWalName,           /* Name of the WAL file */
46600  int bNoShm,                     /* True to run in heap-memory mode */
46601  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
46602  Wal **ppWal                     /* OUT: Allocated Wal handle */
46603){
46604  int rc;                         /* Return Code */
46605  Wal *pRet;                      /* Object to allocate and return */
46606  int flags;                      /* Flags passed to OsOpen() */
46607
46608  assert( zWalName && zWalName[0] );
46609  assert( pDbFd );
46610
46611  /* In the amalgamation, the os_unix.c and os_win.c source files come before
46612  ** this source file.  Verify that the #defines of the locking byte offsets
46613  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
46614  */
46615#ifdef WIN_SHM_BASE
46616  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
46617#endif
46618#ifdef UNIX_SHM_BASE
46619  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
46620#endif
46621
46622
46623  /* Allocate an instance of struct Wal to return. */
46624  *ppWal = 0;
46625  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
46626  if( !pRet ){
46627    return SQLITE_NOMEM;
46628  }
46629
46630  pRet->pVfs = pVfs;
46631  pRet->pWalFd = (sqlite3_file *)&pRet[1];
46632  pRet->pDbFd = pDbFd;
46633  pRet->readLock = -1;
46634  pRet->mxWalSize = mxWalSize;
46635  pRet->zWalName = zWalName;
46636  pRet->syncHeader = 1;
46637  pRet->padToSectorBoundary = 1;
46638  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
46639
46640  /* Open file handle on the write-ahead log file. */
46641  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
46642  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
46643  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
46644    pRet->readOnly = WAL_RDONLY;
46645  }
46646
46647  if( rc!=SQLITE_OK ){
46648    walIndexClose(pRet, 0);
46649    sqlite3OsClose(pRet->pWalFd);
46650    sqlite3_free(pRet);
46651  }else{
46652    int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
46653    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
46654    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
46655      pRet->padToSectorBoundary = 0;
46656    }
46657    *ppWal = pRet;
46658    WALTRACE(("WAL%d: opened\n", pRet));
46659  }
46660  return rc;
46661}
46662
46663/*
46664** Change the size to which the WAL file is trucated on each reset.
46665*/
46666SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
46667  if( pWal ) pWal->mxWalSize = iLimit;
46668}
46669
46670/*
46671** Find the smallest page number out of all pages held in the WAL that
46672** has not been returned by any prior invocation of this method on the
46673** same WalIterator object.   Write into *piFrame the frame index where
46674** that page was last written into the WAL.  Write into *piPage the page
46675** number.
46676**
46677** Return 0 on success.  If there are no pages in the WAL with a page
46678** number larger than *piPage, then return 1.
46679*/
46680static int walIteratorNext(
46681  WalIterator *p,               /* Iterator */
46682  u32 *piPage,                  /* OUT: The page number of the next page */
46683  u32 *piFrame                  /* OUT: Wal frame index of next page */
46684){
46685  u32 iMin;                     /* Result pgno must be greater than iMin */
46686  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
46687  int i;                        /* For looping through segments */
46688
46689  iMin = p->iPrior;
46690  assert( iMin<0xffffffff );
46691  for(i=p->nSegment-1; i>=0; i--){
46692    struct WalSegment *pSegment = &p->aSegment[i];
46693    while( pSegment->iNext<pSegment->nEntry ){
46694      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
46695      if( iPg>iMin ){
46696        if( iPg<iRet ){
46697          iRet = iPg;
46698          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
46699        }
46700        break;
46701      }
46702      pSegment->iNext++;
46703    }
46704  }
46705
46706  *piPage = p->iPrior = iRet;
46707  return (iRet==0xFFFFFFFF);
46708}
46709
46710/*
46711** This function merges two sorted lists into a single sorted list.
46712**
46713** aLeft[] and aRight[] are arrays of indices.  The sort key is
46714** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
46715** is guaranteed for all J<K:
46716**
46717**        aContent[aLeft[J]] < aContent[aLeft[K]]
46718**        aContent[aRight[J]] < aContent[aRight[K]]
46719**
46720** This routine overwrites aRight[] with a new (probably longer) sequence
46721** of indices such that the aRight[] contains every index that appears in
46722** either aLeft[] or the old aRight[] and such that the second condition
46723** above is still met.
46724**
46725** The aContent[aLeft[X]] values will be unique for all X.  And the
46726** aContent[aRight[X]] values will be unique too.  But there might be
46727** one or more combinations of X and Y such that
46728**
46729**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
46730**
46731** When that happens, omit the aLeft[X] and use the aRight[Y] index.
46732*/
46733static void walMerge(
46734  const u32 *aContent,            /* Pages in wal - keys for the sort */
46735  ht_slot *aLeft,                 /* IN: Left hand input list */
46736  int nLeft,                      /* IN: Elements in array *paLeft */
46737  ht_slot **paRight,              /* IN/OUT: Right hand input list */
46738  int *pnRight,                   /* IN/OUT: Elements in *paRight */
46739  ht_slot *aTmp                   /* Temporary buffer */
46740){
46741  int iLeft = 0;                  /* Current index in aLeft */
46742  int iRight = 0;                 /* Current index in aRight */
46743  int iOut = 0;                   /* Current index in output buffer */
46744  int nRight = *pnRight;
46745  ht_slot *aRight = *paRight;
46746
46747  assert( nLeft>0 && nRight>0 );
46748  while( iRight<nRight || iLeft<nLeft ){
46749    ht_slot logpage;
46750    Pgno dbpage;
46751
46752    if( (iLeft<nLeft)
46753     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
46754    ){
46755      logpage = aLeft[iLeft++];
46756    }else{
46757      logpage = aRight[iRight++];
46758    }
46759    dbpage = aContent[logpage];
46760
46761    aTmp[iOut++] = logpage;
46762    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
46763
46764    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
46765    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
46766  }
46767
46768  *paRight = aLeft;
46769  *pnRight = iOut;
46770  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
46771}
46772
46773/*
46774** Sort the elements in list aList using aContent[] as the sort key.
46775** Remove elements with duplicate keys, preferring to keep the
46776** larger aList[] values.
46777**
46778** The aList[] entries are indices into aContent[].  The values in
46779** aList[] are to be sorted so that for all J<K:
46780**
46781**      aContent[aList[J]] < aContent[aList[K]]
46782**
46783** For any X and Y such that
46784**
46785**      aContent[aList[X]] == aContent[aList[Y]]
46786**
46787** Keep the larger of the two values aList[X] and aList[Y] and discard
46788** the smaller.
46789*/
46790static void walMergesort(
46791  const u32 *aContent,            /* Pages in wal */
46792  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
46793  ht_slot *aList,                 /* IN/OUT: List to sort */
46794  int *pnList                     /* IN/OUT: Number of elements in aList[] */
46795){
46796  struct Sublist {
46797    int nList;                    /* Number of elements in aList */
46798    ht_slot *aList;               /* Pointer to sub-list content */
46799  };
46800
46801  const int nList = *pnList;      /* Size of input list */
46802  int nMerge = 0;                 /* Number of elements in list aMerge */
46803  ht_slot *aMerge = 0;            /* List to be merged */
46804  int iList;                      /* Index into input list */
46805  int iSub = 0;                   /* Index into aSub array */
46806  struct Sublist aSub[13];        /* Array of sub-lists */
46807
46808  memset(aSub, 0, sizeof(aSub));
46809  assert( nList<=HASHTABLE_NPAGE && nList>0 );
46810  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
46811
46812  for(iList=0; iList<nList; iList++){
46813    nMerge = 1;
46814    aMerge = &aList[iList];
46815    for(iSub=0; iList & (1<<iSub); iSub++){
46816      struct Sublist *p = &aSub[iSub];
46817      assert( p->aList && p->nList<=(1<<iSub) );
46818      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
46819      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
46820    }
46821    aSub[iSub].aList = aMerge;
46822    aSub[iSub].nList = nMerge;
46823  }
46824
46825  for(iSub++; iSub<ArraySize(aSub); iSub++){
46826    if( nList & (1<<iSub) ){
46827      struct Sublist *p = &aSub[iSub];
46828      assert( p->nList<=(1<<iSub) );
46829      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
46830      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
46831    }
46832  }
46833  assert( aMerge==aList );
46834  *pnList = nMerge;
46835
46836#ifdef SQLITE_DEBUG
46837  {
46838    int i;
46839    for(i=1; i<*pnList; i++){
46840      assert( aContent[aList[i]] > aContent[aList[i-1]] );
46841    }
46842  }
46843#endif
46844}
46845
46846/*
46847** Free an iterator allocated by walIteratorInit().
46848*/
46849static void walIteratorFree(WalIterator *p){
46850  sqlite3ScratchFree(p);
46851}
46852
46853/*
46854** Construct a WalInterator object that can be used to loop over all
46855** pages in the WAL in ascending order. The caller must hold the checkpoint
46856** lock.
46857**
46858** On success, make *pp point to the newly allocated WalInterator object
46859** return SQLITE_OK. Otherwise, return an error code. If this routine
46860** returns an error, the value of *pp is undefined.
46861**
46862** The calling routine should invoke walIteratorFree() to destroy the
46863** WalIterator object when it has finished with it.
46864*/
46865static int walIteratorInit(Wal *pWal, WalIterator **pp){
46866  WalIterator *p;                 /* Return value */
46867  int nSegment;                   /* Number of segments to merge */
46868  u32 iLast;                      /* Last frame in log */
46869  int nByte;                      /* Number of bytes to allocate */
46870  int i;                          /* Iterator variable */
46871  ht_slot *aTmp;                  /* Temp space used by merge-sort */
46872  int rc = SQLITE_OK;             /* Return Code */
46873
46874  /* This routine only runs while holding the checkpoint lock. And
46875  ** it only runs if there is actually content in the log (mxFrame>0).
46876  */
46877  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
46878  iLast = pWal->hdr.mxFrame;
46879
46880  /* Allocate space for the WalIterator object. */
46881  nSegment = walFramePage(iLast) + 1;
46882  nByte = sizeof(WalIterator)
46883        + (nSegment-1)*sizeof(struct WalSegment)
46884        + iLast*sizeof(ht_slot);
46885  p = (WalIterator *)sqlite3ScratchMalloc(nByte);
46886  if( !p ){
46887    return SQLITE_NOMEM;
46888  }
46889  memset(p, 0, nByte);
46890  p->nSegment = nSegment;
46891
46892  /* Allocate temporary space used by the merge-sort routine. This block
46893  ** of memory will be freed before this function returns.
46894  */
46895  aTmp = (ht_slot *)sqlite3ScratchMalloc(
46896      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
46897  );
46898  if( !aTmp ){
46899    rc = SQLITE_NOMEM;
46900  }
46901
46902  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
46903    volatile ht_slot *aHash;
46904    u32 iZero;
46905    volatile u32 *aPgno;
46906
46907    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
46908    if( rc==SQLITE_OK ){
46909      int j;                      /* Counter variable */
46910      int nEntry;                 /* Number of entries in this segment */
46911      ht_slot *aIndex;            /* Sorted index for this segment */
46912
46913      aPgno++;
46914      if( (i+1)==nSegment ){
46915        nEntry = (int)(iLast - iZero);
46916      }else{
46917        nEntry = (int)((u32*)aHash - (u32*)aPgno);
46918      }
46919      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
46920      iZero++;
46921
46922      for(j=0; j<nEntry; j++){
46923        aIndex[j] = (ht_slot)j;
46924      }
46925      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
46926      p->aSegment[i].iZero = iZero;
46927      p->aSegment[i].nEntry = nEntry;
46928      p->aSegment[i].aIndex = aIndex;
46929      p->aSegment[i].aPgno = (u32 *)aPgno;
46930    }
46931  }
46932  sqlite3ScratchFree(aTmp);
46933
46934  if( rc!=SQLITE_OK ){
46935    walIteratorFree(p);
46936  }
46937  *pp = p;
46938  return rc;
46939}
46940
46941/*
46942** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
46943** n. If the attempt fails and parameter xBusy is not NULL, then it is a
46944** busy-handler function. Invoke it and retry the lock until either the
46945** lock is successfully obtained or the busy-handler returns 0.
46946*/
46947static int walBusyLock(
46948  Wal *pWal,                      /* WAL connection */
46949  int (*xBusy)(void*),            /* Function to call when busy */
46950  void *pBusyArg,                 /* Context argument for xBusyHandler */
46951  int lockIdx,                    /* Offset of first byte to lock */
46952  int n                           /* Number of bytes to lock */
46953){
46954  int rc;
46955  do {
46956    rc = walLockExclusive(pWal, lockIdx, n);
46957  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
46958  return rc;
46959}
46960
46961/*
46962** The cache of the wal-index header must be valid to call this function.
46963** Return the page-size in bytes used by the database.
46964*/
46965static int walPagesize(Wal *pWal){
46966  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
46967}
46968
46969/*
46970** Copy as much content as we can from the WAL back into the database file
46971** in response to an sqlite3_wal_checkpoint() request or the equivalent.
46972**
46973** The amount of information copies from WAL to database might be limited
46974** by active readers.  This routine will never overwrite a database page
46975** that a concurrent reader might be using.
46976**
46977** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
46978** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
46979** checkpoints are always run by a background thread or background
46980** process, foreground threads will never block on a lengthy fsync call.
46981**
46982** Fsync is called on the WAL before writing content out of the WAL and
46983** into the database.  This ensures that if the new content is persistent
46984** in the WAL and can be recovered following a power-loss or hard reset.
46985**
46986** Fsync is also called on the database file if (and only if) the entire
46987** WAL content is copied into the database file.  This second fsync makes
46988** it safe to delete the WAL since the new content will persist in the
46989** database file.
46990**
46991** This routine uses and updates the nBackfill field of the wal-index header.
46992** This is the only routine tha will increase the value of nBackfill.
46993** (A WAL reset or recovery will revert nBackfill to zero, but not increase
46994** its value.)
46995**
46996** The caller must be holding sufficient locks to ensure that no other
46997** checkpoint is running (in any other thread or process) at the same
46998** time.
46999*/
47000static int walCheckpoint(
47001  Wal *pWal,                      /* Wal connection */
47002  int eMode,                      /* One of PASSIVE, FULL or RESTART */
47003  int (*xBusyCall)(void*),        /* Function to call when busy */
47004  void *pBusyArg,                 /* Context argument for xBusyHandler */
47005  int sync_flags,                 /* Flags for OsSync() (or 0) */
47006  u8 *zBuf                        /* Temporary buffer to use */
47007){
47008  int rc;                         /* Return code */
47009  int szPage;                     /* Database page-size */
47010  WalIterator *pIter = 0;         /* Wal iterator context */
47011  u32 iDbpage = 0;                /* Next database page to write */
47012  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
47013  u32 mxSafeFrame;                /* Max frame that can be backfilled */
47014  u32 mxPage;                     /* Max database page to write */
47015  int i;                          /* Loop counter */
47016  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
47017  int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
47018
47019  szPage = walPagesize(pWal);
47020  testcase( szPage<=32768 );
47021  testcase( szPage>=65536 );
47022  pInfo = walCkptInfo(pWal);
47023  if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
47024
47025  /* Allocate the iterator */
47026  rc = walIteratorInit(pWal, &pIter);
47027  if( rc!=SQLITE_OK ){
47028    return rc;
47029  }
47030  assert( pIter );
47031
47032  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
47033
47034  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
47035  ** safe to write into the database.  Frames beyond mxSafeFrame might
47036  ** overwrite database pages that are in use by active readers and thus
47037  ** cannot be backfilled from the WAL.
47038  */
47039  mxSafeFrame = pWal->hdr.mxFrame;
47040  mxPage = pWal->hdr.nPage;
47041  for(i=1; i<WAL_NREADER; i++){
47042    u32 y = pInfo->aReadMark[i];
47043    if( mxSafeFrame>y ){
47044      assert( y<=pWal->hdr.mxFrame );
47045      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
47046      if( rc==SQLITE_OK ){
47047        pInfo->aReadMark[i] = READMARK_NOT_USED;
47048        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47049      }else if( rc==SQLITE_BUSY ){
47050        mxSafeFrame = y;
47051        xBusy = 0;
47052      }else{
47053        goto walcheckpoint_out;
47054      }
47055    }
47056  }
47057
47058  if( pInfo->nBackfill<mxSafeFrame
47059   && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
47060  ){
47061    i64 nSize;                    /* Current size of database file */
47062    u32 nBackfill = pInfo->nBackfill;
47063
47064    /* Sync the WAL to disk */
47065    if( sync_flags ){
47066      rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
47067    }
47068
47069    /* If the database file may grow as a result of this checkpoint, hint
47070    ** about the eventual size of the db file to the VFS layer.
47071    */
47072    if( rc==SQLITE_OK ){
47073      i64 nReq = ((i64)mxPage * szPage);
47074      rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
47075      if( rc==SQLITE_OK && nSize<nReq ){
47076        sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
47077      }
47078    }
47079
47080    /* Iterate through the contents of the WAL, copying data to the db file. */
47081    while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
47082      i64 iOffset;
47083      assert( walFramePgno(pWal, iFrame)==iDbpage );
47084      if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
47085      iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
47086      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
47087      rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
47088      if( rc!=SQLITE_OK ) break;
47089      iOffset = (iDbpage-1)*(i64)szPage;
47090      testcase( IS_BIG_INT(iOffset) );
47091      rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
47092      if( rc!=SQLITE_OK ) break;
47093    }
47094
47095    /* If work was actually accomplished... */
47096    if( rc==SQLITE_OK ){
47097      if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
47098        i64 szDb = pWal->hdr.nPage*(i64)szPage;
47099        testcase( IS_BIG_INT(szDb) );
47100        rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
47101        if( rc==SQLITE_OK && sync_flags ){
47102          rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
47103        }
47104      }
47105      if( rc==SQLITE_OK ){
47106        pInfo->nBackfill = mxSafeFrame;
47107      }
47108    }
47109
47110    /* Release the reader lock held while backfilling */
47111    walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
47112  }
47113
47114  if( rc==SQLITE_BUSY ){
47115    /* Reset the return code so as not to report a checkpoint failure
47116    ** just because there are active readers.  */
47117    rc = SQLITE_OK;
47118  }
47119
47120  /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
47121  ** file has been copied into the database file, then block until all
47122  ** readers have finished using the wal file. This ensures that the next
47123  ** process to write to the database restarts the wal file.
47124  */
47125  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
47126    assert( pWal->writeLock );
47127    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
47128      rc = SQLITE_BUSY;
47129    }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
47130      assert( mxSafeFrame==pWal->hdr.mxFrame );
47131      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
47132      if( rc==SQLITE_OK ){
47133        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
47134      }
47135    }
47136  }
47137
47138 walcheckpoint_out:
47139  walIteratorFree(pIter);
47140  return rc;
47141}
47142
47143/*
47144** If the WAL file is currently larger than nMax bytes in size, truncate
47145** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
47146*/
47147static void walLimitSize(Wal *pWal, i64 nMax){
47148  i64 sz;
47149  int rx;
47150  sqlite3BeginBenignMalloc();
47151  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
47152  if( rx==SQLITE_OK && (sz > nMax ) ){
47153    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
47154  }
47155  sqlite3EndBenignMalloc();
47156  if( rx ){
47157    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
47158  }
47159}
47160
47161/*
47162** Close a connection to a log file.
47163*/
47164SQLITE_PRIVATE int sqlite3WalClose(
47165  Wal *pWal,                      /* Wal to close */
47166  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
47167  int nBuf,
47168  u8 *zBuf                        /* Buffer of at least nBuf bytes */
47169){
47170  int rc = SQLITE_OK;
47171  if( pWal ){
47172    int isDelete = 0;             /* True to unlink wal and wal-index files */
47173
47174    /* If an EXCLUSIVE lock can be obtained on the database file (using the
47175    ** ordinary, rollback-mode locking methods, this guarantees that the
47176    ** connection associated with this log file is the only connection to
47177    ** the database. In this case checkpoint the database and unlink both
47178    ** the wal and wal-index files.
47179    **
47180    ** The EXCLUSIVE lock is not released before returning.
47181    */
47182    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
47183    if( rc==SQLITE_OK ){
47184      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
47185        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
47186      }
47187      rc = sqlite3WalCheckpoint(
47188          pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
47189      );
47190      if( rc==SQLITE_OK ){
47191        int bPersist = -1;
47192        sqlite3OsFileControlHint(
47193            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
47194        );
47195        if( bPersist!=1 ){
47196          /* Try to delete the WAL file if the checkpoint completed and
47197          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
47198          ** mode (!bPersist) */
47199          isDelete = 1;
47200        }else if( pWal->mxWalSize>=0 ){
47201          /* Try to truncate the WAL file to zero bytes if the checkpoint
47202          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
47203          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
47204          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
47205          ** to zero bytes as truncating to the journal_size_limit might
47206          ** leave a corrupt WAL file on disk. */
47207          walLimitSize(pWal, 0);
47208        }
47209      }
47210    }
47211
47212    walIndexClose(pWal, isDelete);
47213    sqlite3OsClose(pWal->pWalFd);
47214    if( isDelete ){
47215      sqlite3BeginBenignMalloc();
47216      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
47217      sqlite3EndBenignMalloc();
47218    }
47219    WALTRACE(("WAL%p: closed\n", pWal));
47220    sqlite3_free((void *)pWal->apWiData);
47221    sqlite3_free(pWal);
47222  }
47223  return rc;
47224}
47225
47226/*
47227** Try to read the wal-index header.  Return 0 on success and 1 if
47228** there is a problem.
47229**
47230** The wal-index is in shared memory.  Another thread or process might
47231** be writing the header at the same time this procedure is trying to
47232** read it, which might result in inconsistency.  A dirty read is detected
47233** by verifying that both copies of the header are the same and also by
47234** a checksum on the header.
47235**
47236** If and only if the read is consistent and the header is different from
47237** pWal->hdr, then pWal->hdr is updated to the content of the new header
47238** and *pChanged is set to 1.
47239**
47240** If the checksum cannot be verified return non-zero. If the header
47241** is read successfully and the checksum verified, return zero.
47242*/
47243static int walIndexTryHdr(Wal *pWal, int *pChanged){
47244  u32 aCksum[2];                  /* Checksum on the header content */
47245  WalIndexHdr h1, h2;             /* Two copies of the header content */
47246  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
47247
47248  /* The first page of the wal-index must be mapped at this point. */
47249  assert( pWal->nWiData>0 && pWal->apWiData[0] );
47250
47251  /* Read the header. This might happen concurrently with a write to the
47252  ** same area of shared memory on a different CPU in a SMP,
47253  ** meaning it is possible that an inconsistent snapshot is read
47254  ** from the file. If this happens, return non-zero.
47255  **
47256  ** There are two copies of the header at the beginning of the wal-index.
47257  ** When reading, read [0] first then [1].  Writes are in the reverse order.
47258  ** Memory barriers are used to prevent the compiler or the hardware from
47259  ** reordering the reads and writes.
47260  */
47261  aHdr = walIndexHdr(pWal);
47262  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
47263  walShmBarrier(pWal);
47264  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
47265
47266  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
47267    return 1;   /* Dirty read */
47268  }
47269  if( h1.isInit==0 ){
47270    return 1;   /* Malformed header - probably all zeros */
47271  }
47272  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
47273  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
47274    return 1;   /* Checksum does not match */
47275  }
47276
47277  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
47278    *pChanged = 1;
47279    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
47280    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
47281    testcase( pWal->szPage<=32768 );
47282    testcase( pWal->szPage>=65536 );
47283  }
47284
47285  /* The header was successfully read. Return zero. */
47286  return 0;
47287}
47288
47289/*
47290** Read the wal-index header from the wal-index and into pWal->hdr.
47291** If the wal-header appears to be corrupt, try to reconstruct the
47292** wal-index from the WAL before returning.
47293**
47294** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
47295** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
47296** to 0.
47297**
47298** If the wal-index header is successfully read, return SQLITE_OK.
47299** Otherwise an SQLite error code.
47300*/
47301static int walIndexReadHdr(Wal *pWal, int *pChanged){
47302  int rc;                         /* Return code */
47303  int badHdr;                     /* True if a header read failed */
47304  volatile u32 *page0;            /* Chunk of wal-index containing header */
47305
47306  /* Ensure that page 0 of the wal-index (the page that contains the
47307  ** wal-index header) is mapped. Return early if an error occurs here.
47308  */
47309  assert( pChanged );
47310  rc = walIndexPage(pWal, 0, &page0);
47311  if( rc!=SQLITE_OK ){
47312    return rc;
47313  };
47314  assert( page0 || pWal->writeLock==0 );
47315
47316  /* If the first page of the wal-index has been mapped, try to read the
47317  ** wal-index header immediately, without holding any lock. This usually
47318  ** works, but may fail if the wal-index header is corrupt or currently
47319  ** being modified by another thread or process.
47320  */
47321  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
47322
47323  /* If the first attempt failed, it might have been due to a race
47324  ** with a writer.  So get a WRITE lock and try again.
47325  */
47326  assert( badHdr==0 || pWal->writeLock==0 );
47327  if( badHdr ){
47328    if( pWal->readOnly & WAL_SHM_RDONLY ){
47329      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
47330        walUnlockShared(pWal, WAL_WRITE_LOCK);
47331        rc = SQLITE_READONLY_RECOVERY;
47332      }
47333    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
47334      pWal->writeLock = 1;
47335      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
47336        badHdr = walIndexTryHdr(pWal, pChanged);
47337        if( badHdr ){
47338          /* If the wal-index header is still malformed even while holding
47339          ** a WRITE lock, it can only mean that the header is corrupted and
47340          ** needs to be reconstructed.  So run recovery to do exactly that.
47341          */
47342          rc = walIndexRecover(pWal);
47343          *pChanged = 1;
47344        }
47345      }
47346      pWal->writeLock = 0;
47347      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47348    }
47349  }
47350
47351  /* If the header is read successfully, check the version number to make
47352  ** sure the wal-index was not constructed with some future format that
47353  ** this version of SQLite cannot understand.
47354  */
47355  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
47356    rc = SQLITE_CANTOPEN_BKPT;
47357  }
47358
47359  return rc;
47360}
47361
47362/*
47363** This is the value that walTryBeginRead returns when it needs to
47364** be retried.
47365*/
47366#define WAL_RETRY  (-1)
47367
47368/*
47369** Attempt to start a read transaction.  This might fail due to a race or
47370** other transient condition.  When that happens, it returns WAL_RETRY to
47371** indicate to the caller that it is safe to retry immediately.
47372**
47373** On success return SQLITE_OK.  On a permanent failure (such an
47374** I/O error or an SQLITE_BUSY because another process is running
47375** recovery) return a positive error code.
47376**
47377** The useWal parameter is true to force the use of the WAL and disable
47378** the case where the WAL is bypassed because it has been completely
47379** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
47380** to make a copy of the wal-index header into pWal->hdr.  If the
47381** wal-index header has changed, *pChanged is set to 1 (as an indication
47382** to the caller that the local paget cache is obsolete and needs to be
47383** flushed.)  When useWal==1, the wal-index header is assumed to already
47384** be loaded and the pChanged parameter is unused.
47385**
47386** The caller must set the cnt parameter to the number of prior calls to
47387** this routine during the current read attempt that returned WAL_RETRY.
47388** This routine will start taking more aggressive measures to clear the
47389** race conditions after multiple WAL_RETRY returns, and after an excessive
47390** number of errors will ultimately return SQLITE_PROTOCOL.  The
47391** SQLITE_PROTOCOL return indicates that some other process has gone rogue
47392** and is not honoring the locking protocol.  There is a vanishingly small
47393** chance that SQLITE_PROTOCOL could be returned because of a run of really
47394** bad luck when there is lots of contention for the wal-index, but that
47395** possibility is so small that it can be safely neglected, we believe.
47396**
47397** On success, this routine obtains a read lock on
47398** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
47399** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
47400** that means the Wal does not hold any read lock.  The reader must not
47401** access any database page that is modified by a WAL frame up to and
47402** including frame number aReadMark[pWal->readLock].  The reader will
47403** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
47404** Or if pWal->readLock==0, then the reader will ignore the WAL
47405** completely and get all content directly from the database file.
47406** If the useWal parameter is 1 then the WAL will never be ignored and
47407** this routine will always set pWal->readLock>0 on success.
47408** When the read transaction is completed, the caller must release the
47409** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
47410**
47411** This routine uses the nBackfill and aReadMark[] fields of the header
47412** to select a particular WAL_READ_LOCK() that strives to let the
47413** checkpoint process do as much work as possible.  This routine might
47414** update values of the aReadMark[] array in the header, but if it does
47415** so it takes care to hold an exclusive lock on the corresponding
47416** WAL_READ_LOCK() while changing values.
47417*/
47418static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
47419  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
47420  u32 mxReadMark;                 /* Largest aReadMark[] value */
47421  int mxI;                        /* Index of largest aReadMark[] value */
47422  int i;                          /* Loop counter */
47423  int rc = SQLITE_OK;             /* Return code  */
47424
47425  assert( pWal->readLock<0 );     /* Not currently locked */
47426
47427  /* Take steps to avoid spinning forever if there is a protocol error.
47428  **
47429  ** Circumstances that cause a RETRY should only last for the briefest
47430  ** instances of time.  No I/O or other system calls are done while the
47431  ** locks are held, so the locks should not be held for very long. But
47432  ** if we are unlucky, another process that is holding a lock might get
47433  ** paged out or take a page-fault that is time-consuming to resolve,
47434  ** during the few nanoseconds that it is holding the lock.  In that case,
47435  ** it might take longer than normal for the lock to free.
47436  **
47437  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
47438  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
47439  ** is more of a scheduler yield than an actual delay.  But on the 10th
47440  ** an subsequent retries, the delays start becoming longer and longer,
47441  ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
47442  ** The total delay time before giving up is less than 1 second.
47443  */
47444  if( cnt>5 ){
47445    int nDelay = 1;                      /* Pause time in microseconds */
47446    if( cnt>100 ){
47447      VVA_ONLY( pWal->lockError = 1; )
47448      return SQLITE_PROTOCOL;
47449    }
47450    if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
47451    sqlite3OsSleep(pWal->pVfs, nDelay);
47452  }
47453
47454  if( !useWal ){
47455    rc = walIndexReadHdr(pWal, pChanged);
47456    if( rc==SQLITE_BUSY ){
47457      /* If there is not a recovery running in another thread or process
47458      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
47459      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
47460      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
47461      ** would be technically correct.  But the race is benign since with
47462      ** WAL_RETRY this routine will be called again and will probably be
47463      ** right on the second iteration.
47464      */
47465      if( pWal->apWiData[0]==0 ){
47466        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
47467        ** We assume this is a transient condition, so return WAL_RETRY. The
47468        ** xShmMap() implementation used by the default unix and win32 VFS
47469        ** modules may return SQLITE_BUSY due to a race condition in the
47470        ** code that determines whether or not the shared-memory region
47471        ** must be zeroed before the requested page is returned.
47472        */
47473        rc = WAL_RETRY;
47474      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
47475        walUnlockShared(pWal, WAL_RECOVER_LOCK);
47476        rc = WAL_RETRY;
47477      }else if( rc==SQLITE_BUSY ){
47478        rc = SQLITE_BUSY_RECOVERY;
47479      }
47480    }
47481    if( rc!=SQLITE_OK ){
47482      return rc;
47483    }
47484  }
47485
47486  pInfo = walCkptInfo(pWal);
47487  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
47488    /* The WAL has been completely backfilled (or it is empty).
47489    ** and can be safely ignored.
47490    */
47491    rc = walLockShared(pWal, WAL_READ_LOCK(0));
47492    walShmBarrier(pWal);
47493    if( rc==SQLITE_OK ){
47494      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
47495        /* It is not safe to allow the reader to continue here if frames
47496        ** may have been appended to the log before READ_LOCK(0) was obtained.
47497        ** When holding READ_LOCK(0), the reader ignores the entire log file,
47498        ** which implies that the database file contains a trustworthy
47499        ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
47500        ** happening, this is usually correct.
47501        **
47502        ** However, if frames have been appended to the log (or if the log
47503        ** is wrapped and written for that matter) before the READ_LOCK(0)
47504        ** is obtained, that is not necessarily true. A checkpointer may
47505        ** have started to backfill the appended frames but crashed before
47506        ** it finished. Leaving a corrupt image in the database file.
47507        */
47508        walUnlockShared(pWal, WAL_READ_LOCK(0));
47509        return WAL_RETRY;
47510      }
47511      pWal->readLock = 0;
47512      return SQLITE_OK;
47513    }else if( rc!=SQLITE_BUSY ){
47514      return rc;
47515    }
47516  }
47517
47518  /* If we get this far, it means that the reader will want to use
47519  ** the WAL to get at content from recent commits.  The job now is
47520  ** to select one of the aReadMark[] entries that is closest to
47521  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
47522  */
47523  mxReadMark = 0;
47524  mxI = 0;
47525  for(i=1; i<WAL_NREADER; i++){
47526    u32 thisMark = pInfo->aReadMark[i];
47527    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
47528      assert( thisMark!=READMARK_NOT_USED );
47529      mxReadMark = thisMark;
47530      mxI = i;
47531    }
47532  }
47533  /* There was once an "if" here. The extra "{" is to preserve indentation. */
47534  {
47535    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
47536     && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
47537    ){
47538      for(i=1; i<WAL_NREADER; i++){
47539        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
47540        if( rc==SQLITE_OK ){
47541          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
47542          mxI = i;
47543          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47544          break;
47545        }else if( rc!=SQLITE_BUSY ){
47546          return rc;
47547        }
47548      }
47549    }
47550    if( mxI==0 ){
47551      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
47552      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
47553    }
47554
47555    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
47556    if( rc ){
47557      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
47558    }
47559    /* Now that the read-lock has been obtained, check that neither the
47560    ** value in the aReadMark[] array or the contents of the wal-index
47561    ** header have changed.
47562    **
47563    ** It is necessary to check that the wal-index header did not change
47564    ** between the time it was read and when the shared-lock was obtained
47565    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
47566    ** that the log file may have been wrapped by a writer, or that frames
47567    ** that occur later in the log than pWal->hdr.mxFrame may have been
47568    ** copied into the database by a checkpointer. If either of these things
47569    ** happened, then reading the database with the current value of
47570    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
47571    ** instead.
47572    **
47573    ** This does not guarantee that the copy of the wal-index header is up to
47574    ** date before proceeding. That would not be possible without somehow
47575    ** blocking writers. It only guarantees that a dangerous checkpoint or
47576    ** log-wrap (either of which would require an exclusive lock on
47577    ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
47578    */
47579    walShmBarrier(pWal);
47580    if( pInfo->aReadMark[mxI]!=mxReadMark
47581     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
47582    ){
47583      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
47584      return WAL_RETRY;
47585    }else{
47586      assert( mxReadMark<=pWal->hdr.mxFrame );
47587      pWal->readLock = (i16)mxI;
47588    }
47589  }
47590  return rc;
47591}
47592
47593/*
47594** Begin a read transaction on the database.
47595**
47596** This routine used to be called sqlite3OpenSnapshot() and with good reason:
47597** it takes a snapshot of the state of the WAL and wal-index for the current
47598** instant in time.  The current thread will continue to use this snapshot.
47599** Other threads might append new content to the WAL and wal-index but
47600** that extra content is ignored by the current thread.
47601**
47602** If the database contents have changes since the previous read
47603** transaction, then *pChanged is set to 1 before returning.  The
47604** Pager layer will use this to know that is cache is stale and
47605** needs to be flushed.
47606*/
47607SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
47608  int rc;                         /* Return code */
47609  int cnt = 0;                    /* Number of TryBeginRead attempts */
47610
47611  do{
47612    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
47613  }while( rc==WAL_RETRY );
47614  testcase( (rc&0xff)==SQLITE_BUSY );
47615  testcase( (rc&0xff)==SQLITE_IOERR );
47616  testcase( rc==SQLITE_PROTOCOL );
47617  testcase( rc==SQLITE_OK );
47618  return rc;
47619}
47620
47621/*
47622** Finish with a read transaction.  All this does is release the
47623** read-lock.
47624*/
47625SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
47626  sqlite3WalEndWriteTransaction(pWal);
47627  if( pWal->readLock>=0 ){
47628    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
47629    pWal->readLock = -1;
47630  }
47631}
47632
47633/*
47634** Read a page from the WAL, if it is present in the WAL and if the
47635** current read transaction is configured to use the WAL.
47636**
47637** The *pInWal is set to 1 if the requested page is in the WAL and
47638** has been loaded.  Or *pInWal is set to 0 if the page was not in
47639** the WAL and needs to be read out of the database.
47640*/
47641SQLITE_PRIVATE int sqlite3WalRead(
47642  Wal *pWal,                      /* WAL handle */
47643  Pgno pgno,                      /* Database page number to read data for */
47644  int *pInWal,                    /* OUT: True if data is read from WAL */
47645  int nOut,                       /* Size of buffer pOut in bytes */
47646  u8 *pOut                        /* Buffer to write page data to */
47647){
47648  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
47649  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
47650  int iHash;                      /* Used to loop through N hash tables */
47651
47652  /* This routine is only be called from within a read transaction. */
47653  assert( pWal->readLock>=0 || pWal->lockError );
47654
47655  /* If the "last page" field of the wal-index header snapshot is 0, then
47656  ** no data will be read from the wal under any circumstances. Return early
47657  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
47658  ** then the WAL is ignored by the reader so return early, as if the
47659  ** WAL were empty.
47660  */
47661  if( iLast==0 || pWal->readLock==0 ){
47662    *pInWal = 0;
47663    return SQLITE_OK;
47664  }
47665
47666  /* Search the hash table or tables for an entry matching page number
47667  ** pgno. Each iteration of the following for() loop searches one
47668  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
47669  **
47670  ** This code might run concurrently to the code in walIndexAppend()
47671  ** that adds entries to the wal-index (and possibly to this hash
47672  ** table). This means the value just read from the hash
47673  ** slot (aHash[iKey]) may have been added before or after the
47674  ** current read transaction was opened. Values added after the
47675  ** read transaction was opened may have been written incorrectly -
47676  ** i.e. these slots may contain garbage data. However, we assume
47677  ** that any slots written before the current read transaction was
47678  ** opened remain unmodified.
47679  **
47680  ** For the reasons above, the if(...) condition featured in the inner
47681  ** loop of the following block is more stringent that would be required
47682  ** if we had exclusive access to the hash-table:
47683  **
47684  **   (aPgno[iFrame]==pgno):
47685  **     This condition filters out normal hash-table collisions.
47686  **
47687  **   (iFrame<=iLast):
47688  **     This condition filters out entries that were added to the hash
47689  **     table after the current read-transaction had started.
47690  */
47691  for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
47692    volatile ht_slot *aHash;      /* Pointer to hash table */
47693    volatile u32 *aPgno;          /* Pointer to array of page numbers */
47694    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
47695    int iKey;                     /* Hash slot index */
47696    int nCollide;                 /* Number of hash collisions remaining */
47697    int rc;                       /* Error code */
47698
47699    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
47700    if( rc!=SQLITE_OK ){
47701      return rc;
47702    }
47703    nCollide = HASHTABLE_NSLOT;
47704    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
47705      u32 iFrame = aHash[iKey] + iZero;
47706      if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
47707        /* assert( iFrame>iRead ); -- not true if there is corruption */
47708        iRead = iFrame;
47709      }
47710      if( (nCollide--)==0 ){
47711        return SQLITE_CORRUPT_BKPT;
47712      }
47713    }
47714  }
47715
47716#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
47717  /* If expensive assert() statements are available, do a linear search
47718  ** of the wal-index file content. Make sure the results agree with the
47719  ** result obtained using the hash indexes above.  */
47720  {
47721    u32 iRead2 = 0;
47722    u32 iTest;
47723    for(iTest=iLast; iTest>0; iTest--){
47724      if( walFramePgno(pWal, iTest)==pgno ){
47725        iRead2 = iTest;
47726        break;
47727      }
47728    }
47729    assert( iRead==iRead2 );
47730  }
47731#endif
47732
47733  /* If iRead is non-zero, then it is the log frame number that contains the
47734  ** required page. Read and return data from the log file.
47735  */
47736  if( iRead ){
47737    int sz;
47738    i64 iOffset;
47739    sz = pWal->hdr.szPage;
47740    sz = (sz&0xfe00) + ((sz&0x0001)<<16);
47741    testcase( sz<=32768 );
47742    testcase( sz>=65536 );
47743    iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
47744    *pInWal = 1;
47745    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
47746    return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
47747  }
47748
47749  *pInWal = 0;
47750  return SQLITE_OK;
47751}
47752
47753
47754/*
47755** Return the size of the database in pages (or zero, if unknown).
47756*/
47757SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
47758  if( pWal && ALWAYS(pWal->readLock>=0) ){
47759    return pWal->hdr.nPage;
47760  }
47761  return 0;
47762}
47763
47764
47765/*
47766** This function starts a write transaction on the WAL.
47767**
47768** A read transaction must have already been started by a prior call
47769** to sqlite3WalBeginReadTransaction().
47770**
47771** If another thread or process has written into the database since
47772** the read transaction was started, then it is not possible for this
47773** thread to write as doing so would cause a fork.  So this routine
47774** returns SQLITE_BUSY in that case and no write transaction is started.
47775**
47776** There can only be a single writer active at a time.
47777*/
47778SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
47779  int rc;
47780
47781  /* Cannot start a write transaction without first holding a read
47782  ** transaction. */
47783  assert( pWal->readLock>=0 );
47784
47785  if( pWal->readOnly ){
47786    return SQLITE_READONLY;
47787  }
47788
47789  /* Only one writer allowed at a time.  Get the write lock.  Return
47790  ** SQLITE_BUSY if unable.
47791  */
47792  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
47793  if( rc ){
47794    return rc;
47795  }
47796  pWal->writeLock = 1;
47797
47798  /* If another connection has written to the database file since the
47799  ** time the read transaction on this connection was started, then
47800  ** the write is disallowed.
47801  */
47802  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
47803    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47804    pWal->writeLock = 0;
47805    rc = SQLITE_BUSY;
47806  }
47807
47808  return rc;
47809}
47810
47811/*
47812** End a write transaction.  The commit has already been done.  This
47813** routine merely releases the lock.
47814*/
47815SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
47816  if( pWal->writeLock ){
47817    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47818    pWal->writeLock = 0;
47819    pWal->truncateOnCommit = 0;
47820  }
47821  return SQLITE_OK;
47822}
47823
47824/*
47825** If any data has been written (but not committed) to the log file, this
47826** function moves the write-pointer back to the start of the transaction.
47827**
47828** Additionally, the callback function is invoked for each frame written
47829** to the WAL since the start of the transaction. If the callback returns
47830** other than SQLITE_OK, it is not invoked again and the error code is
47831** returned to the caller.
47832**
47833** Otherwise, if the callback function does not return an error, this
47834** function returns SQLITE_OK.
47835*/
47836SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
47837  int rc = SQLITE_OK;
47838  if( ALWAYS(pWal->writeLock) ){
47839    Pgno iMax = pWal->hdr.mxFrame;
47840    Pgno iFrame;
47841
47842    /* Restore the clients cache of the wal-index header to the state it
47843    ** was in before the client began writing to the database.
47844    */
47845    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
47846
47847    for(iFrame=pWal->hdr.mxFrame+1;
47848        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
47849        iFrame++
47850    ){
47851      /* This call cannot fail. Unless the page for which the page number
47852      ** is passed as the second argument is (a) in the cache and
47853      ** (b) has an outstanding reference, then xUndo is either a no-op
47854      ** (if (a) is false) or simply expels the page from the cache (if (b)
47855      ** is false).
47856      **
47857      ** If the upper layer is doing a rollback, it is guaranteed that there
47858      ** are no outstanding references to any page other than page 1. And
47859      ** page 1 is never written to the log until the transaction is
47860      ** committed. As a result, the call to xUndo may not fail.
47861      */
47862      assert( walFramePgno(pWal, iFrame)!=1 );
47863      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
47864    }
47865    walCleanupHash(pWal);
47866  }
47867  assert( rc==SQLITE_OK );
47868  return rc;
47869}
47870
47871/*
47872** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
47873** values. This function populates the array with values required to
47874** "rollback" the write position of the WAL handle back to the current
47875** point in the event of a savepoint rollback (via WalSavepointUndo()).
47876*/
47877SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
47878  assert( pWal->writeLock );
47879  aWalData[0] = pWal->hdr.mxFrame;
47880  aWalData[1] = pWal->hdr.aFrameCksum[0];
47881  aWalData[2] = pWal->hdr.aFrameCksum[1];
47882  aWalData[3] = pWal->nCkpt;
47883}
47884
47885/*
47886** Move the write position of the WAL back to the point identified by
47887** the values in the aWalData[] array. aWalData must point to an array
47888** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
47889** by a call to WalSavepoint().
47890*/
47891SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
47892  int rc = SQLITE_OK;
47893
47894  assert( pWal->writeLock );
47895  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
47896
47897  if( aWalData[3]!=pWal->nCkpt ){
47898    /* This savepoint was opened immediately after the write-transaction
47899    ** was started. Right after that, the writer decided to wrap around
47900    ** to the start of the log. Update the savepoint values to match.
47901    */
47902    aWalData[0] = 0;
47903    aWalData[3] = pWal->nCkpt;
47904  }
47905
47906  if( aWalData[0]<pWal->hdr.mxFrame ){
47907    pWal->hdr.mxFrame = aWalData[0];
47908    pWal->hdr.aFrameCksum[0] = aWalData[1];
47909    pWal->hdr.aFrameCksum[1] = aWalData[2];
47910    walCleanupHash(pWal);
47911  }
47912
47913  return rc;
47914}
47915
47916
47917/*
47918** This function is called just before writing a set of frames to the log
47919** file (see sqlite3WalFrames()). It checks to see if, instead of appending
47920** to the current log file, it is possible to overwrite the start of the
47921** existing log file with the new frames (i.e. "reset" the log). If so,
47922** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
47923** unchanged.
47924**
47925** SQLITE_OK is returned if no error is encountered (regardless of whether
47926** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
47927** if an error occurs.
47928*/
47929static int walRestartLog(Wal *pWal){
47930  int rc = SQLITE_OK;
47931  int cnt;
47932
47933  if( pWal->readLock==0 ){
47934    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
47935    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
47936    if( pInfo->nBackfill>0 ){
47937      u32 salt1;
47938      sqlite3_randomness(4, &salt1);
47939      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
47940      if( rc==SQLITE_OK ){
47941        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
47942        ** readers are currently using the WAL), then the transactions
47943        ** frames will overwrite the start of the existing log. Update the
47944        ** wal-index header to reflect this.
47945        **
47946        ** In theory it would be Ok to update the cache of the header only
47947        ** at this point. But updating the actual wal-index header is also
47948        ** safe and means there is no special case for sqlite3WalUndo()
47949        ** to handle if this transaction is rolled back.
47950        */
47951        int i;                    /* Loop counter */
47952        u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
47953
47954        pWal->nCkpt++;
47955        pWal->hdr.mxFrame = 0;
47956        sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
47957        aSalt[1] = salt1;
47958        walIndexWriteHdr(pWal);
47959        pInfo->nBackfill = 0;
47960        for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
47961        assert( pInfo->aReadMark[0]==0 );
47962        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
47963      }else if( rc!=SQLITE_BUSY ){
47964        return rc;
47965      }
47966    }
47967    walUnlockShared(pWal, WAL_READ_LOCK(0));
47968    pWal->readLock = -1;
47969    cnt = 0;
47970    do{
47971      int notUsed;
47972      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
47973    }while( rc==WAL_RETRY );
47974    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
47975    testcase( (rc&0xff)==SQLITE_IOERR );
47976    testcase( rc==SQLITE_PROTOCOL );
47977    testcase( rc==SQLITE_OK );
47978  }
47979  return rc;
47980}
47981
47982/*
47983** Information about the current state of the WAL file and where
47984** the next fsync should occur - passed from sqlite3WalFrames() into
47985** walWriteToLog().
47986*/
47987typedef struct WalWriter {
47988  Wal *pWal;                   /* The complete WAL information */
47989  sqlite3_file *pFd;           /* The WAL file to which we write */
47990  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
47991  int syncFlags;               /* Flags for the fsync */
47992  int szPage;                  /* Size of one page */
47993} WalWriter;
47994
47995/*
47996** Write iAmt bytes of content into the WAL file beginning at iOffset.
47997** Do a sync when crossing the p->iSyncPoint boundary.
47998**
47999** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
48000** first write the part before iSyncPoint, then sync, then write the
48001** rest.
48002*/
48003static int walWriteToLog(
48004  WalWriter *p,              /* WAL to write to */
48005  void *pContent,            /* Content to be written */
48006  int iAmt,                  /* Number of bytes to write */
48007  sqlite3_int64 iOffset      /* Start writing at this offset */
48008){
48009  int rc;
48010  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
48011    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
48012    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
48013    if( rc ) return rc;
48014    iOffset += iFirstAmt;
48015    iAmt -= iFirstAmt;
48016    pContent = (void*)(iFirstAmt + (char*)pContent);
48017    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
48018    rc = sqlite3OsSync(p->pFd, p->syncFlags);
48019    if( iAmt==0 || rc ) return rc;
48020  }
48021  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
48022  return rc;
48023}
48024
48025/*
48026** Write out a single frame of the WAL
48027*/
48028static int walWriteOneFrame(
48029  WalWriter *p,               /* Where to write the frame */
48030  PgHdr *pPage,               /* The page of the frame to be written */
48031  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
48032  sqlite3_int64 iOffset       /* Byte offset at which to write */
48033){
48034  int rc;                         /* Result code from subfunctions */
48035  void *pData;                    /* Data actually written */
48036  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
48037#if defined(SQLITE_HAS_CODEC)
48038  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
48039#else
48040  pData = pPage->pData;
48041#endif
48042  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
48043  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
48044  if( rc ) return rc;
48045  /* Write the page data */
48046  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
48047  return rc;
48048}
48049
48050/*
48051** Write a set of frames to the log. The caller must hold the write-lock
48052** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
48053*/
48054SQLITE_PRIVATE int sqlite3WalFrames(
48055  Wal *pWal,                      /* Wal handle to write to */
48056  int szPage,                     /* Database page-size in bytes */
48057  PgHdr *pList,                   /* List of dirty pages to write */
48058  Pgno nTruncate,                 /* Database size after this commit */
48059  int isCommit,                   /* True if this is a commit */
48060  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
48061){
48062  int rc;                         /* Used to catch return codes */
48063  u32 iFrame;                     /* Next frame address */
48064  PgHdr *p;                       /* Iterator to run through pList with. */
48065  PgHdr *pLast = 0;               /* Last frame in list */
48066  int nExtra = 0;                 /* Number of extra copies of last page */
48067  int szFrame;                    /* The size of a single frame */
48068  i64 iOffset;                    /* Next byte to write in WAL file */
48069  WalWriter w;                    /* The writer */
48070
48071  assert( pList );
48072  assert( pWal->writeLock );
48073
48074  /* If this frame set completes a transaction, then nTruncate>0.  If
48075  ** nTruncate==0 then this frame set does not complete the transaction. */
48076  assert( (isCommit!=0)==(nTruncate!=0) );
48077
48078#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
48079  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
48080    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
48081              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
48082  }
48083#endif
48084
48085  /* See if it is possible to write these frames into the start of the
48086  ** log file, instead of appending to it at pWal->hdr.mxFrame.
48087  */
48088  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
48089    return rc;
48090  }
48091
48092  /* If this is the first frame written into the log, write the WAL
48093  ** header to the start of the WAL file. See comments at the top of
48094  ** this source file for a description of the WAL header format.
48095  */
48096  iFrame = pWal->hdr.mxFrame;
48097  if( iFrame==0 ){
48098    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
48099    u32 aCksum[2];                /* Checksum for wal-header */
48100
48101    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
48102    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
48103    sqlite3Put4byte(&aWalHdr[8], szPage);
48104    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
48105    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
48106    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
48107    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
48108    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
48109    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
48110
48111    pWal->szPage = szPage;
48112    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
48113    pWal->hdr.aFrameCksum[0] = aCksum[0];
48114    pWal->hdr.aFrameCksum[1] = aCksum[1];
48115    pWal->truncateOnCommit = 1;
48116
48117    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
48118    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
48119    if( rc!=SQLITE_OK ){
48120      return rc;
48121    }
48122
48123    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
48124    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
48125    ** an out-of-order write following a WAL restart could result in
48126    ** database corruption.  See the ticket:
48127    **
48128    **     http://localhost:591/sqlite/info/ff5be73dee
48129    */
48130    if( pWal->syncHeader && sync_flags ){
48131      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
48132      if( rc ) return rc;
48133    }
48134  }
48135  assert( (int)pWal->szPage==szPage );
48136
48137  /* Setup information needed to write frames into the WAL */
48138  w.pWal = pWal;
48139  w.pFd = pWal->pWalFd;
48140  w.iSyncPoint = 0;
48141  w.syncFlags = sync_flags;
48142  w.szPage = szPage;
48143  iOffset = walFrameOffset(iFrame+1, szPage);
48144  szFrame = szPage + WAL_FRAME_HDRSIZE;
48145
48146  /* Write all frames into the log file exactly once */
48147  for(p=pList; p; p=p->pDirty){
48148    int nDbSize;   /* 0 normally.  Positive == commit flag */
48149    iFrame++;
48150    assert( iOffset==walFrameOffset(iFrame, szPage) );
48151    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
48152    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
48153    if( rc ) return rc;
48154    pLast = p;
48155    iOffset += szFrame;
48156  }
48157
48158  /* If this is the end of a transaction, then we might need to pad
48159  ** the transaction and/or sync the WAL file.
48160  **
48161  ** Padding and syncing only occur if this set of frames complete a
48162  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
48163  ** or synchonous==OFF, then no padding or syncing are needed.
48164  **
48165  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
48166  ** needed and only the sync is done.  If padding is needed, then the
48167  ** final frame is repeated (with its commit mark) until the next sector
48168  ** boundary is crossed.  Only the part of the WAL prior to the last
48169  ** sector boundary is synced; the part of the last frame that extends
48170  ** past the sector boundary is written after the sync.
48171  */
48172  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
48173    if( pWal->padToSectorBoundary ){
48174      int sectorSize = sqlite3OsSectorSize(pWal->pWalFd);
48175      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
48176      while( iOffset<w.iSyncPoint ){
48177        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
48178        if( rc ) return rc;
48179        iOffset += szFrame;
48180        nExtra++;
48181      }
48182    }else{
48183      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
48184    }
48185  }
48186
48187  /* If this frame set completes the first transaction in the WAL and
48188  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
48189  ** journal size limit, if possible.
48190  */
48191  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
48192    i64 sz = pWal->mxWalSize;
48193    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
48194      sz = walFrameOffset(iFrame+nExtra+1, szPage);
48195    }
48196    walLimitSize(pWal, sz);
48197    pWal->truncateOnCommit = 0;
48198  }
48199
48200  /* Append data to the wal-index. It is not necessary to lock the
48201  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
48202  ** guarantees that there are no other writers, and no data that may
48203  ** be in use by existing readers is being overwritten.
48204  */
48205  iFrame = pWal->hdr.mxFrame;
48206  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
48207    iFrame++;
48208    rc = walIndexAppend(pWal, iFrame, p->pgno);
48209  }
48210  while( rc==SQLITE_OK && nExtra>0 ){
48211    iFrame++;
48212    nExtra--;
48213    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
48214  }
48215
48216  if( rc==SQLITE_OK ){
48217    /* Update the private copy of the header. */
48218    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
48219    testcase( szPage<=32768 );
48220    testcase( szPage>=65536 );
48221    pWal->hdr.mxFrame = iFrame;
48222    if( isCommit ){
48223      pWal->hdr.iChange++;
48224      pWal->hdr.nPage = nTruncate;
48225    }
48226    /* If this is a commit, update the wal-index header too. */
48227    if( isCommit ){
48228      walIndexWriteHdr(pWal);
48229      pWal->iCallback = iFrame;
48230    }
48231  }
48232
48233  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
48234  return rc;
48235}
48236
48237/*
48238** This routine is called to implement sqlite3_wal_checkpoint() and
48239** related interfaces.
48240**
48241** Obtain a CHECKPOINT lock and then backfill as much information as
48242** we can from WAL into the database.
48243**
48244** If parameter xBusy is not NULL, it is a pointer to a busy-handler
48245** callback. In this case this function runs a blocking checkpoint.
48246*/
48247SQLITE_PRIVATE int sqlite3WalCheckpoint(
48248  Wal *pWal,                      /* Wal connection */
48249  int eMode,                      /* PASSIVE, FULL or RESTART */
48250  int (*xBusy)(void*),            /* Function to call when busy */
48251  void *pBusyArg,                 /* Context argument for xBusyHandler */
48252  int sync_flags,                 /* Flags to sync db file with (or 0) */
48253  int nBuf,                       /* Size of temporary buffer */
48254  u8 *zBuf,                       /* Temporary buffer to use */
48255  int *pnLog,                     /* OUT: Number of frames in WAL */
48256  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
48257){
48258  int rc;                         /* Return code */
48259  int isChanged = 0;              /* True if a new wal-index header is loaded */
48260  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
48261
48262  assert( pWal->ckptLock==0 );
48263  assert( pWal->writeLock==0 );
48264
48265  if( pWal->readOnly ) return SQLITE_READONLY;
48266  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
48267  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
48268  if( rc ){
48269    /* Usually this is SQLITE_BUSY meaning that another thread or process
48270    ** is already running a checkpoint, or maybe a recovery.  But it might
48271    ** also be SQLITE_IOERR. */
48272    return rc;
48273  }
48274  pWal->ckptLock = 1;
48275
48276  /* If this is a blocking-checkpoint, then obtain the write-lock as well
48277  ** to prevent any writers from running while the checkpoint is underway.
48278  ** This has to be done before the call to walIndexReadHdr() below.
48279  **
48280  ** If the writer lock cannot be obtained, then a passive checkpoint is
48281  ** run instead. Since the checkpointer is not holding the writer lock,
48282  ** there is no point in blocking waiting for any readers. Assuming no
48283  ** other error occurs, this function will return SQLITE_BUSY to the caller.
48284  */
48285  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
48286    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
48287    if( rc==SQLITE_OK ){
48288      pWal->writeLock = 1;
48289    }else if( rc==SQLITE_BUSY ){
48290      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
48291      rc = SQLITE_OK;
48292    }
48293  }
48294
48295  /* Read the wal-index header. */
48296  if( rc==SQLITE_OK ){
48297    rc = walIndexReadHdr(pWal, &isChanged);
48298  }
48299
48300  /* Copy data from the log to the database file. */
48301  if( rc==SQLITE_OK ){
48302    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
48303      rc = SQLITE_CORRUPT_BKPT;
48304    }else{
48305      rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
48306    }
48307
48308    /* If no error occurred, set the output variables. */
48309    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
48310      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
48311      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
48312    }
48313  }
48314
48315  if( isChanged ){
48316    /* If a new wal-index header was loaded before the checkpoint was
48317    ** performed, then the pager-cache associated with pWal is now
48318    ** out of date. So zero the cached wal-index header to ensure that
48319    ** next time the pager opens a snapshot on this database it knows that
48320    ** the cache needs to be reset.
48321    */
48322    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
48323  }
48324
48325  /* Release the locks. */
48326  sqlite3WalEndWriteTransaction(pWal);
48327  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
48328  pWal->ckptLock = 0;
48329  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
48330  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
48331}
48332
48333/* Return the value to pass to a sqlite3_wal_hook callback, the
48334** number of frames in the WAL at the point of the last commit since
48335** sqlite3WalCallback() was called.  If no commits have occurred since
48336** the last call, then return 0.
48337*/
48338SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
48339  u32 ret = 0;
48340  if( pWal ){
48341    ret = pWal->iCallback;
48342    pWal->iCallback = 0;
48343  }
48344  return (int)ret;
48345}
48346
48347/*
48348** This function is called to change the WAL subsystem into or out
48349** of locking_mode=EXCLUSIVE.
48350**
48351** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
48352** into locking_mode=NORMAL.  This means that we must acquire a lock
48353** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
48354** or if the acquisition of the lock fails, then return 0.  If the
48355** transition out of exclusive-mode is successful, return 1.  This
48356** operation must occur while the pager is still holding the exclusive
48357** lock on the main database file.
48358**
48359** If op is one, then change from locking_mode=NORMAL into
48360** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
48361** be released.  Return 1 if the transition is made and 0 if the
48362** WAL is already in exclusive-locking mode - meaning that this
48363** routine is a no-op.  The pager must already hold the exclusive lock
48364** on the main database file before invoking this operation.
48365**
48366** If op is negative, then do a dry-run of the op==1 case but do
48367** not actually change anything. The pager uses this to see if it
48368** should acquire the database exclusive lock prior to invoking
48369** the op==1 case.
48370*/
48371SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
48372  int rc;
48373  assert( pWal->writeLock==0 );
48374  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
48375
48376  /* pWal->readLock is usually set, but might be -1 if there was a
48377  ** prior error while attempting to acquire are read-lock. This cannot
48378  ** happen if the connection is actually in exclusive mode (as no xShmLock
48379  ** locks are taken in this case). Nor should the pager attempt to
48380  ** upgrade to exclusive-mode following such an error.
48381  */
48382  assert( pWal->readLock>=0 || pWal->lockError );
48383  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
48384
48385  if( op==0 ){
48386    if( pWal->exclusiveMode ){
48387      pWal->exclusiveMode = 0;
48388      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
48389        pWal->exclusiveMode = 1;
48390      }
48391      rc = pWal->exclusiveMode==0;
48392    }else{
48393      /* Already in locking_mode=NORMAL */
48394      rc = 0;
48395    }
48396  }else if( op>0 ){
48397    assert( pWal->exclusiveMode==0 );
48398    assert( pWal->readLock>=0 );
48399    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
48400    pWal->exclusiveMode = 1;
48401    rc = 1;
48402  }else{
48403    rc = pWal->exclusiveMode==0;
48404  }
48405  return rc;
48406}
48407
48408/*
48409** Return true if the argument is non-NULL and the WAL module is using
48410** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
48411** WAL module is using shared-memory, return false.
48412*/
48413SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
48414  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
48415}
48416
48417#ifdef SQLITE_ENABLE_ZIPVFS
48418/*
48419** If the argument is not NULL, it points to a Wal object that holds a
48420** read-lock. This function returns the database page-size if it is known,
48421** or zero if it is not (or if pWal is NULL).
48422*/
48423SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
48424  assert( pWal==0 || pWal->readLock>=0 );
48425  return (pWal ? pWal->szPage : 0);
48426}
48427#endif
48428
48429#endif /* #ifndef SQLITE_OMIT_WAL */
48430
48431/************** End of wal.c *************************************************/
48432/************** Begin file btmutex.c *****************************************/
48433/*
48434** 2007 August 27
48435**
48436** The author disclaims copyright to this source code.  In place of
48437** a legal notice, here is a blessing:
48438**
48439**    May you do good and not evil.
48440**    May you find forgiveness for yourself and forgive others.
48441**    May you share freely, never taking more than you give.
48442**
48443*************************************************************************
48444**
48445** This file contains code used to implement mutexes on Btree objects.
48446** This code really belongs in btree.c.  But btree.c is getting too
48447** big and we want to break it down some.  This packaged seemed like
48448** a good breakout.
48449*/
48450/************** Include btreeInt.h in the middle of btmutex.c ****************/
48451/************** Begin file btreeInt.h ****************************************/
48452/*
48453** 2004 April 6
48454**
48455** The author disclaims copyright to this source code.  In place of
48456** a legal notice, here is a blessing:
48457**
48458**    May you do good and not evil.
48459**    May you find forgiveness for yourself and forgive others.
48460**    May you share freely, never taking more than you give.
48461**
48462*************************************************************************
48463** This file implements a external (disk-based) database using BTrees.
48464** For a detailed discussion of BTrees, refer to
48465**
48466**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
48467**     "Sorting And Searching", pages 473-480. Addison-Wesley
48468**     Publishing Company, Reading, Massachusetts.
48469**
48470** The basic idea is that each page of the file contains N database
48471** entries and N+1 pointers to subpages.
48472**
48473**   ----------------------------------------------------------------
48474**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
48475**   ----------------------------------------------------------------
48476**
48477** All of the keys on the page that Ptr(0) points to have values less
48478** than Key(0).  All of the keys on page Ptr(1) and its subpages have
48479** values greater than Key(0) and less than Key(1).  All of the keys
48480** on Ptr(N) and its subpages have values greater than Key(N-1).  And
48481** so forth.
48482**
48483** Finding a particular key requires reading O(log(M)) pages from the
48484** disk where M is the number of entries in the tree.
48485**
48486** In this implementation, a single file can hold one or more separate
48487** BTrees.  Each BTree is identified by the index of its root page.  The
48488** key and data for any entry are combined to form the "payload".  A
48489** fixed amount of payload can be carried directly on the database
48490** page.  If the payload is larger than the preset amount then surplus
48491** bytes are stored on overflow pages.  The payload for an entry
48492** and the preceding pointer are combined to form a "Cell".  Each
48493** page has a small header which contains the Ptr(N) pointer and other
48494** information such as the size of key and data.
48495**
48496** FORMAT DETAILS
48497**
48498** The file is divided into pages.  The first page is called page 1,
48499** the second is page 2, and so forth.  A page number of zero indicates
48500** "no such page".  The page size can be any power of 2 between 512 and 65536.
48501** Each page can be either a btree page, a freelist page, an overflow
48502** page, or a pointer-map page.
48503**
48504** The first page is always a btree page.  The first 100 bytes of the first
48505** page contain a special header (the "file header") that describes the file.
48506** The format of the file header is as follows:
48507**
48508**   OFFSET   SIZE    DESCRIPTION
48509**      0      16     Header string: "SQLite format 3\000"
48510**     16       2     Page size in bytes.
48511**     18       1     File format write version
48512**     19       1     File format read version
48513**     20       1     Bytes of unused space at the end of each page
48514**     21       1     Max embedded payload fraction
48515**     22       1     Min embedded payload fraction
48516**     23       1     Min leaf payload fraction
48517**     24       4     File change counter
48518**     28       4     Reserved for future use
48519**     32       4     First freelist page
48520**     36       4     Number of freelist pages in the file
48521**     40      60     15 4-byte meta values passed to higher layers
48522**
48523**     40       4     Schema cookie
48524**     44       4     File format of schema layer
48525**     48       4     Size of page cache
48526**     52       4     Largest root-page (auto/incr_vacuum)
48527**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
48528**     60       4     User version
48529**     64       4     Incremental vacuum mode
48530**     68       4     unused
48531**     72       4     unused
48532**     76       4     unused
48533**
48534** All of the integer values are big-endian (most significant byte first).
48535**
48536** The file change counter is incremented when the database is changed
48537** This counter allows other processes to know when the file has changed
48538** and thus when they need to flush their cache.
48539**
48540** The max embedded payload fraction is the amount of the total usable
48541** space in a page that can be consumed by a single cell for standard
48542** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
48543** is to limit the maximum cell size so that at least 4 cells will fit
48544** on one page.  Thus the default max embedded payload fraction is 64.
48545**
48546** If the payload for a cell is larger than the max payload, then extra
48547** payload is spilled to overflow pages.  Once an overflow page is allocated,
48548** as many bytes as possible are moved into the overflow pages without letting
48549** the cell size drop below the min embedded payload fraction.
48550**
48551** The min leaf payload fraction is like the min embedded payload fraction
48552** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
48553** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
48554** not specified in the header.
48555**
48556** Each btree pages is divided into three sections:  The header, the
48557** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
48558** file header that occurs before the page header.
48559**
48560**      |----------------|
48561**      | file header    |   100 bytes.  Page 1 only.
48562**      |----------------|
48563**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
48564**      |----------------|
48565**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
48566**      | array          |   |  Grows downward
48567**      |                |   v
48568**      |----------------|
48569**      | unallocated    |
48570**      | space          |
48571**      |----------------|   ^  Grows upwards
48572**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
48573**      | area           |   |  and free space fragments.
48574**      |----------------|
48575**
48576** The page headers looks like this:
48577**
48578**   OFFSET   SIZE     DESCRIPTION
48579**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
48580**      1       2      byte offset to the first freeblock
48581**      3       2      number of cells on this page
48582**      5       2      first byte of the cell content area
48583**      7       1      number of fragmented free bytes
48584**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
48585**
48586** The flags define the format of this btree page.  The leaf flag means that
48587** this page has no children.  The zerodata flag means that this page carries
48588** only keys and no data.  The intkey flag means that the key is a integer
48589** which is stored in the key size entry of the cell header rather than in
48590** the payload area.
48591**
48592** The cell pointer array begins on the first byte after the page header.
48593** The cell pointer array contains zero or more 2-byte numbers which are
48594** offsets from the beginning of the page to the cell content in the cell
48595** content area.  The cell pointers occur in sorted order.  The system strives
48596** to keep free space after the last cell pointer so that new cells can
48597** be easily added without having to defragment the page.
48598**
48599** Cell content is stored at the very end of the page and grows toward the
48600** beginning of the page.
48601**
48602** Unused space within the cell content area is collected into a linked list of
48603** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
48604** to the first freeblock is given in the header.  Freeblocks occur in
48605** increasing order.  Because a freeblock must be at least 4 bytes in size,
48606** any group of 3 or fewer unused bytes in the cell content area cannot
48607** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
48608** a fragment.  The total number of bytes in all fragments is recorded.
48609** in the page header at offset 7.
48610**
48611**    SIZE    DESCRIPTION
48612**      2     Byte offset of the next freeblock
48613**      2     Bytes in this freeblock
48614**
48615** Cells are of variable length.  Cells are stored in the cell content area at
48616** the end of the page.  Pointers to the cells are in the cell pointer array
48617** that immediately follows the page header.  Cells is not necessarily
48618** contiguous or in order, but cell pointers are contiguous and in order.
48619**
48620** Cell content makes use of variable length integers.  A variable
48621** length integer is 1 to 9 bytes where the lower 7 bits of each
48622** byte are used.  The integer consists of all bytes that have bit 8 set and
48623** the first byte with bit 8 clear.  The most significant byte of the integer
48624** appears first.  A variable-length integer may not be more than 9 bytes long.
48625** As a special case, all 8 bytes of the 9th byte are used as data.  This
48626** allows a 64-bit integer to be encoded in 9 bytes.
48627**
48628**    0x00                      becomes  0x00000000
48629**    0x7f                      becomes  0x0000007f
48630**    0x81 0x00                 becomes  0x00000080
48631**    0x82 0x00                 becomes  0x00000100
48632**    0x80 0x7f                 becomes  0x0000007f
48633**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
48634**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
48635**
48636** Variable length integers are used for rowids and to hold the number of
48637** bytes of key and data in a btree cell.
48638**
48639** The content of a cell looks like this:
48640**
48641**    SIZE    DESCRIPTION
48642**      4     Page number of the left child. Omitted if leaf flag is set.
48643**     var    Number of bytes of data. Omitted if the zerodata flag is set.
48644**     var    Number of bytes of key. Or the key itself if intkey flag is set.
48645**      *     Payload
48646**      4     First page of the overflow chain.  Omitted if no overflow
48647**
48648** Overflow pages form a linked list.  Each page except the last is completely
48649** filled with data (pagesize - 4 bytes).  The last page can have as little
48650** as 1 byte of data.
48651**
48652**    SIZE    DESCRIPTION
48653**      4     Page number of next overflow page
48654**      *     Data
48655**
48656** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
48657** file header points to the first in a linked list of trunk page.  Each trunk
48658** page points to multiple leaf pages.  The content of a leaf page is
48659** unspecified.  A trunk page looks like this:
48660**
48661**    SIZE    DESCRIPTION
48662**      4     Page number of next trunk page
48663**      4     Number of leaf pointers on this page
48664**      *     zero or more pages numbers of leaves
48665*/
48666
48667
48668/* The following value is the maximum cell size assuming a maximum page
48669** size give above.
48670*/
48671#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
48672
48673/* The maximum number of cells on a single page of the database.  This
48674** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
48675** plus 2 bytes for the index to the cell in the page header).  Such
48676** small cells will be rare, but they are possible.
48677*/
48678#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
48679
48680/* Forward declarations */
48681typedef struct MemPage MemPage;
48682typedef struct BtLock BtLock;
48683
48684/*
48685** This is a magic string that appears at the beginning of every
48686** SQLite database in order to identify the file as a real database.
48687**
48688** You can change this value at compile-time by specifying a
48689** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
48690** header must be exactly 16 bytes including the zero-terminator so
48691** the string itself should be 15 characters long.  If you change
48692** the header, then your custom library will not be able to read
48693** databases generated by the standard tools and the standard tools
48694** will not be able to read databases created by your custom library.
48695*/
48696#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
48697#  define SQLITE_FILE_HEADER "SQLite format 3"
48698#endif
48699
48700/*
48701** Page type flags.  An ORed combination of these flags appear as the
48702** first byte of on-disk image of every BTree page.
48703*/
48704#define PTF_INTKEY    0x01
48705#define PTF_ZERODATA  0x02
48706#define PTF_LEAFDATA  0x04
48707#define PTF_LEAF      0x08
48708
48709/*
48710** As each page of the file is loaded into memory, an instance of the following
48711** structure is appended and initialized to zero.  This structure stores
48712** information about the page that is decoded from the raw file page.
48713**
48714** The pParent field points back to the parent page.  This allows us to
48715** walk up the BTree from any leaf to the root.  Care must be taken to
48716** unref() the parent page pointer when this page is no longer referenced.
48717** The pageDestructor() routine handles that chore.
48718**
48719** Access to all fields of this structure is controlled by the mutex
48720** stored in MemPage.pBt->mutex.
48721*/
48722struct MemPage {
48723  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
48724  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
48725  u8 intKey;           /* True if intkey flag is set */
48726  u8 leaf;             /* True if leaf flag is set */
48727  u8 hasData;          /* True if this page stores data */
48728  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
48729  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
48730  u8 max1bytePayload;  /* min(maxLocal,127) */
48731  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
48732  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
48733  u16 cellOffset;      /* Index in aData of first cell pointer */
48734  u16 nFree;           /* Number of free bytes on the page */
48735  u16 nCell;           /* Number of cells on this page, local and ovfl */
48736  u16 maskPage;        /* Mask for page offset */
48737  u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
48738                       ** non-overflow cell */
48739  u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
48740  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
48741  u8 *aData;           /* Pointer to disk image of the page data */
48742  u8 *aDataEnd;        /* One byte past the end of usable data */
48743  u8 *aCellIdx;        /* The cell index area */
48744  DbPage *pDbPage;     /* Pager page handle */
48745  Pgno pgno;           /* Page number for this page */
48746};
48747
48748/*
48749** The in-memory image of a disk page has the auxiliary information appended
48750** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
48751** that extra information.
48752*/
48753#define EXTRA_SIZE sizeof(MemPage)
48754
48755/*
48756** A linked list of the following structures is stored at BtShared.pLock.
48757** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
48758** is opened on the table with root page BtShared.iTable. Locks are removed
48759** from this list when a transaction is committed or rolled back, or when
48760** a btree handle is closed.
48761*/
48762struct BtLock {
48763  Btree *pBtree;        /* Btree handle holding this lock */
48764  Pgno iTable;          /* Root page of table */
48765  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
48766  BtLock *pNext;        /* Next in BtShared.pLock list */
48767};
48768
48769/* Candidate values for BtLock.eLock */
48770#define READ_LOCK     1
48771#define WRITE_LOCK    2
48772
48773/* A Btree handle
48774**
48775** A database connection contains a pointer to an instance of
48776** this object for every database file that it has open.  This structure
48777** is opaque to the database connection.  The database connection cannot
48778** see the internals of this structure and only deals with pointers to
48779** this structure.
48780**
48781** For some database files, the same underlying database cache might be
48782** shared between multiple connections.  In that case, each connection
48783** has it own instance of this object.  But each instance of this object
48784** points to the same BtShared object.  The database cache and the
48785** schema associated with the database file are all contained within
48786** the BtShared object.
48787**
48788** All fields in this structure are accessed under sqlite3.mutex.
48789** The pBt pointer itself may not be changed while there exists cursors
48790** in the referenced BtShared that point back to this Btree since those
48791** cursors have to go through this Btree to find their BtShared and
48792** they often do so without holding sqlite3.mutex.
48793*/
48794struct Btree {
48795  sqlite3 *db;       /* The database connection holding this btree */
48796  BtShared *pBt;     /* Sharable content of this btree */
48797  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
48798  u8 sharable;       /* True if we can share pBt with another db */
48799  u8 locked;         /* True if db currently has pBt locked */
48800  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
48801  int nBackup;       /* Number of backup operations reading this btree */
48802  Btree *pNext;      /* List of other sharable Btrees from the same db */
48803  Btree *pPrev;      /* Back pointer of the same list */
48804#ifndef SQLITE_OMIT_SHARED_CACHE
48805  BtLock lock;       /* Object used to lock page 1 */
48806#endif
48807};
48808
48809/*
48810** Btree.inTrans may take one of the following values.
48811**
48812** If the shared-data extension is enabled, there may be multiple users
48813** of the Btree structure. At most one of these may open a write transaction,
48814** but any number may have active read transactions.
48815*/
48816#define TRANS_NONE  0
48817#define TRANS_READ  1
48818#define TRANS_WRITE 2
48819
48820/*
48821** An instance of this object represents a single database file.
48822**
48823** A single database file can be in use at the same time by two
48824** or more database connections.  When two or more connections are
48825** sharing the same database file, each connection has it own
48826** private Btree object for the file and each of those Btrees points
48827** to this one BtShared object.  BtShared.nRef is the number of
48828** connections currently sharing this database file.
48829**
48830** Fields in this structure are accessed under the BtShared.mutex
48831** mutex, except for nRef and pNext which are accessed under the
48832** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
48833** may not be modified once it is initially set as long as nRef>0.
48834** The pSchema field may be set once under BtShared.mutex and
48835** thereafter is unchanged as long as nRef>0.
48836**
48837** isPending:
48838**
48839**   If a BtShared client fails to obtain a write-lock on a database
48840**   table (because there exists one or more read-locks on the table),
48841**   the shared-cache enters 'pending-lock' state and isPending is
48842**   set to true.
48843**
48844**   The shared-cache leaves the 'pending lock' state when either of
48845**   the following occur:
48846**
48847**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
48848**     2) The number of locks held by other connections drops to zero.
48849**
48850**   while in the 'pending-lock' state, no connection may start a new
48851**   transaction.
48852**
48853**   This feature is included to help prevent writer-starvation.
48854*/
48855struct BtShared {
48856  Pager *pPager;        /* The page cache */
48857  sqlite3 *db;          /* Database connection currently using this Btree */
48858  BtCursor *pCursor;    /* A list of all open cursors */
48859  MemPage *pPage1;      /* First page of the database */
48860  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
48861#ifndef SQLITE_OMIT_AUTOVACUUM
48862  u8 autoVacuum;        /* True if auto-vacuum is enabled */
48863  u8 incrVacuum;        /* True if incr-vacuum is enabled */
48864#endif
48865  u8 inTransaction;     /* Transaction state */
48866  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
48867  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
48868  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
48869  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
48870  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
48871  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
48872  u32 pageSize;         /* Total number of bytes on a page */
48873  u32 usableSize;       /* Number of usable bytes on each page */
48874  int nTransaction;     /* Number of open transactions (read + write) */
48875  u32 nPage;            /* Number of pages in the database */
48876  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
48877  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
48878  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
48879  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
48880#ifndef SQLITE_OMIT_SHARED_CACHE
48881  int nRef;             /* Number of references to this structure */
48882  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
48883  BtLock *pLock;        /* List of locks held on this shared-btree struct */
48884  Btree *pWriter;       /* Btree with currently open write transaction */
48885#endif
48886  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
48887};
48888
48889/*
48890** Allowed values for BtShared.btsFlags
48891*/
48892#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
48893#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
48894#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
48895#define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
48896#define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
48897#define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
48898#define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
48899
48900/*
48901** An instance of the following structure is used to hold information
48902** about a cell.  The parseCellPtr() function fills in this structure
48903** based on information extract from the raw disk page.
48904*/
48905typedef struct CellInfo CellInfo;
48906struct CellInfo {
48907  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
48908  u8 *pCell;     /* Pointer to the start of cell content */
48909  u32 nData;     /* Number of bytes of data */
48910  u32 nPayload;  /* Total amount of payload */
48911  u16 nHeader;   /* Size of the cell content header in bytes */
48912  u16 nLocal;    /* Amount of payload held locally */
48913  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
48914  u16 nSize;     /* Size of the cell content on the main b-tree page */
48915};
48916
48917/*
48918** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
48919** this will be declared corrupt. This value is calculated based on a
48920** maximum database size of 2^31 pages a minimum fanout of 2 for a
48921** root-node and 3 for all other internal nodes.
48922**
48923** If a tree that appears to be taller than this is encountered, it is
48924** assumed that the database is corrupt.
48925*/
48926#define BTCURSOR_MAX_DEPTH 20
48927
48928/*
48929** A cursor is a pointer to a particular entry within a particular
48930** b-tree within a database file.
48931**
48932** The entry is identified by its MemPage and the index in
48933** MemPage.aCell[] of the entry.
48934**
48935** A single database file can be shared by two more database connections,
48936** but cursors cannot be shared.  Each cursor is associated with a
48937** particular database connection identified BtCursor.pBtree.db.
48938**
48939** Fields in this structure are accessed under the BtShared.mutex
48940** found at self->pBt->mutex.
48941*/
48942struct BtCursor {
48943  Btree *pBtree;            /* The Btree to which this cursor belongs */
48944  BtShared *pBt;            /* The BtShared this cursor points to */
48945  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
48946  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
48947#ifndef SQLITE_OMIT_INCRBLOB
48948  Pgno *aOverflow;          /* Cache of overflow page locations */
48949#endif
48950  Pgno pgnoRoot;            /* The root page of this tree */
48951  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
48952  CellInfo info;            /* A parse of the cell we are pointing at */
48953  i64 nKey;        /* Size of pKey, or last integer key */
48954  void *pKey;      /* Saved key that was cursor's last known position */
48955  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
48956  u8 wrFlag;                /* True if writable */
48957  u8 atLast;                /* Cursor pointing to the last entry */
48958  u8 validNKey;             /* True if info.nKey is valid */
48959  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
48960#ifndef SQLITE_OMIT_INCRBLOB
48961  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
48962#endif
48963  i16 iPage;                            /* Index of current page in apPage */
48964  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
48965  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
48966};
48967
48968/*
48969** Potential values for BtCursor.eState.
48970**
48971** CURSOR_VALID:
48972**   Cursor points to a valid entry. getPayload() etc. may be called.
48973**
48974** CURSOR_INVALID:
48975**   Cursor does not point to a valid entry. This can happen (for example)
48976**   because the table is empty or because BtreeCursorFirst() has not been
48977**   called.
48978**
48979** CURSOR_REQUIRESEEK:
48980**   The table that this cursor was opened on still exists, but has been
48981**   modified since the cursor was last used. The cursor position is saved
48982**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
48983**   this state, restoreCursorPosition() can be called to attempt to
48984**   seek the cursor to the saved position.
48985**
48986** CURSOR_FAULT:
48987**   A unrecoverable error (an I/O error or a malloc failure) has occurred
48988**   on a different connection that shares the BtShared cache with this
48989**   cursor.  The error has left the cache in an inconsistent state.
48990**   Do nothing else with this cursor.  Any attempt to use the cursor
48991**   should return the error code stored in BtCursor.skip
48992*/
48993#define CURSOR_INVALID           0
48994#define CURSOR_VALID             1
48995#define CURSOR_REQUIRESEEK       2
48996#define CURSOR_FAULT             3
48997
48998/*
48999** The database page the PENDING_BYTE occupies. This page is never used.
49000*/
49001# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
49002
49003/*
49004** These macros define the location of the pointer-map entry for a
49005** database page. The first argument to each is the number of usable
49006** bytes on each page of the database (often 1024). The second is the
49007** page number to look up in the pointer map.
49008**
49009** PTRMAP_PAGENO returns the database page number of the pointer-map
49010** page that stores the required pointer. PTRMAP_PTROFFSET returns
49011** the offset of the requested map entry.
49012**
49013** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
49014** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
49015** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
49016** this test.
49017*/
49018#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
49019#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
49020#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
49021
49022/*
49023** The pointer map is a lookup table that identifies the parent page for
49024** each child page in the database file.  The parent page is the page that
49025** contains a pointer to the child.  Every page in the database contains
49026** 0 or 1 parent pages.  (In this context 'database page' refers
49027** to any page that is not part of the pointer map itself.)  Each pointer map
49028** entry consists of a single byte 'type' and a 4 byte parent page number.
49029** The PTRMAP_XXX identifiers below are the valid types.
49030**
49031** The purpose of the pointer map is to facility moving pages from one
49032** position in the file to another as part of autovacuum.  When a page
49033** is moved, the pointer in its parent must be updated to point to the
49034** new location.  The pointer map is used to locate the parent page quickly.
49035**
49036** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
49037**                  used in this case.
49038**
49039** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
49040**                  is not used in this case.
49041**
49042** PTRMAP_OVERFLOW1: The database page is the first page in a list of
49043**                   overflow pages. The page number identifies the page that
49044**                   contains the cell with a pointer to this overflow page.
49045**
49046** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
49047**                   overflow pages. The page-number identifies the previous
49048**                   page in the overflow page list.
49049**
49050** PTRMAP_BTREE: The database page is a non-root btree page. The page number
49051**               identifies the parent page in the btree.
49052*/
49053#define PTRMAP_ROOTPAGE 1
49054#define PTRMAP_FREEPAGE 2
49055#define PTRMAP_OVERFLOW1 3
49056#define PTRMAP_OVERFLOW2 4
49057#define PTRMAP_BTREE 5
49058
49059/* A bunch of assert() statements to check the transaction state variables
49060** of handle p (type Btree*) are internally consistent.
49061*/
49062#define btreeIntegrity(p) \
49063  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
49064  assert( p->pBt->inTransaction>=p->inTrans );
49065
49066
49067/*
49068** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
49069** if the database supports auto-vacuum or not. Because it is used
49070** within an expression that is an argument to another macro
49071** (sqliteMallocRaw), it is not possible to use conditional compilation.
49072** So, this macro is defined instead.
49073*/
49074#ifndef SQLITE_OMIT_AUTOVACUUM
49075#define ISAUTOVACUUM (pBt->autoVacuum)
49076#else
49077#define ISAUTOVACUUM 0
49078#endif
49079
49080
49081/*
49082** This structure is passed around through all the sanity checking routines
49083** in order to keep track of some global state information.
49084*/
49085typedef struct IntegrityCk IntegrityCk;
49086struct IntegrityCk {
49087  BtShared *pBt;    /* The tree being checked out */
49088  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
49089  int *anRef;       /* Number of times each page is referenced */
49090  Pgno nPage;       /* Number of pages in the database */
49091  int mxErr;        /* Stop accumulating errors when this reaches zero */
49092  int nErr;         /* Number of messages written to zErrMsg so far */
49093  int mallocFailed; /* A memory allocation error has occurred */
49094  StrAccum errMsg;  /* Accumulate the error message text here */
49095};
49096
49097/*
49098** Routines to read or write a two- and four-byte big-endian integer values.
49099*/
49100#define get2byte(x)   ((x)[0]<<8 | (x)[1])
49101#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
49102#define get4byte sqlite3Get4byte
49103#define put4byte sqlite3Put4byte
49104
49105/************** End of btreeInt.h ********************************************/
49106/************** Continuing where we left off in btmutex.c ********************/
49107#ifndef SQLITE_OMIT_SHARED_CACHE
49108#if SQLITE_THREADSAFE
49109
49110/*
49111** Obtain the BtShared mutex associated with B-Tree handle p. Also,
49112** set BtShared.db to the database handle associated with p and the
49113** p->locked boolean to true.
49114*/
49115static void lockBtreeMutex(Btree *p){
49116  assert( p->locked==0 );
49117  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
49118  assert( sqlite3_mutex_held(p->db->mutex) );
49119
49120  sqlite3_mutex_enter(p->pBt->mutex);
49121  p->pBt->db = p->db;
49122  p->locked = 1;
49123}
49124
49125/*
49126** Release the BtShared mutex associated with B-Tree handle p and
49127** clear the p->locked boolean.
49128*/
49129static void unlockBtreeMutex(Btree *p){
49130  BtShared *pBt = p->pBt;
49131  assert( p->locked==1 );
49132  assert( sqlite3_mutex_held(pBt->mutex) );
49133  assert( sqlite3_mutex_held(p->db->mutex) );
49134  assert( p->db==pBt->db );
49135
49136  sqlite3_mutex_leave(pBt->mutex);
49137  p->locked = 0;
49138}
49139
49140/*
49141** Enter a mutex on the given BTree object.
49142**
49143** If the object is not sharable, then no mutex is ever required
49144** and this routine is a no-op.  The underlying mutex is non-recursive.
49145** But we keep a reference count in Btree.wantToLock so the behavior
49146** of this interface is recursive.
49147**
49148** To avoid deadlocks, multiple Btrees are locked in the same order
49149** by all database connections.  The p->pNext is a list of other
49150** Btrees belonging to the same database connection as the p Btree
49151** which need to be locked after p.  If we cannot get a lock on
49152** p, then first unlock all of the others on p->pNext, then wait
49153** for the lock to become available on p, then relock all of the
49154** subsequent Btrees that desire a lock.
49155*/
49156SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49157  Btree *pLater;
49158
49159  /* Some basic sanity checking on the Btree.  The list of Btrees
49160  ** connected by pNext and pPrev should be in sorted order by
49161  ** Btree.pBt value. All elements of the list should belong to
49162  ** the same connection. Only shared Btrees are on the list. */
49163  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
49164  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
49165  assert( p->pNext==0 || p->pNext->db==p->db );
49166  assert( p->pPrev==0 || p->pPrev->db==p->db );
49167  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
49168
49169  /* Check for locking consistency */
49170  assert( !p->locked || p->wantToLock>0 );
49171  assert( p->sharable || p->wantToLock==0 );
49172
49173  /* We should already hold a lock on the database connection */
49174  assert( sqlite3_mutex_held(p->db->mutex) );
49175
49176  /* Unless the database is sharable and unlocked, then BtShared.db
49177  ** should already be set correctly. */
49178  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
49179
49180  if( !p->sharable ) return;
49181  p->wantToLock++;
49182  if( p->locked ) return;
49183
49184  /* In most cases, we should be able to acquire the lock we
49185  ** want without having to go throught the ascending lock
49186  ** procedure that follows.  Just be sure not to block.
49187  */
49188  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
49189    p->pBt->db = p->db;
49190    p->locked = 1;
49191    return;
49192  }
49193
49194  /* To avoid deadlock, first release all locks with a larger
49195  ** BtShared address.  Then acquire our lock.  Then reacquire
49196  ** the other BtShared locks that we used to hold in ascending
49197  ** order.
49198  */
49199  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49200    assert( pLater->sharable );
49201    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
49202    assert( !pLater->locked || pLater->wantToLock>0 );
49203    if( pLater->locked ){
49204      unlockBtreeMutex(pLater);
49205    }
49206  }
49207  lockBtreeMutex(p);
49208  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49209    if( pLater->wantToLock ){
49210      lockBtreeMutex(pLater);
49211    }
49212  }
49213}
49214
49215/*
49216** Exit the recursive mutex on a Btree.
49217*/
49218SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
49219  if( p->sharable ){
49220    assert( p->wantToLock>0 );
49221    p->wantToLock--;
49222    if( p->wantToLock==0 ){
49223      unlockBtreeMutex(p);
49224    }
49225  }
49226}
49227
49228#ifndef NDEBUG
49229/*
49230** Return true if the BtShared mutex is held on the btree, or if the
49231** B-Tree is not marked as sharable.
49232**
49233** This routine is used only from within assert() statements.
49234*/
49235SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
49236  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
49237  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
49238  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
49239  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
49240
49241  return (p->sharable==0 || p->locked);
49242}
49243#endif
49244
49245
49246#ifndef SQLITE_OMIT_INCRBLOB
49247/*
49248** Enter and leave a mutex on a Btree given a cursor owned by that
49249** Btree.  These entry points are used by incremental I/O and can be
49250** omitted if that module is not used.
49251*/
49252SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
49253  sqlite3BtreeEnter(pCur->pBtree);
49254}
49255SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
49256  sqlite3BtreeLeave(pCur->pBtree);
49257}
49258#endif /* SQLITE_OMIT_INCRBLOB */
49259
49260
49261/*
49262** Enter the mutex on every Btree associated with a database
49263** connection.  This is needed (for example) prior to parsing
49264** a statement since we will be comparing table and column names
49265** against all schemas and we do not want those schemas being
49266** reset out from under us.
49267**
49268** There is a corresponding leave-all procedures.
49269**
49270** Enter the mutexes in accending order by BtShared pointer address
49271** to avoid the possibility of deadlock when two threads with
49272** two or more btrees in common both try to lock all their btrees
49273** at the same instant.
49274*/
49275SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49276  int i;
49277  Btree *p;
49278  assert( sqlite3_mutex_held(db->mutex) );
49279  for(i=0; i<db->nDb; i++){
49280    p = db->aDb[i].pBt;
49281    if( p ) sqlite3BtreeEnter(p);
49282  }
49283}
49284SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
49285  int i;
49286  Btree *p;
49287  assert( sqlite3_mutex_held(db->mutex) );
49288  for(i=0; i<db->nDb; i++){
49289    p = db->aDb[i].pBt;
49290    if( p ) sqlite3BtreeLeave(p);
49291  }
49292}
49293
49294/*
49295** Return true if a particular Btree requires a lock.  Return FALSE if
49296** no lock is ever required since it is not sharable.
49297*/
49298SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
49299  return p->sharable;
49300}
49301
49302#ifndef NDEBUG
49303/*
49304** Return true if the current thread holds the database connection
49305** mutex and all required BtShared mutexes.
49306**
49307** This routine is used inside assert() statements only.
49308*/
49309SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
49310  int i;
49311  if( !sqlite3_mutex_held(db->mutex) ){
49312    return 0;
49313  }
49314  for(i=0; i<db->nDb; i++){
49315    Btree *p;
49316    p = db->aDb[i].pBt;
49317    if( p && p->sharable &&
49318         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
49319      return 0;
49320    }
49321  }
49322  return 1;
49323}
49324#endif /* NDEBUG */
49325
49326#ifndef NDEBUG
49327/*
49328** Return true if the correct mutexes are held for accessing the
49329** db->aDb[iDb].pSchema structure.  The mutexes required for schema
49330** access are:
49331**
49332**   (1) The mutex on db
49333**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
49334**
49335** If pSchema is not NULL, then iDb is computed from pSchema and
49336** db using sqlite3SchemaToIndex().
49337*/
49338SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
49339  Btree *p;
49340  assert( db!=0 );
49341  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
49342  assert( iDb>=0 && iDb<db->nDb );
49343  if( !sqlite3_mutex_held(db->mutex) ) return 0;
49344  if( iDb==1 ) return 1;
49345  p = db->aDb[iDb].pBt;
49346  assert( p!=0 );
49347  return p->sharable==0 || p->locked==1;
49348}
49349#endif /* NDEBUG */
49350
49351#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
49352/*
49353** The following are special cases for mutex enter routines for use
49354** in single threaded applications that use shared cache.  Except for
49355** these two routines, all mutex operations are no-ops in that case and
49356** are null #defines in btree.h.
49357**
49358** If shared cache is disabled, then all btree mutex routines, including
49359** the ones below, are no-ops and are null #defines in btree.h.
49360*/
49361
49362SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49363  p->pBt->db = p->db;
49364}
49365SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49366  int i;
49367  for(i=0; i<db->nDb; i++){
49368    Btree *p = db->aDb[i].pBt;
49369    if( p ){
49370      p->pBt->db = p->db;
49371    }
49372  }
49373}
49374#endif /* if SQLITE_THREADSAFE */
49375#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
49376
49377/************** End of btmutex.c *********************************************/
49378/************** Begin file btree.c *******************************************/
49379/*
49380** 2004 April 6
49381**
49382** The author disclaims copyright to this source code.  In place of
49383** a legal notice, here is a blessing:
49384**
49385**    May you do good and not evil.
49386**    May you find forgiveness for yourself and forgive others.
49387**    May you share freely, never taking more than you give.
49388**
49389*************************************************************************
49390** This file implements a external (disk-based) database using BTrees.
49391** See the header comment on "btreeInt.h" for additional information.
49392** Including a description of file format and an overview of operation.
49393*/
49394
49395/*
49396** The header string that appears at the beginning of every
49397** SQLite database.
49398*/
49399static const char zMagicHeader[] = SQLITE_FILE_HEADER;
49400
49401/*
49402** Set this global variable to 1 to enable tracing using the TRACE
49403** macro.
49404*/
49405#if 0
49406int sqlite3BtreeTrace=1;  /* True to enable tracing */
49407# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
49408#else
49409# define TRACE(X)
49410#endif
49411
49412/*
49413** Extract a 2-byte big-endian integer from an array of unsigned bytes.
49414** But if the value is zero, make it 65536.
49415**
49416** This routine is used to extract the "offset to cell content area" value
49417** from the header of a btree page.  If the page size is 65536 and the page
49418** is empty, the offset should be 65536, but the 2-byte value stores zero.
49419** This routine makes the necessary adjustment to 65536.
49420*/
49421#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
49422
49423#ifndef SQLITE_OMIT_SHARED_CACHE
49424/*
49425** A list of BtShared objects that are eligible for participation
49426** in shared cache.  This variable has file scope during normal builds,
49427** but the test harness needs to access it so we make it global for
49428** test builds.
49429**
49430** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
49431*/
49432#ifdef SQLITE_TEST
49433SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
49434#else
49435static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
49436#endif
49437#endif /* SQLITE_OMIT_SHARED_CACHE */
49438
49439#ifndef SQLITE_OMIT_SHARED_CACHE
49440/*
49441** Enable or disable the shared pager and schema features.
49442**
49443** This routine has no effect on existing database connections.
49444** The shared cache setting effects only future calls to
49445** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
49446*/
49447SQLITE_API int sqlite3_enable_shared_cache(int enable){
49448  sqlite3GlobalConfig.sharedCacheEnabled = enable;
49449  return SQLITE_OK;
49450}
49451#endif
49452
49453
49454
49455#ifdef SQLITE_OMIT_SHARED_CACHE
49456  /*
49457  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
49458  ** and clearAllSharedCacheTableLocks()
49459  ** manipulate entries in the BtShared.pLock linked list used to store
49460  ** shared-cache table level locks. If the library is compiled with the
49461  ** shared-cache feature disabled, then there is only ever one user
49462  ** of each BtShared structure and so this locking is not necessary.
49463  ** So define the lock related functions as no-ops.
49464  */
49465  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
49466  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
49467  #define clearAllSharedCacheTableLocks(a)
49468  #define downgradeAllSharedCacheTableLocks(a)
49469  #define hasSharedCacheTableLock(a,b,c,d) 1
49470  #define hasReadConflicts(a, b) 0
49471#endif
49472
49473#ifndef SQLITE_OMIT_SHARED_CACHE
49474
49475#ifdef SQLITE_DEBUG
49476/*
49477**** This function is only used as part of an assert() statement. ***
49478**
49479** Check to see if pBtree holds the required locks to read or write to the
49480** table with root page iRoot.   Return 1 if it does and 0 if not.
49481**
49482** For example, when writing to a table with root-page iRoot via
49483** Btree connection pBtree:
49484**
49485**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
49486**
49487** When writing to an index that resides in a sharable database, the
49488** caller should have first obtained a lock specifying the root page of
49489** the corresponding table. This makes things a bit more complicated,
49490** as this module treats each table as a separate structure. To determine
49491** the table corresponding to the index being written, this
49492** function has to search through the database schema.
49493**
49494** Instead of a lock on the table/index rooted at page iRoot, the caller may
49495** hold a write-lock on the schema table (root page 1). This is also
49496** acceptable.
49497*/
49498static int hasSharedCacheTableLock(
49499  Btree *pBtree,         /* Handle that must hold lock */
49500  Pgno iRoot,            /* Root page of b-tree */
49501  int isIndex,           /* True if iRoot is the root of an index b-tree */
49502  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
49503){
49504  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
49505  Pgno iTab = 0;
49506  BtLock *pLock;
49507
49508  /* If this database is not shareable, or if the client is reading
49509  ** and has the read-uncommitted flag set, then no lock is required.
49510  ** Return true immediately.
49511  */
49512  if( (pBtree->sharable==0)
49513   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
49514  ){
49515    return 1;
49516  }
49517
49518  /* If the client is reading  or writing an index and the schema is
49519  ** not loaded, then it is too difficult to actually check to see if
49520  ** the correct locks are held.  So do not bother - just return true.
49521  ** This case does not come up very often anyhow.
49522  */
49523  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
49524    return 1;
49525  }
49526
49527  /* Figure out the root-page that the lock should be held on. For table
49528  ** b-trees, this is just the root page of the b-tree being read or
49529  ** written. For index b-trees, it is the root page of the associated
49530  ** table.  */
49531  if( isIndex ){
49532    HashElem *p;
49533    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
49534      Index *pIdx = (Index *)sqliteHashData(p);
49535      if( pIdx->tnum==(int)iRoot ){
49536        iTab = pIdx->pTable->tnum;
49537      }
49538    }
49539  }else{
49540    iTab = iRoot;
49541  }
49542
49543  /* Search for the required lock. Either a write-lock on root-page iTab, a
49544  ** write-lock on the schema table, or (if the client is reading) a
49545  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
49546  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
49547    if( pLock->pBtree==pBtree
49548     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
49549     && pLock->eLock>=eLockType
49550    ){
49551      return 1;
49552    }
49553  }
49554
49555  /* Failed to find the required lock. */
49556  return 0;
49557}
49558#endif /* SQLITE_DEBUG */
49559
49560#ifdef SQLITE_DEBUG
49561/*
49562**** This function may be used as part of assert() statements only. ****
49563**
49564** Return true if it would be illegal for pBtree to write into the
49565** table or index rooted at iRoot because other shared connections are
49566** simultaneously reading that same table or index.
49567**
49568** It is illegal for pBtree to write if some other Btree object that
49569** shares the same BtShared object is currently reading or writing
49570** the iRoot table.  Except, if the other Btree object has the
49571** read-uncommitted flag set, then it is OK for the other object to
49572** have a read cursor.
49573**
49574** For example, before writing to any part of the table or index
49575** rooted at page iRoot, one should call:
49576**
49577**    assert( !hasReadConflicts(pBtree, iRoot) );
49578*/
49579static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
49580  BtCursor *p;
49581  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
49582    if( p->pgnoRoot==iRoot
49583     && p->pBtree!=pBtree
49584     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
49585    ){
49586      return 1;
49587    }
49588  }
49589  return 0;
49590}
49591#endif    /* #ifdef SQLITE_DEBUG */
49592
49593/*
49594** Query to see if Btree handle p may obtain a lock of type eLock
49595** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
49596** SQLITE_OK if the lock may be obtained (by calling
49597** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
49598*/
49599static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
49600  BtShared *pBt = p->pBt;
49601  BtLock *pIter;
49602
49603  assert( sqlite3BtreeHoldsMutex(p) );
49604  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49605  assert( p->db!=0 );
49606  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
49607
49608  /* If requesting a write-lock, then the Btree must have an open write
49609  ** transaction on this file. And, obviously, for this to be so there
49610  ** must be an open write transaction on the file itself.
49611  */
49612  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
49613  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
49614
49615  /* This routine is a no-op if the shared-cache is not enabled */
49616  if( !p->sharable ){
49617    return SQLITE_OK;
49618  }
49619
49620  /* If some other connection is holding an exclusive lock, the
49621  ** requested lock may not be obtained.
49622  */
49623  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
49624    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
49625    return SQLITE_LOCKED_SHAREDCACHE;
49626  }
49627
49628  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49629    /* The condition (pIter->eLock!=eLock) in the following if(...)
49630    ** statement is a simplification of:
49631    **
49632    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
49633    **
49634    ** since we know that if eLock==WRITE_LOCK, then no other connection
49635    ** may hold a WRITE_LOCK on any table in this file (since there can
49636    ** only be a single writer).
49637    */
49638    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
49639    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
49640    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
49641      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
49642      if( eLock==WRITE_LOCK ){
49643        assert( p==pBt->pWriter );
49644        pBt->btsFlags |= BTS_PENDING;
49645      }
49646      return SQLITE_LOCKED_SHAREDCACHE;
49647    }
49648  }
49649  return SQLITE_OK;
49650}
49651#endif /* !SQLITE_OMIT_SHARED_CACHE */
49652
49653#ifndef SQLITE_OMIT_SHARED_CACHE
49654/*
49655** Add a lock on the table with root-page iTable to the shared-btree used
49656** by Btree handle p. Parameter eLock must be either READ_LOCK or
49657** WRITE_LOCK.
49658**
49659** This function assumes the following:
49660**
49661**   (a) The specified Btree object p is connected to a sharable
49662**       database (one with the BtShared.sharable flag set), and
49663**
49664**   (b) No other Btree objects hold a lock that conflicts
49665**       with the requested lock (i.e. querySharedCacheTableLock() has
49666**       already been called and returned SQLITE_OK).
49667**
49668** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
49669** is returned if a malloc attempt fails.
49670*/
49671static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
49672  BtShared *pBt = p->pBt;
49673  BtLock *pLock = 0;
49674  BtLock *pIter;
49675
49676  assert( sqlite3BtreeHoldsMutex(p) );
49677  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49678  assert( p->db!=0 );
49679
49680  /* A connection with the read-uncommitted flag set will never try to
49681  ** obtain a read-lock using this function. The only read-lock obtained
49682  ** by a connection in read-uncommitted mode is on the sqlite_master
49683  ** table, and that lock is obtained in BtreeBeginTrans().  */
49684  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
49685
49686  /* This function should only be called on a sharable b-tree after it
49687  ** has been determined that no other b-tree holds a conflicting lock.  */
49688  assert( p->sharable );
49689  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
49690
49691  /* First search the list for an existing lock on this table. */
49692  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49693    if( pIter->iTable==iTable && pIter->pBtree==p ){
49694      pLock = pIter;
49695      break;
49696    }
49697  }
49698
49699  /* If the above search did not find a BtLock struct associating Btree p
49700  ** with table iTable, allocate one and link it into the list.
49701  */
49702  if( !pLock ){
49703    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
49704    if( !pLock ){
49705      return SQLITE_NOMEM;
49706    }
49707    pLock->iTable = iTable;
49708    pLock->pBtree = p;
49709    pLock->pNext = pBt->pLock;
49710    pBt->pLock = pLock;
49711  }
49712
49713  /* Set the BtLock.eLock variable to the maximum of the current lock
49714  ** and the requested lock. This means if a write-lock was already held
49715  ** and a read-lock requested, we don't incorrectly downgrade the lock.
49716  */
49717  assert( WRITE_LOCK>READ_LOCK );
49718  if( eLock>pLock->eLock ){
49719    pLock->eLock = eLock;
49720  }
49721
49722  return SQLITE_OK;
49723}
49724#endif /* !SQLITE_OMIT_SHARED_CACHE */
49725
49726#ifndef SQLITE_OMIT_SHARED_CACHE
49727/*
49728** Release all the table locks (locks obtained via calls to
49729** the setSharedCacheTableLock() procedure) held by Btree object p.
49730**
49731** This function assumes that Btree p has an open read or write
49732** transaction. If it does not, then the BTS_PENDING flag
49733** may be incorrectly cleared.
49734*/
49735static void clearAllSharedCacheTableLocks(Btree *p){
49736  BtShared *pBt = p->pBt;
49737  BtLock **ppIter = &pBt->pLock;
49738
49739  assert( sqlite3BtreeHoldsMutex(p) );
49740  assert( p->sharable || 0==*ppIter );
49741  assert( p->inTrans>0 );
49742
49743  while( *ppIter ){
49744    BtLock *pLock = *ppIter;
49745    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
49746    assert( pLock->pBtree->inTrans>=pLock->eLock );
49747    if( pLock->pBtree==p ){
49748      *ppIter = pLock->pNext;
49749      assert( pLock->iTable!=1 || pLock==&p->lock );
49750      if( pLock->iTable!=1 ){
49751        sqlite3_free(pLock);
49752      }
49753    }else{
49754      ppIter = &pLock->pNext;
49755    }
49756  }
49757
49758  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
49759  if( pBt->pWriter==p ){
49760    pBt->pWriter = 0;
49761    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
49762  }else if( pBt->nTransaction==2 ){
49763    /* This function is called when Btree p is concluding its
49764    ** transaction. If there currently exists a writer, and p is not
49765    ** that writer, then the number of locks held by connections other
49766    ** than the writer must be about to drop to zero. In this case
49767    ** set the BTS_PENDING flag to 0.
49768    **
49769    ** If there is not currently a writer, then BTS_PENDING must
49770    ** be zero already. So this next line is harmless in that case.
49771    */
49772    pBt->btsFlags &= ~BTS_PENDING;
49773  }
49774}
49775
49776/*
49777** This function changes all write-locks held by Btree p into read-locks.
49778*/
49779static void downgradeAllSharedCacheTableLocks(Btree *p){
49780  BtShared *pBt = p->pBt;
49781  if( pBt->pWriter==p ){
49782    BtLock *pLock;
49783    pBt->pWriter = 0;
49784    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
49785    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
49786      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
49787      pLock->eLock = READ_LOCK;
49788    }
49789  }
49790}
49791
49792#endif /* SQLITE_OMIT_SHARED_CACHE */
49793
49794static void releasePage(MemPage *pPage);  /* Forward reference */
49795
49796/*
49797***** This routine is used inside of assert() only ****
49798**
49799** Verify that the cursor holds the mutex on its BtShared
49800*/
49801#ifdef SQLITE_DEBUG
49802static int cursorHoldsMutex(BtCursor *p){
49803  return sqlite3_mutex_held(p->pBt->mutex);
49804}
49805#endif
49806
49807
49808#ifndef SQLITE_OMIT_INCRBLOB
49809/*
49810** Invalidate the overflow page-list cache for cursor pCur, if any.
49811*/
49812static void invalidateOverflowCache(BtCursor *pCur){
49813  assert( cursorHoldsMutex(pCur) );
49814  sqlite3_free(pCur->aOverflow);
49815  pCur->aOverflow = 0;
49816}
49817
49818/*
49819** Invalidate the overflow page-list cache for all cursors opened
49820** on the shared btree structure pBt.
49821*/
49822static void invalidateAllOverflowCache(BtShared *pBt){
49823  BtCursor *p;
49824  assert( sqlite3_mutex_held(pBt->mutex) );
49825  for(p=pBt->pCursor; p; p=p->pNext){
49826    invalidateOverflowCache(p);
49827  }
49828}
49829
49830/*
49831** This function is called before modifying the contents of a table
49832** to invalidate any incrblob cursors that are open on the
49833** row or one of the rows being modified.
49834**
49835** If argument isClearTable is true, then the entire contents of the
49836** table is about to be deleted. In this case invalidate all incrblob
49837** cursors open on any row within the table with root-page pgnoRoot.
49838**
49839** Otherwise, if argument isClearTable is false, then the row with
49840** rowid iRow is being replaced or deleted. In this case invalidate
49841** only those incrblob cursors open on that specific row.
49842*/
49843static void invalidateIncrblobCursors(
49844  Btree *pBtree,          /* The database file to check */
49845  i64 iRow,               /* The rowid that might be changing */
49846  int isClearTable        /* True if all rows are being deleted */
49847){
49848  BtCursor *p;
49849  BtShared *pBt = pBtree->pBt;
49850  assert( sqlite3BtreeHoldsMutex(pBtree) );
49851  for(p=pBt->pCursor; p; p=p->pNext){
49852    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
49853      p->eState = CURSOR_INVALID;
49854    }
49855  }
49856}
49857
49858#else
49859  /* Stub functions when INCRBLOB is omitted */
49860  #define invalidateOverflowCache(x)
49861  #define invalidateAllOverflowCache(x)
49862  #define invalidateIncrblobCursors(x,y,z)
49863#endif /* SQLITE_OMIT_INCRBLOB */
49864
49865/*
49866** Set bit pgno of the BtShared.pHasContent bitvec. This is called
49867** when a page that previously contained data becomes a free-list leaf
49868** page.
49869**
49870** The BtShared.pHasContent bitvec exists to work around an obscure
49871** bug caused by the interaction of two useful IO optimizations surrounding
49872** free-list leaf pages:
49873**
49874**   1) When all data is deleted from a page and the page becomes
49875**      a free-list leaf page, the page is not written to the database
49876**      (as free-list leaf pages contain no meaningful data). Sometimes
49877**      such a page is not even journalled (as it will not be modified,
49878**      why bother journalling it?).
49879**
49880**   2) When a free-list leaf page is reused, its content is not read
49881**      from the database or written to the journal file (why should it
49882**      be, if it is not at all meaningful?).
49883**
49884** By themselves, these optimizations work fine and provide a handy
49885** performance boost to bulk delete or insert operations. However, if
49886** a page is moved to the free-list and then reused within the same
49887** transaction, a problem comes up. If the page is not journalled when
49888** it is moved to the free-list and it is also not journalled when it
49889** is extracted from the free-list and reused, then the original data
49890** may be lost. In the event of a rollback, it may not be possible
49891** to restore the database to its original configuration.
49892**
49893** The solution is the BtShared.pHasContent bitvec. Whenever a page is
49894** moved to become a free-list leaf page, the corresponding bit is
49895** set in the bitvec. Whenever a leaf page is extracted from the free-list,
49896** optimization 2 above is omitted if the corresponding bit is already
49897** set in BtShared.pHasContent. The contents of the bitvec are cleared
49898** at the end of every transaction.
49899*/
49900static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
49901  int rc = SQLITE_OK;
49902  if( !pBt->pHasContent ){
49903    assert( pgno<=pBt->nPage );
49904    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
49905    if( !pBt->pHasContent ){
49906      rc = SQLITE_NOMEM;
49907    }
49908  }
49909  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
49910    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
49911  }
49912  return rc;
49913}
49914
49915/*
49916** Query the BtShared.pHasContent vector.
49917**
49918** This function is called when a free-list leaf page is removed from the
49919** free-list for reuse. It returns false if it is safe to retrieve the
49920** page from the pager layer with the 'no-content' flag set. True otherwise.
49921*/
49922static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
49923  Bitvec *p = pBt->pHasContent;
49924  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
49925}
49926
49927/*
49928** Clear (destroy) the BtShared.pHasContent bitvec. This should be
49929** invoked at the conclusion of each write-transaction.
49930*/
49931static void btreeClearHasContent(BtShared *pBt){
49932  sqlite3BitvecDestroy(pBt->pHasContent);
49933  pBt->pHasContent = 0;
49934}
49935
49936/*
49937** Save the current cursor position in the variables BtCursor.nKey
49938** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
49939**
49940** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
49941** prior to calling this routine.
49942*/
49943static int saveCursorPosition(BtCursor *pCur){
49944  int rc;
49945
49946  assert( CURSOR_VALID==pCur->eState );
49947  assert( 0==pCur->pKey );
49948  assert( cursorHoldsMutex(pCur) );
49949
49950  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
49951  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
49952
49953  /* If this is an intKey table, then the above call to BtreeKeySize()
49954  ** stores the integer key in pCur->nKey. In this case this value is
49955  ** all that is required. Otherwise, if pCur is not open on an intKey
49956  ** table, then malloc space for and store the pCur->nKey bytes of key
49957  ** data.
49958  */
49959  if( 0==pCur->apPage[0]->intKey ){
49960    void *pKey = sqlite3Malloc( (int)pCur->nKey );
49961    if( pKey ){
49962      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
49963      if( rc==SQLITE_OK ){
49964        pCur->pKey = pKey;
49965      }else{
49966        sqlite3_free(pKey);
49967      }
49968    }else{
49969      rc = SQLITE_NOMEM;
49970    }
49971  }
49972  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
49973
49974  if( rc==SQLITE_OK ){
49975    int i;
49976    for(i=0; i<=pCur->iPage; i++){
49977      releasePage(pCur->apPage[i]);
49978      pCur->apPage[i] = 0;
49979    }
49980    pCur->iPage = -1;
49981    pCur->eState = CURSOR_REQUIRESEEK;
49982  }
49983
49984  invalidateOverflowCache(pCur);
49985  return rc;
49986}
49987
49988/*
49989** Save the positions of all cursors (except pExcept) that are open on
49990** the table  with root-page iRoot. Usually, this is called just before cursor
49991** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
49992*/
49993static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
49994  BtCursor *p;
49995  assert( sqlite3_mutex_held(pBt->mutex) );
49996  assert( pExcept==0 || pExcept->pBt==pBt );
49997  for(p=pBt->pCursor; p; p=p->pNext){
49998    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
49999        p->eState==CURSOR_VALID ){
50000      int rc = saveCursorPosition(p);
50001      if( SQLITE_OK!=rc ){
50002        return rc;
50003      }
50004    }
50005  }
50006  return SQLITE_OK;
50007}
50008
50009/*
50010** Clear the current cursor position.
50011*/
50012SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
50013  assert( cursorHoldsMutex(pCur) );
50014  sqlite3_free(pCur->pKey);
50015  pCur->pKey = 0;
50016  pCur->eState = CURSOR_INVALID;
50017}
50018
50019/*
50020** In this version of BtreeMoveto, pKey is a packed index record
50021** such as is generated by the OP_MakeRecord opcode.  Unpack the
50022** record and then call BtreeMovetoUnpacked() to do the work.
50023*/
50024static int btreeMoveto(
50025  BtCursor *pCur,     /* Cursor open on the btree to be searched */
50026  const void *pKey,   /* Packed key if the btree is an index */
50027  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
50028  int bias,           /* Bias search to the high end */
50029  int *pRes           /* Write search results here */
50030){
50031  int rc;                    /* Status code */
50032  UnpackedRecord *pIdxKey;   /* Unpacked index key */
50033  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
50034  char *pFree = 0;
50035
50036  if( pKey ){
50037    assert( nKey==(i64)(int)nKey );
50038    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
50039        pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
50040    );
50041    if( pIdxKey==0 ) return SQLITE_NOMEM;
50042    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
50043  }else{
50044    pIdxKey = 0;
50045  }
50046  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
50047  if( pFree ){
50048    sqlite3DbFree(pCur->pKeyInfo->db, pFree);
50049  }
50050  return rc;
50051}
50052
50053/*
50054** Restore the cursor to the position it was in (or as close to as possible)
50055** when saveCursorPosition() was called. Note that this call deletes the
50056** saved position info stored by saveCursorPosition(), so there can be
50057** at most one effective restoreCursorPosition() call after each
50058** saveCursorPosition().
50059*/
50060static int btreeRestoreCursorPosition(BtCursor *pCur){
50061  int rc;
50062  assert( cursorHoldsMutex(pCur) );
50063  assert( pCur->eState>=CURSOR_REQUIRESEEK );
50064  if( pCur->eState==CURSOR_FAULT ){
50065    return pCur->skipNext;
50066  }
50067  pCur->eState = CURSOR_INVALID;
50068  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
50069  if( rc==SQLITE_OK ){
50070    sqlite3_free(pCur->pKey);
50071    pCur->pKey = 0;
50072    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
50073  }
50074  return rc;
50075}
50076
50077#define restoreCursorPosition(p) \
50078  (p->eState>=CURSOR_REQUIRESEEK ? \
50079         btreeRestoreCursorPosition(p) : \
50080         SQLITE_OK)
50081
50082/*
50083** Determine whether or not a cursor has moved from the position it
50084** was last placed at.  Cursors can move when the row they are pointing
50085** at is deleted out from under them.
50086**
50087** This routine returns an error code if something goes wrong.  The
50088** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
50089*/
50090SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
50091  int rc;
50092
50093  rc = restoreCursorPosition(pCur);
50094  if( rc ){
50095    *pHasMoved = 1;
50096    return rc;
50097  }
50098  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
50099    *pHasMoved = 1;
50100  }else{
50101    *pHasMoved = 0;
50102  }
50103  return SQLITE_OK;
50104}
50105
50106#ifndef SQLITE_OMIT_AUTOVACUUM
50107/*
50108** Given a page number of a regular database page, return the page
50109** number for the pointer-map page that contains the entry for the
50110** input page number.
50111**
50112** Return 0 (not a valid page) for pgno==1 since there is
50113** no pointer map associated with page 1.  The integrity_check logic
50114** requires that ptrmapPageno(*,1)!=1.
50115*/
50116static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
50117  int nPagesPerMapPage;
50118  Pgno iPtrMap, ret;
50119  assert( sqlite3_mutex_held(pBt->mutex) );
50120  if( pgno<2 ) return 0;
50121  nPagesPerMapPage = (pBt->usableSize/5)+1;
50122  iPtrMap = (pgno-2)/nPagesPerMapPage;
50123  ret = (iPtrMap*nPagesPerMapPage) + 2;
50124  if( ret==PENDING_BYTE_PAGE(pBt) ){
50125    ret++;
50126  }
50127  return ret;
50128}
50129
50130/*
50131** Write an entry into the pointer map.
50132**
50133** This routine updates the pointer map entry for page number 'key'
50134** so that it maps to type 'eType' and parent page number 'pgno'.
50135**
50136** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
50137** a no-op.  If an error occurs, the appropriate error code is written
50138** into *pRC.
50139*/
50140static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
50141  DbPage *pDbPage;  /* The pointer map page */
50142  u8 *pPtrmap;      /* The pointer map data */
50143  Pgno iPtrmap;     /* The pointer map page number */
50144  int offset;       /* Offset in pointer map page */
50145  int rc;           /* Return code from subfunctions */
50146
50147  if( *pRC ) return;
50148
50149  assert( sqlite3_mutex_held(pBt->mutex) );
50150  /* The master-journal page number must never be used as a pointer map page */
50151  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
50152
50153  assert( pBt->autoVacuum );
50154  if( key==0 ){
50155    *pRC = SQLITE_CORRUPT_BKPT;
50156    return;
50157  }
50158  iPtrmap = PTRMAP_PAGENO(pBt, key);
50159  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50160  if( rc!=SQLITE_OK ){
50161    *pRC = rc;
50162    return;
50163  }
50164  offset = PTRMAP_PTROFFSET(iPtrmap, key);
50165  if( offset<0 ){
50166    *pRC = SQLITE_CORRUPT_BKPT;
50167    goto ptrmap_exit;
50168  }
50169  assert( offset <= (int)pBt->usableSize-5 );
50170  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50171
50172  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
50173    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
50174    *pRC= rc = sqlite3PagerWrite(pDbPage);
50175    if( rc==SQLITE_OK ){
50176      pPtrmap[offset] = eType;
50177      put4byte(&pPtrmap[offset+1], parent);
50178    }
50179  }
50180
50181ptrmap_exit:
50182  sqlite3PagerUnref(pDbPage);
50183}
50184
50185/*
50186** Read an entry from the pointer map.
50187**
50188** This routine retrieves the pointer map entry for page 'key', writing
50189** the type and parent page number to *pEType and *pPgno respectively.
50190** An error code is returned if something goes wrong, otherwise SQLITE_OK.
50191*/
50192static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
50193  DbPage *pDbPage;   /* The pointer map page */
50194  int iPtrmap;       /* Pointer map page index */
50195  u8 *pPtrmap;       /* Pointer map page data */
50196  int offset;        /* Offset of entry in pointer map */
50197  int rc;
50198
50199  assert( sqlite3_mutex_held(pBt->mutex) );
50200
50201  iPtrmap = PTRMAP_PAGENO(pBt, key);
50202  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50203  if( rc!=0 ){
50204    return rc;
50205  }
50206  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50207
50208  offset = PTRMAP_PTROFFSET(iPtrmap, key);
50209  if( offset<0 ){
50210    sqlite3PagerUnref(pDbPage);
50211    return SQLITE_CORRUPT_BKPT;
50212  }
50213  assert( offset <= (int)pBt->usableSize-5 );
50214  assert( pEType!=0 );
50215  *pEType = pPtrmap[offset];
50216  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
50217
50218  sqlite3PagerUnref(pDbPage);
50219  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
50220  return SQLITE_OK;
50221}
50222
50223#else /* if defined SQLITE_OMIT_AUTOVACUUM */
50224  #define ptrmapPut(w,x,y,z,rc)
50225  #define ptrmapGet(w,x,y,z) SQLITE_OK
50226  #define ptrmapPutOvflPtr(x, y, rc)
50227#endif
50228
50229/*
50230** Given a btree page and a cell index (0 means the first cell on
50231** the page, 1 means the second cell, and so forth) return a pointer
50232** to the cell content.
50233**
50234** This routine works only for pages that do not contain overflow cells.
50235*/
50236#define findCell(P,I) \
50237  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
50238#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
50239
50240
50241/*
50242** This a more complex version of findCell() that works for
50243** pages that do contain overflow cells.
50244*/
50245static u8 *findOverflowCell(MemPage *pPage, int iCell){
50246  int i;
50247  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50248  for(i=pPage->nOverflow-1; i>=0; i--){
50249    int k;
50250    k = pPage->aiOvfl[i];
50251    if( k<=iCell ){
50252      if( k==iCell ){
50253        return pPage->apOvfl[i];
50254      }
50255      iCell--;
50256    }
50257  }
50258  return findCell(pPage, iCell);
50259}
50260
50261/*
50262** Parse a cell content block and fill in the CellInfo structure.  There
50263** are two versions of this function.  btreeParseCell() takes a
50264** cell index as the second argument and btreeParseCellPtr()
50265** takes a pointer to the body of the cell as its second argument.
50266**
50267** Within this file, the parseCell() macro can be called instead of
50268** btreeParseCellPtr(). Using some compilers, this will be faster.
50269*/
50270static void btreeParseCellPtr(
50271  MemPage *pPage,         /* Page containing the cell */
50272  u8 *pCell,              /* Pointer to the cell text. */
50273  CellInfo *pInfo         /* Fill in this structure */
50274){
50275  u16 n;                  /* Number bytes in cell content header */
50276  u32 nPayload;           /* Number of bytes of cell payload */
50277
50278  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50279
50280  pInfo->pCell = pCell;
50281  assert( pPage->leaf==0 || pPage->leaf==1 );
50282  n = pPage->childPtrSize;
50283  assert( n==4-4*pPage->leaf );
50284  if( pPage->intKey ){
50285    if( pPage->hasData ){
50286      n += getVarint32(&pCell[n], nPayload);
50287    }else{
50288      nPayload = 0;
50289    }
50290    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
50291    pInfo->nData = nPayload;
50292  }else{
50293    pInfo->nData = 0;
50294    n += getVarint32(&pCell[n], nPayload);
50295    pInfo->nKey = nPayload;
50296  }
50297  pInfo->nPayload = nPayload;
50298  pInfo->nHeader = n;
50299  testcase( nPayload==pPage->maxLocal );
50300  testcase( nPayload==pPage->maxLocal+1 );
50301  if( likely(nPayload<=pPage->maxLocal) ){
50302    /* This is the (easy) common case where the entire payload fits
50303    ** on the local page.  No overflow is required.
50304    */
50305    if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
50306    pInfo->nLocal = (u16)nPayload;
50307    pInfo->iOverflow = 0;
50308  }else{
50309    /* If the payload will not fit completely on the local page, we have
50310    ** to decide how much to store locally and how much to spill onto
50311    ** overflow pages.  The strategy is to minimize the amount of unused
50312    ** space on overflow pages while keeping the amount of local storage
50313    ** in between minLocal and maxLocal.
50314    **
50315    ** Warning:  changing the way overflow payload is distributed in any
50316    ** way will result in an incompatible file format.
50317    */
50318    int minLocal;  /* Minimum amount of payload held locally */
50319    int maxLocal;  /* Maximum amount of payload held locally */
50320    int surplus;   /* Overflow payload available for local storage */
50321
50322    minLocal = pPage->minLocal;
50323    maxLocal = pPage->maxLocal;
50324    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
50325    testcase( surplus==maxLocal );
50326    testcase( surplus==maxLocal+1 );
50327    if( surplus <= maxLocal ){
50328      pInfo->nLocal = (u16)surplus;
50329    }else{
50330      pInfo->nLocal = (u16)minLocal;
50331    }
50332    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
50333    pInfo->nSize = pInfo->iOverflow + 4;
50334  }
50335}
50336#define parseCell(pPage, iCell, pInfo) \
50337  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
50338static void btreeParseCell(
50339  MemPage *pPage,         /* Page containing the cell */
50340  int iCell,              /* The cell index.  First cell is 0 */
50341  CellInfo *pInfo         /* Fill in this structure */
50342){
50343  parseCell(pPage, iCell, pInfo);
50344}
50345
50346/*
50347** Compute the total number of bytes that a Cell needs in the cell
50348** data area of the btree-page.  The return number includes the cell
50349** data header and the local payload, but not any overflow page or
50350** the space used by the cell pointer.
50351*/
50352static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
50353  u8 *pIter = &pCell[pPage->childPtrSize];
50354  u32 nSize;
50355
50356#ifdef SQLITE_DEBUG
50357  /* The value returned by this function should always be the same as
50358  ** the (CellInfo.nSize) value found by doing a full parse of the
50359  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
50360  ** this function verifies that this invariant is not violated. */
50361  CellInfo debuginfo;
50362  btreeParseCellPtr(pPage, pCell, &debuginfo);
50363#endif
50364
50365  if( pPage->intKey ){
50366    u8 *pEnd;
50367    if( pPage->hasData ){
50368      pIter += getVarint32(pIter, nSize);
50369    }else{
50370      nSize = 0;
50371    }
50372
50373    /* pIter now points at the 64-bit integer key value, a variable length
50374    ** integer. The following block moves pIter to point at the first byte
50375    ** past the end of the key value. */
50376    pEnd = &pIter[9];
50377    while( (*pIter++)&0x80 && pIter<pEnd );
50378  }else{
50379    pIter += getVarint32(pIter, nSize);
50380  }
50381
50382  testcase( nSize==pPage->maxLocal );
50383  testcase( nSize==pPage->maxLocal+1 );
50384  if( nSize>pPage->maxLocal ){
50385    int minLocal = pPage->minLocal;
50386    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
50387    testcase( nSize==pPage->maxLocal );
50388    testcase( nSize==pPage->maxLocal+1 );
50389    if( nSize>pPage->maxLocal ){
50390      nSize = minLocal;
50391    }
50392    nSize += 4;
50393  }
50394  nSize += (u32)(pIter - pCell);
50395
50396  /* The minimum size of any cell is 4 bytes. */
50397  if( nSize<4 ){
50398    nSize = 4;
50399  }
50400
50401  assert( nSize==debuginfo.nSize );
50402  return (u16)nSize;
50403}
50404
50405#ifdef SQLITE_DEBUG
50406/* This variation on cellSizePtr() is used inside of assert() statements
50407** only. */
50408static u16 cellSize(MemPage *pPage, int iCell){
50409  return cellSizePtr(pPage, findCell(pPage, iCell));
50410}
50411#endif
50412
50413#ifndef SQLITE_OMIT_AUTOVACUUM
50414/*
50415** If the cell pCell, part of page pPage contains a pointer
50416** to an overflow page, insert an entry into the pointer-map
50417** for the overflow page.
50418*/
50419static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
50420  CellInfo info;
50421  if( *pRC ) return;
50422  assert( pCell!=0 );
50423  btreeParseCellPtr(pPage, pCell, &info);
50424  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
50425  if( info.iOverflow ){
50426    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
50427    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
50428  }
50429}
50430#endif
50431
50432
50433/*
50434** Defragment the page given.  All Cells are moved to the
50435** end of the page and all free space is collected into one
50436** big FreeBlk that occurs in between the header and cell
50437** pointer array and the cell content area.
50438*/
50439static int defragmentPage(MemPage *pPage){
50440  int i;                     /* Loop counter */
50441  int pc;                    /* Address of a i-th cell */
50442  int hdr;                   /* Offset to the page header */
50443  int size;                  /* Size of a cell */
50444  int usableSize;            /* Number of usable bytes on a page */
50445  int cellOffset;            /* Offset to the cell pointer array */
50446  int cbrk;                  /* Offset to the cell content area */
50447  int nCell;                 /* Number of cells on the page */
50448  unsigned char *data;       /* The page data */
50449  unsigned char *temp;       /* Temp area for cell content */
50450  int iCellFirst;            /* First allowable cell index */
50451  int iCellLast;             /* Last possible cell index */
50452
50453
50454  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50455  assert( pPage->pBt!=0 );
50456  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
50457  assert( pPage->nOverflow==0 );
50458  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50459  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
50460  data = pPage->aData;
50461  hdr = pPage->hdrOffset;
50462  cellOffset = pPage->cellOffset;
50463  nCell = pPage->nCell;
50464  assert( nCell==get2byte(&data[hdr+3]) );
50465  usableSize = pPage->pBt->usableSize;
50466  cbrk = get2byte(&data[hdr+5]);
50467  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
50468  cbrk = usableSize;
50469  iCellFirst = cellOffset + 2*nCell;
50470  iCellLast = usableSize - 4;
50471  for(i=0; i<nCell; i++){
50472    u8 *pAddr;     /* The i-th cell pointer */
50473    pAddr = &data[cellOffset + i*2];
50474    pc = get2byte(pAddr);
50475    testcase( pc==iCellFirst );
50476    testcase( pc==iCellLast );
50477#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50478    /* These conditions have already been verified in btreeInitPage()
50479    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
50480    */
50481    if( pc<iCellFirst || pc>iCellLast ){
50482      return SQLITE_CORRUPT_BKPT;
50483    }
50484#endif
50485    assert( pc>=iCellFirst && pc<=iCellLast );
50486    size = cellSizePtr(pPage, &temp[pc]);
50487    cbrk -= size;
50488#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50489    if( cbrk<iCellFirst ){
50490      return SQLITE_CORRUPT_BKPT;
50491    }
50492#else
50493    if( cbrk<iCellFirst || pc+size>usableSize ){
50494      return SQLITE_CORRUPT_BKPT;
50495    }
50496#endif
50497    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
50498    testcase( cbrk+size==usableSize );
50499    testcase( pc+size==usableSize );
50500    memcpy(&data[cbrk], &temp[pc], size);
50501    put2byte(pAddr, cbrk);
50502  }
50503  assert( cbrk>=iCellFirst );
50504  put2byte(&data[hdr+5], cbrk);
50505  data[hdr+1] = 0;
50506  data[hdr+2] = 0;
50507  data[hdr+7] = 0;
50508  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
50509  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50510  if( cbrk-iCellFirst!=pPage->nFree ){
50511    return SQLITE_CORRUPT_BKPT;
50512  }
50513  return SQLITE_OK;
50514}
50515
50516/*
50517** Allocate nByte bytes of space from within the B-Tree page passed
50518** as the first argument. Write into *pIdx the index into pPage->aData[]
50519** of the first byte of allocated space. Return either SQLITE_OK or
50520** an error code (usually SQLITE_CORRUPT).
50521**
50522** The caller guarantees that there is sufficient space to make the
50523** allocation.  This routine might need to defragment in order to bring
50524** all the space together, however.  This routine will avoid using
50525** the first two bytes past the cell pointer area since presumably this
50526** allocation is being made in order to insert a new cell, so we will
50527** also end up needing a new cell pointer.
50528*/
50529static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
50530  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
50531  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
50532  int nFrag;                           /* Number of fragmented bytes on pPage */
50533  int top;                             /* First byte of cell content area */
50534  int gap;        /* First byte of gap between cell pointers and cell content */
50535  int rc;         /* Integer return code */
50536  int usableSize; /* Usable size of the page */
50537
50538  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50539  assert( pPage->pBt );
50540  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50541  assert( nByte>=0 );  /* Minimum cell size is 4 */
50542  assert( pPage->nFree>=nByte );
50543  assert( pPage->nOverflow==0 );
50544  usableSize = pPage->pBt->usableSize;
50545  assert( nByte < usableSize-8 );
50546
50547  nFrag = data[hdr+7];
50548  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
50549  gap = pPage->cellOffset + 2*pPage->nCell;
50550  top = get2byteNotZero(&data[hdr+5]);
50551  if( gap>top ) return SQLITE_CORRUPT_BKPT;
50552  testcase( gap+2==top );
50553  testcase( gap+1==top );
50554  testcase( gap==top );
50555
50556  if( nFrag>=60 ){
50557    /* Always defragment highly fragmented pages */
50558    rc = defragmentPage(pPage);
50559    if( rc ) return rc;
50560    top = get2byteNotZero(&data[hdr+5]);
50561  }else if( gap+2<=top ){
50562    /* Search the freelist looking for a free slot big enough to satisfy
50563    ** the request. The allocation is made from the first free slot in
50564    ** the list that is large enough to accomadate it.
50565    */
50566    int pc, addr;
50567    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
50568      int size;            /* Size of the free slot */
50569      if( pc>usableSize-4 || pc<addr+4 ){
50570        return SQLITE_CORRUPT_BKPT;
50571      }
50572      size = get2byte(&data[pc+2]);
50573      if( size>=nByte ){
50574        int x = size - nByte;
50575        testcase( x==4 );
50576        testcase( x==3 );
50577        if( x<4 ){
50578          /* Remove the slot from the free-list. Update the number of
50579          ** fragmented bytes within the page. */
50580          memcpy(&data[addr], &data[pc], 2);
50581          data[hdr+7] = (u8)(nFrag + x);
50582        }else if( size+pc > usableSize ){
50583          return SQLITE_CORRUPT_BKPT;
50584        }else{
50585          /* The slot remains on the free-list. Reduce its size to account
50586          ** for the portion used by the new allocation. */
50587          put2byte(&data[pc+2], x);
50588        }
50589        *pIdx = pc + x;
50590        return SQLITE_OK;
50591      }
50592    }
50593  }
50594
50595  /* Check to make sure there is enough space in the gap to satisfy
50596  ** the allocation.  If not, defragment.
50597  */
50598  testcase( gap+2+nByte==top );
50599  if( gap+2+nByte>top ){
50600    rc = defragmentPage(pPage);
50601    if( rc ) return rc;
50602    top = get2byteNotZero(&data[hdr+5]);
50603    assert( gap+nByte<=top );
50604  }
50605
50606
50607  /* Allocate memory from the gap in between the cell pointer array
50608  ** and the cell content area.  The btreeInitPage() call has already
50609  ** validated the freelist.  Given that the freelist is valid, there
50610  ** is no way that the allocation can extend off the end of the page.
50611  ** The assert() below verifies the previous sentence.
50612  */
50613  top -= nByte;
50614  put2byte(&data[hdr+5], top);
50615  assert( top+nByte <= (int)pPage->pBt->usableSize );
50616  *pIdx = top;
50617  return SQLITE_OK;
50618}
50619
50620/*
50621** Return a section of the pPage->aData to the freelist.
50622** The first byte of the new free block is pPage->aDisk[start]
50623** and the size of the block is "size" bytes.
50624**
50625** Most of the effort here is involved in coalesing adjacent
50626** free blocks into a single big free block.
50627*/
50628static int freeSpace(MemPage *pPage, int start, int size){
50629  int addr, pbegin, hdr;
50630  int iLast;                        /* Largest possible freeblock offset */
50631  unsigned char *data = pPage->aData;
50632
50633  assert( pPage->pBt!=0 );
50634  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50635  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
50636  assert( (start + size) <= (int)pPage->pBt->usableSize );
50637  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50638  assert( size>=0 );   /* Minimum cell size is 4 */
50639
50640  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
50641    /* Overwrite deleted information with zeros when the secure_delete
50642    ** option is enabled */
50643    memset(&data[start], 0, size);
50644  }
50645
50646  /* Add the space back into the linked list of freeblocks.  Note that
50647  ** even though the freeblock list was checked by btreeInitPage(),
50648  ** btreeInitPage() did not detect overlapping cells or
50649  ** freeblocks that overlapped cells.   Nor does it detect when the
50650  ** cell content area exceeds the value in the page header.  If these
50651  ** situations arise, then subsequent insert operations might corrupt
50652  ** the freelist.  So we do need to check for corruption while scanning
50653  ** the freelist.
50654  */
50655  hdr = pPage->hdrOffset;
50656  addr = hdr + 1;
50657  iLast = pPage->pBt->usableSize - 4;
50658  assert( start<=iLast );
50659  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
50660    if( pbegin<addr+4 ){
50661      return SQLITE_CORRUPT_BKPT;
50662    }
50663    addr = pbegin;
50664  }
50665  if( pbegin>iLast ){
50666    return SQLITE_CORRUPT_BKPT;
50667  }
50668  assert( pbegin>addr || pbegin==0 );
50669  put2byte(&data[addr], start);
50670  put2byte(&data[start], pbegin);
50671  put2byte(&data[start+2], size);
50672  pPage->nFree = pPage->nFree + (u16)size;
50673
50674  /* Coalesce adjacent free blocks */
50675  addr = hdr + 1;
50676  while( (pbegin = get2byte(&data[addr]))>0 ){
50677    int pnext, psize, x;
50678    assert( pbegin>addr );
50679    assert( pbegin <= (int)pPage->pBt->usableSize-4 );
50680    pnext = get2byte(&data[pbegin]);
50681    psize = get2byte(&data[pbegin+2]);
50682    if( pbegin + psize + 3 >= pnext && pnext>0 ){
50683      int frag = pnext - (pbegin+psize);
50684      if( (frag<0) || (frag>(int)data[hdr+7]) ){
50685        return SQLITE_CORRUPT_BKPT;
50686      }
50687      data[hdr+7] -= (u8)frag;
50688      x = get2byte(&data[pnext]);
50689      put2byte(&data[pbegin], x);
50690      x = pnext + get2byte(&data[pnext+2]) - pbegin;
50691      put2byte(&data[pbegin+2], x);
50692    }else{
50693      addr = pbegin;
50694    }
50695  }
50696
50697  /* If the cell content area begins with a freeblock, remove it. */
50698  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
50699    int top;
50700    pbegin = get2byte(&data[hdr+1]);
50701    memcpy(&data[hdr+1], &data[pbegin], 2);
50702    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
50703    put2byte(&data[hdr+5], top);
50704  }
50705  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50706  return SQLITE_OK;
50707}
50708
50709/*
50710** Decode the flags byte (the first byte of the header) for a page
50711** and initialize fields of the MemPage structure accordingly.
50712**
50713** Only the following combinations are supported.  Anything different
50714** indicates a corrupt database files:
50715**
50716**         PTF_ZERODATA
50717**         PTF_ZERODATA | PTF_LEAF
50718**         PTF_LEAFDATA | PTF_INTKEY
50719**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
50720*/
50721static int decodeFlags(MemPage *pPage, int flagByte){
50722  BtShared *pBt;     /* A copy of pPage->pBt */
50723
50724  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
50725  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50726  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
50727  flagByte &= ~PTF_LEAF;
50728  pPage->childPtrSize = 4-4*pPage->leaf;
50729  pBt = pPage->pBt;
50730  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
50731    pPage->intKey = 1;
50732    pPage->hasData = pPage->leaf;
50733    pPage->maxLocal = pBt->maxLeaf;
50734    pPage->minLocal = pBt->minLeaf;
50735  }else if( flagByte==PTF_ZERODATA ){
50736    pPage->intKey = 0;
50737    pPage->hasData = 0;
50738    pPage->maxLocal = pBt->maxLocal;
50739    pPage->minLocal = pBt->minLocal;
50740  }else{
50741    return SQLITE_CORRUPT_BKPT;
50742  }
50743  pPage->max1bytePayload = pBt->max1bytePayload;
50744  return SQLITE_OK;
50745}
50746
50747/*
50748** Initialize the auxiliary information for a disk block.
50749**
50750** Return SQLITE_OK on success.  If we see that the page does
50751** not contain a well-formed database page, then return
50752** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
50753** guarantee that the page is well-formed.  It only shows that
50754** we failed to detect any corruption.
50755*/
50756static int btreeInitPage(MemPage *pPage){
50757
50758  assert( pPage->pBt!=0 );
50759  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50760  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
50761  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
50762  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
50763
50764  if( !pPage->isInit ){
50765    u16 pc;            /* Address of a freeblock within pPage->aData[] */
50766    u8 hdr;            /* Offset to beginning of page header */
50767    u8 *data;          /* Equal to pPage->aData */
50768    BtShared *pBt;        /* The main btree structure */
50769    int usableSize;    /* Amount of usable space on each page */
50770    u16 cellOffset;    /* Offset from start of page to first cell pointer */
50771    int nFree;         /* Number of unused bytes on the page */
50772    int top;           /* First byte of the cell content area */
50773    int iCellFirst;    /* First allowable cell or freeblock offset */
50774    int iCellLast;     /* Last possible cell or freeblock offset */
50775
50776    pBt = pPage->pBt;
50777
50778    hdr = pPage->hdrOffset;
50779    data = pPage->aData;
50780    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
50781    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
50782    pPage->maskPage = (u16)(pBt->pageSize - 1);
50783    pPage->nOverflow = 0;
50784    usableSize = pBt->usableSize;
50785    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
50786    pPage->aDataEnd = &data[usableSize];
50787    pPage->aCellIdx = &data[cellOffset];
50788    top = get2byteNotZero(&data[hdr+5]);
50789    pPage->nCell = get2byte(&data[hdr+3]);
50790    if( pPage->nCell>MX_CELL(pBt) ){
50791      /* To many cells for a single page.  The page must be corrupt */
50792      return SQLITE_CORRUPT_BKPT;
50793    }
50794    testcase( pPage->nCell==MX_CELL(pBt) );
50795
50796    /* A malformed database page might cause us to read past the end
50797    ** of page when parsing a cell.
50798    **
50799    ** The following block of code checks early to see if a cell extends
50800    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
50801    ** returned if it does.
50802    */
50803    iCellFirst = cellOffset + 2*pPage->nCell;
50804    iCellLast = usableSize - 4;
50805#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50806    {
50807      int i;            /* Index into the cell pointer array */
50808      int sz;           /* Size of a cell */
50809
50810      if( !pPage->leaf ) iCellLast--;
50811      for(i=0; i<pPage->nCell; i++){
50812        pc = get2byte(&data[cellOffset+i*2]);
50813        testcase( pc==iCellFirst );
50814        testcase( pc==iCellLast );
50815        if( pc<iCellFirst || pc>iCellLast ){
50816          return SQLITE_CORRUPT_BKPT;
50817        }
50818        sz = cellSizePtr(pPage, &data[pc]);
50819        testcase( pc+sz==usableSize );
50820        if( pc+sz>usableSize ){
50821          return SQLITE_CORRUPT_BKPT;
50822        }
50823      }
50824      if( !pPage->leaf ) iCellLast++;
50825    }
50826#endif
50827
50828    /* Compute the total free space on the page */
50829    pc = get2byte(&data[hdr+1]);
50830    nFree = data[hdr+7] + top;
50831    while( pc>0 ){
50832      u16 next, size;
50833      if( pc<iCellFirst || pc>iCellLast ){
50834        /* Start of free block is off the page */
50835        return SQLITE_CORRUPT_BKPT;
50836      }
50837      next = get2byte(&data[pc]);
50838      size = get2byte(&data[pc+2]);
50839      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
50840        /* Free blocks must be in ascending order. And the last byte of
50841	** the free-block must lie on the database page.  */
50842        return SQLITE_CORRUPT_BKPT;
50843      }
50844      nFree = nFree + size;
50845      pc = next;
50846    }
50847
50848    /* At this point, nFree contains the sum of the offset to the start
50849    ** of the cell-content area plus the number of free bytes within
50850    ** the cell-content area. If this is greater than the usable-size
50851    ** of the page, then the page must be corrupted. This check also
50852    ** serves to verify that the offset to the start of the cell-content
50853    ** area, according to the page header, lies within the page.
50854    */
50855    if( nFree>usableSize ){
50856      return SQLITE_CORRUPT_BKPT;
50857    }
50858    pPage->nFree = (u16)(nFree - iCellFirst);
50859    pPage->isInit = 1;
50860  }
50861  return SQLITE_OK;
50862}
50863
50864/*
50865** Set up a raw page so that it looks like a database page holding
50866** no entries.
50867*/
50868static void zeroPage(MemPage *pPage, int flags){
50869  unsigned char *data = pPage->aData;
50870  BtShared *pBt = pPage->pBt;
50871  u8 hdr = pPage->hdrOffset;
50872  u16 first;
50873
50874  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
50875  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
50876  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
50877  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50878  assert( sqlite3_mutex_held(pBt->mutex) );
50879  if( pBt->btsFlags & BTS_SECURE_DELETE ){
50880    memset(&data[hdr], 0, pBt->usableSize - hdr);
50881  }
50882  data[hdr] = (char)flags;
50883  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
50884  memset(&data[hdr+1], 0, 4);
50885  data[hdr+7] = 0;
50886  put2byte(&data[hdr+5], pBt->usableSize);
50887  pPage->nFree = (u16)(pBt->usableSize - first);
50888  decodeFlags(pPage, flags);
50889  pPage->hdrOffset = hdr;
50890  pPage->cellOffset = first;
50891  pPage->aDataEnd = &data[pBt->usableSize];
50892  pPage->aCellIdx = &data[first];
50893  pPage->nOverflow = 0;
50894  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
50895  pPage->maskPage = (u16)(pBt->pageSize - 1);
50896  pPage->nCell = 0;
50897  pPage->isInit = 1;
50898}
50899
50900
50901/*
50902** Convert a DbPage obtained from the pager into a MemPage used by
50903** the btree layer.
50904*/
50905static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
50906  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
50907  pPage->aData = sqlite3PagerGetData(pDbPage);
50908  pPage->pDbPage = pDbPage;
50909  pPage->pBt = pBt;
50910  pPage->pgno = pgno;
50911  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
50912  return pPage;
50913}
50914
50915/*
50916** Get a page from the pager.  Initialize the MemPage.pBt and
50917** MemPage.aData elements if needed.
50918**
50919** If the noContent flag is set, it means that we do not care about
50920** the content of the page at this time.  So do not go to the disk
50921** to fetch the content.  Just fill in the content with zeros for now.
50922** If in the future we call sqlite3PagerWrite() on this page, that
50923** means we have started to be concerned about content and the disk
50924** read should occur at that point.
50925*/
50926static int btreeGetPage(
50927  BtShared *pBt,       /* The btree */
50928  Pgno pgno,           /* Number of the page to fetch */
50929  MemPage **ppPage,    /* Return the page in this parameter */
50930  int noContent        /* Do not load page content if true */
50931){
50932  int rc;
50933  DbPage *pDbPage;
50934
50935  assert( sqlite3_mutex_held(pBt->mutex) );
50936  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
50937  if( rc ) return rc;
50938  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
50939  return SQLITE_OK;
50940}
50941
50942/*
50943** Retrieve a page from the pager cache. If the requested page is not
50944** already in the pager cache return NULL. Initialize the MemPage.pBt and
50945** MemPage.aData elements if needed.
50946*/
50947static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
50948  DbPage *pDbPage;
50949  assert( sqlite3_mutex_held(pBt->mutex) );
50950  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
50951  if( pDbPage ){
50952    return btreePageFromDbPage(pDbPage, pgno, pBt);
50953  }
50954  return 0;
50955}
50956
50957/*
50958** Return the size of the database file in pages. If there is any kind of
50959** error, return ((unsigned int)-1).
50960*/
50961static Pgno btreePagecount(BtShared *pBt){
50962  return pBt->nPage;
50963}
50964SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
50965  assert( sqlite3BtreeHoldsMutex(p) );
50966  assert( ((p->pBt->nPage)&0x8000000)==0 );
50967  return (int)btreePagecount(p->pBt);
50968}
50969
50970/*
50971** Get a page from the pager and initialize it.  This routine is just a
50972** convenience wrapper around separate calls to btreeGetPage() and
50973** btreeInitPage().
50974**
50975** If an error occurs, then the value *ppPage is set to is undefined. It
50976** may remain unchanged, or it may be set to an invalid value.
50977*/
50978static int getAndInitPage(
50979  BtShared *pBt,          /* The database file */
50980  Pgno pgno,           /* Number of the page to get */
50981  MemPage **ppPage     /* Write the page pointer here */
50982){
50983  int rc;
50984  assert( sqlite3_mutex_held(pBt->mutex) );
50985
50986  if( pgno>btreePagecount(pBt) ){
50987    rc = SQLITE_CORRUPT_BKPT;
50988  }else{
50989    rc = btreeGetPage(pBt, pgno, ppPage, 0);
50990    if( rc==SQLITE_OK ){
50991      rc = btreeInitPage(*ppPage);
50992      if( rc!=SQLITE_OK ){
50993        releasePage(*ppPage);
50994      }
50995    }
50996  }
50997
50998  testcase( pgno==0 );
50999  assert( pgno!=0 || rc==SQLITE_CORRUPT );
51000  return rc;
51001}
51002
51003/*
51004** Release a MemPage.  This should be called once for each prior
51005** call to btreeGetPage.
51006*/
51007static void releasePage(MemPage *pPage){
51008  if( pPage ){
51009    assert( pPage->aData );
51010    assert( pPage->pBt );
51011    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51012    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
51013    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51014    sqlite3PagerUnref(pPage->pDbPage);
51015  }
51016}
51017
51018/*
51019** During a rollback, when the pager reloads information into the cache
51020** so that the cache is restored to its original state at the start of
51021** the transaction, for each page restored this routine is called.
51022**
51023** This routine needs to reset the extra data section at the end of the
51024** page to agree with the restored data.
51025*/
51026static void pageReinit(DbPage *pData){
51027  MemPage *pPage;
51028  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
51029  assert( sqlite3PagerPageRefcount(pData)>0 );
51030  if( pPage->isInit ){
51031    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51032    pPage->isInit = 0;
51033    if( sqlite3PagerPageRefcount(pData)>1 ){
51034      /* pPage might not be a btree page;  it might be an overflow page
51035      ** or ptrmap page or a free page.  In those cases, the following
51036      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
51037      ** But no harm is done by this.  And it is very important that
51038      ** btreeInitPage() be called on every btree page so we make
51039      ** the call for every page that comes in for re-initing. */
51040      btreeInitPage(pPage);
51041    }
51042  }
51043}
51044
51045/*
51046** Invoke the busy handler for a btree.
51047*/
51048static int btreeInvokeBusyHandler(void *pArg){
51049  BtShared *pBt = (BtShared*)pArg;
51050  assert( pBt->db );
51051  assert( sqlite3_mutex_held(pBt->db->mutex) );
51052  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
51053}
51054
51055/*
51056** Open a database file.
51057**
51058** zFilename is the name of the database file.  If zFilename is NULL
51059** then an ephemeral database is created.  The ephemeral database might
51060** be exclusively in memory, or it might use a disk-based memory cache.
51061** Either way, the ephemeral database will be automatically deleted
51062** when sqlite3BtreeClose() is called.
51063**
51064** If zFilename is ":memory:" then an in-memory database is created
51065** that is automatically destroyed when it is closed.
51066**
51067** The "flags" parameter is a bitmask that might contain bits like
51068** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
51069**
51070** If the database is already opened in the same database connection
51071** and we are in shared cache mode, then the open will fail with an
51072** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
51073** objects in the same database connection since doing so will lead
51074** to problems with locking.
51075*/
51076SQLITE_PRIVATE int sqlite3BtreeOpen(
51077  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
51078  const char *zFilename,  /* Name of the file containing the BTree database */
51079  sqlite3 *db,            /* Associated database handle */
51080  Btree **ppBtree,        /* Pointer to new Btree object written here */
51081  int flags,              /* Options */
51082  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
51083){
51084  BtShared *pBt = 0;             /* Shared part of btree structure */
51085  Btree *p;                      /* Handle to return */
51086  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
51087  int rc = SQLITE_OK;            /* Result code from this function */
51088  u8 nReserve;                   /* Byte of unused space on each page */
51089  unsigned char zDbHeader[100];  /* Database header content */
51090
51091  /* True if opening an ephemeral, temporary database */
51092  const int isTempDb = zFilename==0 || zFilename[0]==0;
51093
51094  /* Set the variable isMemdb to true for an in-memory database, or
51095  ** false for a file-based database.
51096  */
51097#ifdef SQLITE_OMIT_MEMORYDB
51098  const int isMemdb = 0;
51099#else
51100  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
51101                       || (isTempDb && sqlite3TempInMemory(db));
51102#endif
51103
51104  assert( db!=0 );
51105  assert( pVfs!=0 );
51106  assert( sqlite3_mutex_held(db->mutex) );
51107  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
51108
51109  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
51110  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
51111
51112  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
51113  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
51114
51115  if( isMemdb ){
51116    flags |= BTREE_MEMORY;
51117  }
51118  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
51119    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
51120  }
51121  p = sqlite3MallocZero(sizeof(Btree));
51122  if( !p ){
51123    return SQLITE_NOMEM;
51124  }
51125  p->inTrans = TRANS_NONE;
51126  p->db = db;
51127#ifndef SQLITE_OMIT_SHARED_CACHE
51128  p->lock.pBtree = p;
51129  p->lock.iTable = 1;
51130#endif
51131
51132#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51133  /*
51134  ** If this Btree is a candidate for shared cache, try to find an
51135  ** existing BtShared object that we can share with
51136  */
51137  if( isMemdb==0 && isTempDb==0 ){
51138    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
51139      int nFullPathname = pVfs->mxPathname+1;
51140      char *zFullPathname = sqlite3Malloc(nFullPathname);
51141      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51142      p->sharable = 1;
51143      if( !zFullPathname ){
51144        sqlite3_free(p);
51145        return SQLITE_NOMEM;
51146      }
51147      rc = sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
51148      if( rc ){
51149        sqlite3_free(zFullPathname);
51150        sqlite3_free(p);
51151        return rc;
51152      }
51153#if SQLITE_THREADSAFE
51154      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
51155      sqlite3_mutex_enter(mutexOpen);
51156      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
51157      sqlite3_mutex_enter(mutexShared);
51158#endif
51159      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
51160        assert( pBt->nRef>0 );
51161        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
51162                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
51163          int iDb;
51164          for(iDb=db->nDb-1; iDb>=0; iDb--){
51165            Btree *pExisting = db->aDb[iDb].pBt;
51166            if( pExisting && pExisting->pBt==pBt ){
51167              sqlite3_mutex_leave(mutexShared);
51168              sqlite3_mutex_leave(mutexOpen);
51169              sqlite3_free(zFullPathname);
51170              sqlite3_free(p);
51171              return SQLITE_CONSTRAINT;
51172            }
51173          }
51174          p->pBt = pBt;
51175          pBt->nRef++;
51176          break;
51177        }
51178      }
51179      sqlite3_mutex_leave(mutexShared);
51180      sqlite3_free(zFullPathname);
51181    }
51182#ifdef SQLITE_DEBUG
51183    else{
51184      /* In debug mode, we mark all persistent databases as sharable
51185      ** even when they are not.  This exercises the locking code and
51186      ** gives more opportunity for asserts(sqlite3_mutex_held())
51187      ** statements to find locking problems.
51188      */
51189      p->sharable = 1;
51190    }
51191#endif
51192  }
51193#endif
51194  if( pBt==0 ){
51195    /*
51196    ** The following asserts make sure that structures used by the btree are
51197    ** the right size.  This is to guard against size changes that result
51198    ** when compiling on a different architecture.
51199    */
51200    assert( sizeof(i64)==8 || sizeof(i64)==4 );
51201    assert( sizeof(u64)==8 || sizeof(u64)==4 );
51202    assert( sizeof(u32)==4 );
51203    assert( sizeof(u16)==2 );
51204    assert( sizeof(Pgno)==4 );
51205
51206    pBt = sqlite3MallocZero( sizeof(*pBt) );
51207    if( pBt==0 ){
51208      rc = SQLITE_NOMEM;
51209      goto btree_open_out;
51210    }
51211    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
51212                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
51213    if( rc==SQLITE_OK ){
51214      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
51215    }
51216    if( rc!=SQLITE_OK ){
51217      goto btree_open_out;
51218    }
51219    pBt->openFlags = (u8)flags;
51220    pBt->db = db;
51221    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
51222    p->pBt = pBt;
51223
51224    pBt->pCursor = 0;
51225    pBt->pPage1 = 0;
51226    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
51227#ifdef SQLITE_SECURE_DELETE
51228    pBt->btsFlags |= BTS_SECURE_DELETE;
51229#endif
51230    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
51231    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
51232         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
51233      pBt->pageSize = 0;
51234#ifndef SQLITE_OMIT_AUTOVACUUM
51235      /* If the magic name ":memory:" will create an in-memory database, then
51236      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
51237      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
51238      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
51239      ** regular file-name. In this case the auto-vacuum applies as per normal.
51240      */
51241      if( zFilename && !isMemdb ){
51242        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
51243        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
51244      }
51245#endif
51246      nReserve = 0;
51247    }else{
51248      nReserve = zDbHeader[20];
51249      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51250#ifndef SQLITE_OMIT_AUTOVACUUM
51251      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
51252      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
51253#endif
51254    }
51255    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51256    if( rc ) goto btree_open_out;
51257    pBt->usableSize = pBt->pageSize - nReserve;
51258    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
51259
51260#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51261    /* Add the new BtShared object to the linked list sharable BtShareds.
51262    */
51263    if( p->sharable ){
51264      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51265      pBt->nRef = 1;
51266      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
51267      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
51268        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
51269        if( pBt->mutex==0 ){
51270          rc = SQLITE_NOMEM;
51271          db->mallocFailed = 0;
51272          goto btree_open_out;
51273        }
51274      }
51275      sqlite3_mutex_enter(mutexShared);
51276      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
51277      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
51278      sqlite3_mutex_leave(mutexShared);
51279    }
51280#endif
51281  }
51282
51283#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51284  /* If the new Btree uses a sharable pBtShared, then link the new
51285  ** Btree into the list of all sharable Btrees for the same connection.
51286  ** The list is kept in ascending order by pBt address.
51287  */
51288  if( p->sharable ){
51289    int i;
51290    Btree *pSib;
51291    for(i=0; i<db->nDb; i++){
51292      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
51293        while( pSib->pPrev ){ pSib = pSib->pPrev; }
51294        if( p->pBt<pSib->pBt ){
51295          p->pNext = pSib;
51296          p->pPrev = 0;
51297          pSib->pPrev = p;
51298        }else{
51299          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
51300            pSib = pSib->pNext;
51301          }
51302          p->pNext = pSib->pNext;
51303          p->pPrev = pSib;
51304          if( p->pNext ){
51305            p->pNext->pPrev = p;
51306          }
51307          pSib->pNext = p;
51308        }
51309        break;
51310      }
51311    }
51312  }
51313#endif
51314  *ppBtree = p;
51315
51316btree_open_out:
51317  if( rc!=SQLITE_OK ){
51318    if( pBt && pBt->pPager ){
51319      sqlite3PagerClose(pBt->pPager);
51320    }
51321    sqlite3_free(pBt);
51322    sqlite3_free(p);
51323    *ppBtree = 0;
51324  }else{
51325    /* If the B-Tree was successfully opened, set the pager-cache size to the
51326    ** default value. Except, when opening on an existing shared pager-cache,
51327    ** do not change the pager-cache size.
51328    */
51329    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
51330      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
51331    }
51332  }
51333  if( mutexOpen ){
51334    assert( sqlite3_mutex_held(mutexOpen) );
51335    sqlite3_mutex_leave(mutexOpen);
51336  }
51337  return rc;
51338}
51339
51340/*
51341** Decrement the BtShared.nRef counter.  When it reaches zero,
51342** remove the BtShared structure from the sharing list.  Return
51343** true if the BtShared.nRef counter reaches zero and return
51344** false if it is still positive.
51345*/
51346static int removeFromSharingList(BtShared *pBt){
51347#ifndef SQLITE_OMIT_SHARED_CACHE
51348  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
51349  BtShared *pList;
51350  int removed = 0;
51351
51352  assert( sqlite3_mutex_notheld(pBt->mutex) );
51353  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
51354  sqlite3_mutex_enter(pMaster);
51355  pBt->nRef--;
51356  if( pBt->nRef<=0 ){
51357    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
51358      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
51359    }else{
51360      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
51361      while( ALWAYS(pList) && pList->pNext!=pBt ){
51362        pList=pList->pNext;
51363      }
51364      if( ALWAYS(pList) ){
51365        pList->pNext = pBt->pNext;
51366      }
51367    }
51368    if( SQLITE_THREADSAFE ){
51369      sqlite3_mutex_free(pBt->mutex);
51370    }
51371    removed = 1;
51372  }
51373  sqlite3_mutex_leave(pMaster);
51374  return removed;
51375#else
51376  return 1;
51377#endif
51378}
51379
51380/*
51381** Make sure pBt->pTmpSpace points to an allocation of
51382** MX_CELL_SIZE(pBt) bytes.
51383*/
51384static void allocateTempSpace(BtShared *pBt){
51385  if( !pBt->pTmpSpace ){
51386    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
51387  }
51388}
51389
51390/*
51391** Free the pBt->pTmpSpace allocation
51392*/
51393static void freeTempSpace(BtShared *pBt){
51394  sqlite3PageFree( pBt->pTmpSpace);
51395  pBt->pTmpSpace = 0;
51396}
51397
51398/*
51399** Close an open database and invalidate all cursors.
51400*/
51401SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
51402  BtShared *pBt = p->pBt;
51403  BtCursor *pCur;
51404
51405  /* Close all cursors opened via this handle.  */
51406  assert( sqlite3_mutex_held(p->db->mutex) );
51407  sqlite3BtreeEnter(p);
51408  pCur = pBt->pCursor;
51409  while( pCur ){
51410    BtCursor *pTmp = pCur;
51411    pCur = pCur->pNext;
51412    if( pTmp->pBtree==p ){
51413      sqlite3BtreeCloseCursor(pTmp);
51414    }
51415  }
51416
51417  /* Rollback any active transaction and free the handle structure.
51418  ** The call to sqlite3BtreeRollback() drops any table-locks held by
51419  ** this handle.
51420  */
51421  sqlite3BtreeRollback(p, SQLITE_OK);
51422  sqlite3BtreeLeave(p);
51423
51424  /* If there are still other outstanding references to the shared-btree
51425  ** structure, return now. The remainder of this procedure cleans
51426  ** up the shared-btree.
51427  */
51428  assert( p->wantToLock==0 && p->locked==0 );
51429  if( !p->sharable || removeFromSharingList(pBt) ){
51430    /* The pBt is no longer on the sharing list, so we can access
51431    ** it without having to hold the mutex.
51432    **
51433    ** Clean out and delete the BtShared object.
51434    */
51435    assert( !pBt->pCursor );
51436    sqlite3PagerClose(pBt->pPager);
51437    if( pBt->xFreeSchema && pBt->pSchema ){
51438      pBt->xFreeSchema(pBt->pSchema);
51439    }
51440    sqlite3DbFree(0, pBt->pSchema);
51441    freeTempSpace(pBt);
51442    sqlite3_free(pBt);
51443  }
51444
51445#ifndef SQLITE_OMIT_SHARED_CACHE
51446  assert( p->wantToLock==0 );
51447  assert( p->locked==0 );
51448  if( p->pPrev ) p->pPrev->pNext = p->pNext;
51449  if( p->pNext ) p->pNext->pPrev = p->pPrev;
51450#endif
51451
51452  sqlite3_free(p);
51453  return SQLITE_OK;
51454}
51455
51456/*
51457** Change the limit on the number of pages allowed in the cache.
51458**
51459** The maximum number of cache pages is set to the absolute
51460** value of mxPage.  If mxPage is negative, the pager will
51461** operate asynchronously - it will not stop to do fsync()s
51462** to insure data is written to the disk surface before
51463** continuing.  Transactions still work if synchronous is off,
51464** and the database cannot be corrupted if this program
51465** crashes.  But if the operating system crashes or there is
51466** an abrupt power failure when synchronous is off, the database
51467** could be left in an inconsistent and unrecoverable state.
51468** Synchronous is on by default so database corruption is not
51469** normally a worry.
51470*/
51471SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
51472  BtShared *pBt = p->pBt;
51473  assert( sqlite3_mutex_held(p->db->mutex) );
51474  sqlite3BtreeEnter(p);
51475  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
51476  sqlite3BtreeLeave(p);
51477  return SQLITE_OK;
51478}
51479
51480/*
51481** Change the way data is synced to disk in order to increase or decrease
51482** how well the database resists damage due to OS crashes and power
51483** failures.  Level 1 is the same as asynchronous (no syncs() occur and
51484** there is a high probability of damage)  Level 2 is the default.  There
51485** is a very low but non-zero probability of damage.  Level 3 reduces the
51486** probability of damage to near zero but with a write performance reduction.
51487*/
51488#ifndef SQLITE_OMIT_PAGER_PRAGMAS
51489SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
51490  Btree *p,              /* The btree to set the safety level on */
51491  int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
51492  int fullSync,          /* PRAGMA fullfsync. */
51493  int ckptFullSync       /* PRAGMA checkpoint_fullfync */
51494){
51495  BtShared *pBt = p->pBt;
51496  assert( sqlite3_mutex_held(p->db->mutex) );
51497  assert( level>=1 && level<=3 );
51498  sqlite3BtreeEnter(p);
51499  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
51500  sqlite3BtreeLeave(p);
51501  return SQLITE_OK;
51502}
51503#endif
51504
51505/*
51506** Return TRUE if the given btree is set to safety level 1.  In other
51507** words, return TRUE if no sync() occurs on the disk files.
51508*/
51509SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
51510  BtShared *pBt = p->pBt;
51511  int rc;
51512  assert( sqlite3_mutex_held(p->db->mutex) );
51513  sqlite3BtreeEnter(p);
51514  assert( pBt && pBt->pPager );
51515  rc = sqlite3PagerNosync(pBt->pPager);
51516  sqlite3BtreeLeave(p);
51517  return rc;
51518}
51519
51520/*
51521** Change the default pages size and the number of reserved bytes per page.
51522** Or, if the page size has already been fixed, return SQLITE_READONLY
51523** without changing anything.
51524**
51525** The page size must be a power of 2 between 512 and 65536.  If the page
51526** size supplied does not meet this constraint then the page size is not
51527** changed.
51528**
51529** Page sizes are constrained to be a power of two so that the region
51530** of the database file used for locking (beginning at PENDING_BYTE,
51531** the first byte past the 1GB boundary, 0x40000000) needs to occur
51532** at the beginning of a page.
51533**
51534** If parameter nReserve is less than zero, then the number of reserved
51535** bytes per page is left unchanged.
51536**
51537** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
51538** and autovacuum mode can no longer be changed.
51539*/
51540SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
51541  int rc = SQLITE_OK;
51542  BtShared *pBt = p->pBt;
51543  assert( nReserve>=-1 && nReserve<=255 );
51544  sqlite3BtreeEnter(p);
51545  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
51546    sqlite3BtreeLeave(p);
51547    return SQLITE_READONLY;
51548  }
51549  if( nReserve<0 ){
51550    nReserve = pBt->pageSize - pBt->usableSize;
51551  }
51552  assert( nReserve>=0 && nReserve<=255 );
51553  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
51554        ((pageSize-1)&pageSize)==0 ){
51555    assert( (pageSize & 7)==0 );
51556    assert( !pBt->pPage1 && !pBt->pCursor );
51557    pBt->pageSize = (u32)pageSize;
51558    freeTempSpace(pBt);
51559  }
51560  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51561  pBt->usableSize = pBt->pageSize - (u16)nReserve;
51562  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51563  sqlite3BtreeLeave(p);
51564  return rc;
51565}
51566
51567/*
51568** Return the currently defined page size
51569*/
51570SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
51571  return p->pBt->pageSize;
51572}
51573
51574#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
51575/*
51576** Return the number of bytes of space at the end of every page that
51577** are intentually left unused.  This is the "reserved" space that is
51578** sometimes used by extensions.
51579*/
51580SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
51581  int n;
51582  sqlite3BtreeEnter(p);
51583  n = p->pBt->pageSize - p->pBt->usableSize;
51584  sqlite3BtreeLeave(p);
51585  return n;
51586}
51587
51588/*
51589** Set the maximum page count for a database if mxPage is positive.
51590** No changes are made if mxPage is 0 or negative.
51591** Regardless of the value of mxPage, return the maximum page count.
51592*/
51593SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
51594  int n;
51595  sqlite3BtreeEnter(p);
51596  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
51597  sqlite3BtreeLeave(p);
51598  return n;
51599}
51600
51601/*
51602** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
51603** then make no changes.  Always return the value of the BTS_SECURE_DELETE
51604** setting after the change.
51605*/
51606SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
51607  int b;
51608  if( p==0 ) return 0;
51609  sqlite3BtreeEnter(p);
51610  if( newFlag>=0 ){
51611    p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
51612    if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
51613  }
51614  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
51615  sqlite3BtreeLeave(p);
51616  return b;
51617}
51618#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
51619
51620/*
51621** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
51622** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
51623** is disabled. The default value for the auto-vacuum property is
51624** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
51625*/
51626SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
51627#ifdef SQLITE_OMIT_AUTOVACUUM
51628  return SQLITE_READONLY;
51629#else
51630  BtShared *pBt = p->pBt;
51631  int rc = SQLITE_OK;
51632  u8 av = (u8)autoVacuum;
51633
51634  sqlite3BtreeEnter(p);
51635  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
51636    rc = SQLITE_READONLY;
51637  }else{
51638    pBt->autoVacuum = av ?1:0;
51639    pBt->incrVacuum = av==2 ?1:0;
51640  }
51641  sqlite3BtreeLeave(p);
51642  return rc;
51643#endif
51644}
51645
51646/*
51647** Return the value of the 'auto-vacuum' property. If auto-vacuum is
51648** enabled 1 is returned. Otherwise 0.
51649*/
51650SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
51651#ifdef SQLITE_OMIT_AUTOVACUUM
51652  return BTREE_AUTOVACUUM_NONE;
51653#else
51654  int rc;
51655  sqlite3BtreeEnter(p);
51656  rc = (
51657    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
51658    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
51659    BTREE_AUTOVACUUM_INCR
51660  );
51661  sqlite3BtreeLeave(p);
51662  return rc;
51663#endif
51664}
51665
51666
51667/*
51668** Get a reference to pPage1 of the database file.  This will
51669** also acquire a readlock on that file.
51670**
51671** SQLITE_OK is returned on success.  If the file is not a
51672** well-formed database file, then SQLITE_CORRUPT is returned.
51673** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
51674** is returned if we run out of memory.
51675*/
51676static int lockBtree(BtShared *pBt){
51677  int rc;              /* Result code from subfunctions */
51678  MemPage *pPage1;     /* Page 1 of the database file */
51679  int nPage;           /* Number of pages in the database */
51680  int nPageFile = 0;   /* Number of pages in the database file */
51681  int nPageHeader;     /* Number of pages in the database according to hdr */
51682
51683  assert( sqlite3_mutex_held(pBt->mutex) );
51684  assert( pBt->pPage1==0 );
51685  rc = sqlite3PagerSharedLock(pBt->pPager);
51686  if( rc!=SQLITE_OK ) return rc;
51687  rc = btreeGetPage(pBt, 1, &pPage1, 0);
51688  if( rc!=SQLITE_OK ) return rc;
51689
51690  /* Do some checking to help insure the file we opened really is
51691  ** a valid database file.
51692  */
51693  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
51694  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
51695  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
51696    nPage = nPageFile;
51697  }
51698  if( nPage>0 ){
51699    u32 pageSize;
51700    u32 usableSize;
51701    u8 *page1 = pPage1->aData;
51702    rc = SQLITE_NOTADB;
51703    if( memcmp(page1, zMagicHeader, 16)!=0 ){
51704      goto page1_init_failed;
51705    }
51706
51707#ifdef SQLITE_OMIT_WAL
51708    if( page1[18]>1 ){
51709      pBt->btsFlags |= BTS_READ_ONLY;
51710    }
51711    if( page1[19]>1 ){
51712      goto page1_init_failed;
51713    }
51714#else
51715    if( page1[18]>2 ){
51716      pBt->btsFlags |= BTS_READ_ONLY;
51717    }
51718    if( page1[19]>2 ){
51719      goto page1_init_failed;
51720    }
51721
51722    /* If the write version is set to 2, this database should be accessed
51723    ** in WAL mode. If the log is not already open, open it now. Then
51724    ** return SQLITE_OK and return without populating BtShared.pPage1.
51725    ** The caller detects this and calls this function again. This is
51726    ** required as the version of page 1 currently in the page1 buffer
51727    ** may not be the latest version - there may be a newer one in the log
51728    ** file.
51729    */
51730    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
51731      int isOpen = 0;
51732      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
51733      if( rc!=SQLITE_OK ){
51734        goto page1_init_failed;
51735      }else if( isOpen==0 ){
51736        releasePage(pPage1);
51737        return SQLITE_OK;
51738      }
51739      rc = SQLITE_NOTADB;
51740    }
51741#endif
51742
51743    /* The maximum embedded fraction must be exactly 25%.  And the minimum
51744    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
51745    ** The original design allowed these amounts to vary, but as of
51746    ** version 3.6.0, we require them to be fixed.
51747    */
51748    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
51749      goto page1_init_failed;
51750    }
51751    pageSize = (page1[16]<<8) | (page1[17]<<16);
51752    if( ((pageSize-1)&pageSize)!=0
51753     || pageSize>SQLITE_MAX_PAGE_SIZE
51754     || pageSize<=256
51755    ){
51756      goto page1_init_failed;
51757    }
51758    assert( (pageSize & 7)==0 );
51759    usableSize = pageSize - page1[20];
51760    if( (u32)pageSize!=pBt->pageSize ){
51761      /* After reading the first page of the database assuming a page size
51762      ** of BtShared.pageSize, we have discovered that the page-size is
51763      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
51764      ** zero and return SQLITE_OK. The caller will call this function
51765      ** again with the correct page-size.
51766      */
51767      releasePage(pPage1);
51768      pBt->usableSize = usableSize;
51769      pBt->pageSize = pageSize;
51770      freeTempSpace(pBt);
51771      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
51772                                   pageSize-usableSize);
51773      return rc;
51774    }
51775    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
51776      rc = SQLITE_CORRUPT_BKPT;
51777      goto page1_init_failed;
51778    }
51779    if( usableSize<480 ){
51780      goto page1_init_failed;
51781    }
51782    pBt->pageSize = pageSize;
51783    pBt->usableSize = usableSize;
51784#ifndef SQLITE_OMIT_AUTOVACUUM
51785    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
51786    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
51787#endif
51788  }
51789
51790  /* maxLocal is the maximum amount of payload to store locally for
51791  ** a cell.  Make sure it is small enough so that at least minFanout
51792  ** cells can will fit on one page.  We assume a 10-byte page header.
51793  ** Besides the payload, the cell must store:
51794  **     2-byte pointer to the cell
51795  **     4-byte child pointer
51796  **     9-byte nKey value
51797  **     4-byte nData value
51798  **     4-byte overflow page pointer
51799  ** So a cell consists of a 2-byte pointer, a header which is as much as
51800  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
51801  ** page pointer.
51802  */
51803  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
51804  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
51805  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
51806  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
51807  if( pBt->maxLocal>127 ){
51808    pBt->max1bytePayload = 127;
51809  }else{
51810    pBt->max1bytePayload = (u8)pBt->maxLocal;
51811  }
51812  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
51813  pBt->pPage1 = pPage1;
51814  pBt->nPage = nPage;
51815  return SQLITE_OK;
51816
51817page1_init_failed:
51818  releasePage(pPage1);
51819  pBt->pPage1 = 0;
51820  return rc;
51821}
51822
51823/*
51824** If there are no outstanding cursors and we are not in the middle
51825** of a transaction but there is a read lock on the database, then
51826** this routine unrefs the first page of the database file which
51827** has the effect of releasing the read lock.
51828**
51829** If there is a transaction in progress, this routine is a no-op.
51830*/
51831static void unlockBtreeIfUnused(BtShared *pBt){
51832  assert( sqlite3_mutex_held(pBt->mutex) );
51833  assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
51834  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
51835    assert( pBt->pPage1->aData );
51836    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
51837    assert( pBt->pPage1->aData );
51838    releasePage(pBt->pPage1);
51839    pBt->pPage1 = 0;
51840  }
51841}
51842
51843/*
51844** If pBt points to an empty file then convert that empty file
51845** into a new empty database by initializing the first page of
51846** the database.
51847*/
51848static int newDatabase(BtShared *pBt){
51849  MemPage *pP1;
51850  unsigned char *data;
51851  int rc;
51852
51853  assert( sqlite3_mutex_held(pBt->mutex) );
51854  if( pBt->nPage>0 ){
51855    return SQLITE_OK;
51856  }
51857  pP1 = pBt->pPage1;
51858  assert( pP1!=0 );
51859  data = pP1->aData;
51860  rc = sqlite3PagerWrite(pP1->pDbPage);
51861  if( rc ) return rc;
51862  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
51863  assert( sizeof(zMagicHeader)==16 );
51864  data[16] = (u8)((pBt->pageSize>>8)&0xff);
51865  data[17] = (u8)((pBt->pageSize>>16)&0xff);
51866  data[18] = 1;
51867  data[19] = 1;
51868  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
51869  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
51870  data[21] = 64;
51871  data[22] = 32;
51872  data[23] = 32;
51873  memset(&data[24], 0, 100-24);
51874  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
51875  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51876#ifndef SQLITE_OMIT_AUTOVACUUM
51877  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
51878  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
51879  put4byte(&data[36 + 4*4], pBt->autoVacuum);
51880  put4byte(&data[36 + 7*4], pBt->incrVacuum);
51881#endif
51882  pBt->nPage = 1;
51883  data[31] = 1;
51884  return SQLITE_OK;
51885}
51886
51887/*
51888** Attempt to start a new transaction. A write-transaction
51889** is started if the second argument is nonzero, otherwise a read-
51890** transaction.  If the second argument is 2 or more and exclusive
51891** transaction is started, meaning that no other process is allowed
51892** to access the database.  A preexisting transaction may not be
51893** upgraded to exclusive by calling this routine a second time - the
51894** exclusivity flag only works for a new transaction.
51895**
51896** A write-transaction must be started before attempting any
51897** changes to the database.  None of the following routines
51898** will work unless a transaction is started first:
51899**
51900**      sqlite3BtreeCreateTable()
51901**      sqlite3BtreeCreateIndex()
51902**      sqlite3BtreeClearTable()
51903**      sqlite3BtreeDropTable()
51904**      sqlite3BtreeInsert()
51905**      sqlite3BtreeDelete()
51906**      sqlite3BtreeUpdateMeta()
51907**
51908** If an initial attempt to acquire the lock fails because of lock contention
51909** and the database was previously unlocked, then invoke the busy handler
51910** if there is one.  But if there was previously a read-lock, do not
51911** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
51912** returned when there is already a read-lock in order to avoid a deadlock.
51913**
51914** Suppose there are two processes A and B.  A has a read lock and B has
51915** a reserved lock.  B tries to promote to exclusive but is blocked because
51916** of A's read lock.  A tries to promote to reserved but is blocked by B.
51917** One or the other of the two processes must give way or there can be
51918** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
51919** when A already has a read lock, we encourage A to give up and let B
51920** proceed.
51921*/
51922SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
51923  sqlite3 *pBlock = 0;
51924  BtShared *pBt = p->pBt;
51925  int rc = SQLITE_OK;
51926
51927  sqlite3BtreeEnter(p);
51928  btreeIntegrity(p);
51929
51930  /* If the btree is already in a write-transaction, or it
51931  ** is already in a read-transaction and a read-transaction
51932  ** is requested, this is a no-op.
51933  */
51934  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
51935    goto trans_begun;
51936  }
51937
51938  /* Write transactions are not possible on a read-only database */
51939  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
51940    rc = SQLITE_READONLY;
51941    goto trans_begun;
51942  }
51943
51944#ifndef SQLITE_OMIT_SHARED_CACHE
51945  /* If another database handle has already opened a write transaction
51946  ** on this shared-btree structure and a second write transaction is
51947  ** requested, return SQLITE_LOCKED.
51948  */
51949  if( (wrflag && pBt->inTransaction==TRANS_WRITE)
51950   || (pBt->btsFlags & BTS_PENDING)!=0
51951  ){
51952    pBlock = pBt->pWriter->db;
51953  }else if( wrflag>1 ){
51954    BtLock *pIter;
51955    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
51956      if( pIter->pBtree!=p ){
51957        pBlock = pIter->pBtree->db;
51958        break;
51959      }
51960    }
51961  }
51962  if( pBlock ){
51963    sqlite3ConnectionBlocked(p->db, pBlock);
51964    rc = SQLITE_LOCKED_SHAREDCACHE;
51965    goto trans_begun;
51966  }
51967#endif
51968
51969  /* Any read-only or read-write transaction implies a read-lock on
51970  ** page 1. So if some other shared-cache client already has a write-lock
51971  ** on page 1, the transaction cannot be opened. */
51972  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
51973  if( SQLITE_OK!=rc ) goto trans_begun;
51974
51975  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
51976  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
51977  do {
51978    /* Call lockBtree() until either pBt->pPage1 is populated or
51979    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
51980    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
51981    ** reading page 1 it discovers that the page-size of the database
51982    ** file is not pBt->pageSize. In this case lockBtree() will update
51983    ** pBt->pageSize to the page-size of the file on disk.
51984    */
51985    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
51986
51987    if( rc==SQLITE_OK && wrflag ){
51988      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
51989        rc = SQLITE_READONLY;
51990      }else{
51991        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
51992        if( rc==SQLITE_OK ){
51993          rc = newDatabase(pBt);
51994        }
51995      }
51996    }
51997
51998    if( rc!=SQLITE_OK ){
51999      unlockBtreeIfUnused(pBt);
52000    }
52001  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
52002          btreeInvokeBusyHandler(pBt) );
52003
52004  if( rc==SQLITE_OK ){
52005    if( p->inTrans==TRANS_NONE ){
52006      pBt->nTransaction++;
52007#ifndef SQLITE_OMIT_SHARED_CACHE
52008      if( p->sharable ){
52009	assert( p->lock.pBtree==p && p->lock.iTable==1 );
52010        p->lock.eLock = READ_LOCK;
52011        p->lock.pNext = pBt->pLock;
52012        pBt->pLock = &p->lock;
52013      }
52014#endif
52015    }
52016    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
52017    if( p->inTrans>pBt->inTransaction ){
52018      pBt->inTransaction = p->inTrans;
52019    }
52020    if( wrflag ){
52021      MemPage *pPage1 = pBt->pPage1;
52022#ifndef SQLITE_OMIT_SHARED_CACHE
52023      assert( !pBt->pWriter );
52024      pBt->pWriter = p;
52025      pBt->btsFlags &= ~BTS_EXCLUSIVE;
52026      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
52027#endif
52028
52029      /* If the db-size header field is incorrect (as it may be if an old
52030      ** client has been writing the database file), update it now. Doing
52031      ** this sooner rather than later means the database size can safely
52032      ** re-read the database size from page 1 if a savepoint or transaction
52033      ** rollback occurs within the transaction.
52034      */
52035      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
52036        rc = sqlite3PagerWrite(pPage1->pDbPage);
52037        if( rc==SQLITE_OK ){
52038          put4byte(&pPage1->aData[28], pBt->nPage);
52039        }
52040      }
52041    }
52042  }
52043
52044
52045trans_begun:
52046  if( rc==SQLITE_OK && wrflag ){
52047    /* This call makes sure that the pager has the correct number of
52048    ** open savepoints. If the second parameter is greater than 0 and
52049    ** the sub-journal is not already open, then it will be opened here.
52050    */
52051    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
52052  }
52053
52054  btreeIntegrity(p);
52055  sqlite3BtreeLeave(p);
52056  return rc;
52057}
52058
52059#ifndef SQLITE_OMIT_AUTOVACUUM
52060
52061/*
52062** Set the pointer-map entries for all children of page pPage. Also, if
52063** pPage contains cells that point to overflow pages, set the pointer
52064** map entries for the overflow pages as well.
52065*/
52066static int setChildPtrmaps(MemPage *pPage){
52067  int i;                             /* Counter variable */
52068  int nCell;                         /* Number of cells in page pPage */
52069  int rc;                            /* Return code */
52070  BtShared *pBt = pPage->pBt;
52071  u8 isInitOrig = pPage->isInit;
52072  Pgno pgno = pPage->pgno;
52073
52074  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52075  rc = btreeInitPage(pPage);
52076  if( rc!=SQLITE_OK ){
52077    goto set_child_ptrmaps_out;
52078  }
52079  nCell = pPage->nCell;
52080
52081  for(i=0; i<nCell; i++){
52082    u8 *pCell = findCell(pPage, i);
52083
52084    ptrmapPutOvflPtr(pPage, pCell, &rc);
52085
52086    if( !pPage->leaf ){
52087      Pgno childPgno = get4byte(pCell);
52088      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52089    }
52090  }
52091
52092  if( !pPage->leaf ){
52093    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52094    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52095  }
52096
52097set_child_ptrmaps_out:
52098  pPage->isInit = isInitOrig;
52099  return rc;
52100}
52101
52102/*
52103** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
52104** that it points to iTo. Parameter eType describes the type of pointer to
52105** be modified, as  follows:
52106**
52107** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
52108**                   page of pPage.
52109**
52110** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
52111**                   page pointed to by one of the cells on pPage.
52112**
52113** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
52114**                   overflow page in the list.
52115*/
52116static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
52117  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52118  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52119  if( eType==PTRMAP_OVERFLOW2 ){
52120    /* The pointer is always the first 4 bytes of the page in this case.  */
52121    if( get4byte(pPage->aData)!=iFrom ){
52122      return SQLITE_CORRUPT_BKPT;
52123    }
52124    put4byte(pPage->aData, iTo);
52125  }else{
52126    u8 isInitOrig = pPage->isInit;
52127    int i;
52128    int nCell;
52129
52130    btreeInitPage(pPage);
52131    nCell = pPage->nCell;
52132
52133    for(i=0; i<nCell; i++){
52134      u8 *pCell = findCell(pPage, i);
52135      if( eType==PTRMAP_OVERFLOW1 ){
52136        CellInfo info;
52137        btreeParseCellPtr(pPage, pCell, &info);
52138        if( info.iOverflow
52139         && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
52140         && iFrom==get4byte(&pCell[info.iOverflow])
52141        ){
52142          put4byte(&pCell[info.iOverflow], iTo);
52143          break;
52144        }
52145      }else{
52146        if( get4byte(pCell)==iFrom ){
52147          put4byte(pCell, iTo);
52148          break;
52149        }
52150      }
52151    }
52152
52153    if( i==nCell ){
52154      if( eType!=PTRMAP_BTREE ||
52155          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
52156        return SQLITE_CORRUPT_BKPT;
52157      }
52158      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
52159    }
52160
52161    pPage->isInit = isInitOrig;
52162  }
52163  return SQLITE_OK;
52164}
52165
52166
52167/*
52168** Move the open database page pDbPage to location iFreePage in the
52169** database. The pDbPage reference remains valid.
52170**
52171** The isCommit flag indicates that there is no need to remember that
52172** the journal needs to be sync()ed before database page pDbPage->pgno
52173** can be written to. The caller has already promised not to write to that
52174** page.
52175*/
52176static int relocatePage(
52177  BtShared *pBt,           /* Btree */
52178  MemPage *pDbPage,        /* Open page to move */
52179  u8 eType,                /* Pointer map 'type' entry for pDbPage */
52180  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
52181  Pgno iFreePage,          /* The location to move pDbPage to */
52182  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
52183){
52184  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
52185  Pgno iDbPage = pDbPage->pgno;
52186  Pager *pPager = pBt->pPager;
52187  int rc;
52188
52189  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
52190      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
52191  assert( sqlite3_mutex_held(pBt->mutex) );
52192  assert( pDbPage->pBt==pBt );
52193
52194  /* Move page iDbPage from its current location to page number iFreePage */
52195  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
52196      iDbPage, iFreePage, iPtrPage, eType));
52197  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
52198  if( rc!=SQLITE_OK ){
52199    return rc;
52200  }
52201  pDbPage->pgno = iFreePage;
52202
52203  /* If pDbPage was a btree-page, then it may have child pages and/or cells
52204  ** that point to overflow pages. The pointer map entries for all these
52205  ** pages need to be changed.
52206  **
52207  ** If pDbPage is an overflow page, then the first 4 bytes may store a
52208  ** pointer to a subsequent overflow page. If this is the case, then
52209  ** the pointer map needs to be updated for the subsequent overflow page.
52210  */
52211  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
52212    rc = setChildPtrmaps(pDbPage);
52213    if( rc!=SQLITE_OK ){
52214      return rc;
52215    }
52216  }else{
52217    Pgno nextOvfl = get4byte(pDbPage->aData);
52218    if( nextOvfl!=0 ){
52219      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
52220      if( rc!=SQLITE_OK ){
52221        return rc;
52222      }
52223    }
52224  }
52225
52226  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
52227  ** that it points at iFreePage. Also fix the pointer map entry for
52228  ** iPtrPage.
52229  */
52230  if( eType!=PTRMAP_ROOTPAGE ){
52231    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
52232    if( rc!=SQLITE_OK ){
52233      return rc;
52234    }
52235    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
52236    if( rc!=SQLITE_OK ){
52237      releasePage(pPtrPage);
52238      return rc;
52239    }
52240    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
52241    releasePage(pPtrPage);
52242    if( rc==SQLITE_OK ){
52243      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
52244    }
52245  }
52246  return rc;
52247}
52248
52249/* Forward declaration required by incrVacuumStep(). */
52250static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
52251
52252/*
52253** Perform a single step of an incremental-vacuum. If successful,
52254** return SQLITE_OK. If there is no work to do (and therefore no
52255** point in calling this function again), return SQLITE_DONE.
52256**
52257** More specificly, this function attempts to re-organize the
52258** database so that the last page of the file currently in use
52259** is no longer in use.
52260**
52261** If the nFin parameter is non-zero, this function assumes
52262** that the caller will keep calling incrVacuumStep() until
52263** it returns SQLITE_DONE or an error, and that nFin is the
52264** number of pages the database file will contain after this
52265** process is complete.  If nFin is zero, it is assumed that
52266** incrVacuumStep() will be called a finite amount of times
52267** which may or may not empty the freelist.  A full autovacuum
52268** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
52269*/
52270static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
52271  Pgno nFreeList;           /* Number of pages still on the free-list */
52272  int rc;
52273
52274  assert( sqlite3_mutex_held(pBt->mutex) );
52275  assert( iLastPg>nFin );
52276
52277  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
52278    u8 eType;
52279    Pgno iPtrPage;
52280
52281    nFreeList = get4byte(&pBt->pPage1->aData[36]);
52282    if( nFreeList==0 ){
52283      return SQLITE_DONE;
52284    }
52285
52286    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
52287    if( rc!=SQLITE_OK ){
52288      return rc;
52289    }
52290    if( eType==PTRMAP_ROOTPAGE ){
52291      return SQLITE_CORRUPT_BKPT;
52292    }
52293
52294    if( eType==PTRMAP_FREEPAGE ){
52295      if( nFin==0 ){
52296        /* Remove the page from the files free-list. This is not required
52297        ** if nFin is non-zero. In that case, the free-list will be
52298        ** truncated to zero after this function returns, so it doesn't
52299        ** matter if it still contains some garbage entries.
52300        */
52301        Pgno iFreePg;
52302        MemPage *pFreePg;
52303        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
52304        if( rc!=SQLITE_OK ){
52305          return rc;
52306        }
52307        assert( iFreePg==iLastPg );
52308        releasePage(pFreePg);
52309      }
52310    } else {
52311      Pgno iFreePg;             /* Index of free page to move pLastPg to */
52312      MemPage *pLastPg;
52313
52314      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
52315      if( rc!=SQLITE_OK ){
52316        return rc;
52317      }
52318
52319      /* If nFin is zero, this loop runs exactly once and page pLastPg
52320      ** is swapped with the first free page pulled off the free list.
52321      **
52322      ** On the other hand, if nFin is greater than zero, then keep
52323      ** looping until a free-page located within the first nFin pages
52324      ** of the file is found.
52325      */
52326      do {
52327        MemPage *pFreePg;
52328        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
52329        if( rc!=SQLITE_OK ){
52330          releasePage(pLastPg);
52331          return rc;
52332        }
52333        releasePage(pFreePg);
52334      }while( nFin!=0 && iFreePg>nFin );
52335      assert( iFreePg<iLastPg );
52336
52337      rc = sqlite3PagerWrite(pLastPg->pDbPage);
52338      if( rc==SQLITE_OK ){
52339        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
52340      }
52341      releasePage(pLastPg);
52342      if( rc!=SQLITE_OK ){
52343        return rc;
52344      }
52345    }
52346  }
52347
52348  if( nFin==0 ){
52349    iLastPg--;
52350    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
52351      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
52352        MemPage *pPg;
52353        rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
52354        if( rc!=SQLITE_OK ){
52355          return rc;
52356        }
52357        rc = sqlite3PagerWrite(pPg->pDbPage);
52358        releasePage(pPg);
52359        if( rc!=SQLITE_OK ){
52360          return rc;
52361        }
52362      }
52363      iLastPg--;
52364    }
52365    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
52366    pBt->nPage = iLastPg;
52367  }
52368  return SQLITE_OK;
52369}
52370
52371/*
52372** A write-transaction must be opened before calling this function.
52373** It performs a single unit of work towards an incremental vacuum.
52374**
52375** If the incremental vacuum is finished after this function has run,
52376** SQLITE_DONE is returned. If it is not finished, but no error occurred,
52377** SQLITE_OK is returned. Otherwise an SQLite error code.
52378*/
52379SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
52380  int rc;
52381  BtShared *pBt = p->pBt;
52382
52383  sqlite3BtreeEnter(p);
52384  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
52385  if( !pBt->autoVacuum ){
52386    rc = SQLITE_DONE;
52387  }else{
52388    invalidateAllOverflowCache(pBt);
52389    rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
52390    if( rc==SQLITE_OK ){
52391      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52392      put4byte(&pBt->pPage1->aData[28], pBt->nPage);
52393    }
52394  }
52395  sqlite3BtreeLeave(p);
52396  return rc;
52397}
52398
52399/*
52400** This routine is called prior to sqlite3PagerCommit when a transaction
52401** is commited for an auto-vacuum database.
52402**
52403** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
52404** the database file should be truncated to during the commit process.
52405** i.e. the database has been reorganized so that only the first *pnTrunc
52406** pages are in use.
52407*/
52408static int autoVacuumCommit(BtShared *pBt){
52409  int rc = SQLITE_OK;
52410  Pager *pPager = pBt->pPager;
52411  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
52412
52413  assert( sqlite3_mutex_held(pBt->mutex) );
52414  invalidateAllOverflowCache(pBt);
52415  assert(pBt->autoVacuum);
52416  if( !pBt->incrVacuum ){
52417    Pgno nFin;         /* Number of pages in database after autovacuuming */
52418    Pgno nFree;        /* Number of pages on the freelist initially */
52419    Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
52420    Pgno iFree;        /* The next page to be freed */
52421    int nEntry;        /* Number of entries on one ptrmap page */
52422    Pgno nOrig;        /* Database size before freeing */
52423
52424    nOrig = btreePagecount(pBt);
52425    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
52426      /* It is not possible to create a database for which the final page
52427      ** is either a pointer-map page or the pending-byte page. If one
52428      ** is encountered, this indicates corruption.
52429      */
52430      return SQLITE_CORRUPT_BKPT;
52431    }
52432
52433    nFree = get4byte(&pBt->pPage1->aData[36]);
52434    nEntry = pBt->usableSize/5;
52435    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
52436    nFin = nOrig - nFree - nPtrmap;
52437    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
52438      nFin--;
52439    }
52440    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
52441      nFin--;
52442    }
52443    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
52444
52445    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
52446      rc = incrVacuumStep(pBt, nFin, iFree);
52447    }
52448    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
52449      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52450      put4byte(&pBt->pPage1->aData[32], 0);
52451      put4byte(&pBt->pPage1->aData[36], 0);
52452      put4byte(&pBt->pPage1->aData[28], nFin);
52453      sqlite3PagerTruncateImage(pBt->pPager, nFin);
52454      pBt->nPage = nFin;
52455    }
52456    if( rc!=SQLITE_OK ){
52457      sqlite3PagerRollback(pPager);
52458    }
52459  }
52460
52461  assert( nRef==sqlite3PagerRefcount(pPager) );
52462  return rc;
52463}
52464
52465#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
52466# define setChildPtrmaps(x) SQLITE_OK
52467#endif
52468
52469/*
52470** This routine does the first phase of a two-phase commit.  This routine
52471** causes a rollback journal to be created (if it does not already exist)
52472** and populated with enough information so that if a power loss occurs
52473** the database can be restored to its original state by playing back
52474** the journal.  Then the contents of the journal are flushed out to
52475** the disk.  After the journal is safely on oxide, the changes to the
52476** database are written into the database file and flushed to oxide.
52477** At the end of this call, the rollback journal still exists on the
52478** disk and we are still holding all locks, so the transaction has not
52479** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
52480** commit process.
52481**
52482** This call is a no-op if no write-transaction is currently active on pBt.
52483**
52484** Otherwise, sync the database file for the btree pBt. zMaster points to
52485** the name of a master journal file that should be written into the
52486** individual journal file, or is NULL, indicating no master journal file
52487** (single database transaction).
52488**
52489** When this is called, the master journal should already have been
52490** created, populated with this journal pointer and synced to disk.
52491**
52492** Once this is routine has returned, the only thing required to commit
52493** the write-transaction for this database file is to delete the journal.
52494*/
52495SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
52496  int rc = SQLITE_OK;
52497  if( p->inTrans==TRANS_WRITE ){
52498    BtShared *pBt = p->pBt;
52499    sqlite3BtreeEnter(p);
52500#ifndef SQLITE_OMIT_AUTOVACUUM
52501    if( pBt->autoVacuum ){
52502      rc = autoVacuumCommit(pBt);
52503      if( rc!=SQLITE_OK ){
52504        sqlite3BtreeLeave(p);
52505        return rc;
52506      }
52507    }
52508#endif
52509    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
52510    sqlite3BtreeLeave(p);
52511  }
52512  return rc;
52513}
52514
52515/*
52516** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
52517** at the conclusion of a transaction.
52518*/
52519static void btreeEndTransaction(Btree *p){
52520  BtShared *pBt = p->pBt;
52521  assert( sqlite3BtreeHoldsMutex(p) );
52522
52523  btreeClearHasContent(pBt);
52524  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
52525    /* If there are other active statements that belong to this database
52526    ** handle, downgrade to a read-only transaction. The other statements
52527    ** may still be reading from the database.  */
52528    downgradeAllSharedCacheTableLocks(p);
52529    p->inTrans = TRANS_READ;
52530  }else{
52531    /* If the handle had any kind of transaction open, decrement the
52532    ** transaction count of the shared btree. If the transaction count
52533    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
52534    ** call below will unlock the pager.  */
52535    if( p->inTrans!=TRANS_NONE ){
52536      clearAllSharedCacheTableLocks(p);
52537      pBt->nTransaction--;
52538      if( 0==pBt->nTransaction ){
52539        pBt->inTransaction = TRANS_NONE;
52540      }
52541    }
52542
52543    /* Set the current transaction state to TRANS_NONE and unlock the
52544    ** pager if this call closed the only read or write transaction.  */
52545    p->inTrans = TRANS_NONE;
52546    unlockBtreeIfUnused(pBt);
52547  }
52548
52549  btreeIntegrity(p);
52550}
52551
52552/*
52553** Commit the transaction currently in progress.
52554**
52555** This routine implements the second phase of a 2-phase commit.  The
52556** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
52557** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
52558** routine did all the work of writing information out to disk and flushing the
52559** contents so that they are written onto the disk platter.  All this
52560** routine has to do is delete or truncate or zero the header in the
52561** the rollback journal (which causes the transaction to commit) and
52562** drop locks.
52563**
52564** Normally, if an error occurs while the pager layer is attempting to
52565** finalize the underlying journal file, this function returns an error and
52566** the upper layer will attempt a rollback. However, if the second argument
52567** is non-zero then this b-tree transaction is part of a multi-file
52568** transaction. In this case, the transaction has already been committed
52569** (by deleting a master journal file) and the caller will ignore this
52570** functions return code. So, even if an error occurs in the pager layer,
52571** reset the b-tree objects internal state to indicate that the write
52572** transaction has been closed. This is quite safe, as the pager will have
52573** transitioned to the error state.
52574**
52575** This will release the write lock on the database file.  If there
52576** are no active cursors, it also releases the read lock.
52577*/
52578SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
52579
52580  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
52581  sqlite3BtreeEnter(p);
52582  btreeIntegrity(p);
52583
52584  /* If the handle has a write-transaction open, commit the shared-btrees
52585  ** transaction and set the shared state to TRANS_READ.
52586  */
52587  if( p->inTrans==TRANS_WRITE ){
52588    int rc;
52589    BtShared *pBt = p->pBt;
52590    assert( pBt->inTransaction==TRANS_WRITE );
52591    assert( pBt->nTransaction>0 );
52592    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
52593    if( rc!=SQLITE_OK && bCleanup==0 ){
52594      sqlite3BtreeLeave(p);
52595      return rc;
52596    }
52597    pBt->inTransaction = TRANS_READ;
52598  }
52599
52600  btreeEndTransaction(p);
52601  sqlite3BtreeLeave(p);
52602  return SQLITE_OK;
52603}
52604
52605/*
52606** Do both phases of a commit.
52607*/
52608SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
52609  int rc;
52610  sqlite3BtreeEnter(p);
52611  rc = sqlite3BtreeCommitPhaseOne(p, 0);
52612  if( rc==SQLITE_OK ){
52613    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
52614  }
52615  sqlite3BtreeLeave(p);
52616  return rc;
52617}
52618
52619#ifndef NDEBUG
52620/*
52621** Return the number of write-cursors open on this handle. This is for use
52622** in assert() expressions, so it is only compiled if NDEBUG is not
52623** defined.
52624**
52625** For the purposes of this routine, a write-cursor is any cursor that
52626** is capable of writing to the databse.  That means the cursor was
52627** originally opened for writing and the cursor has not be disabled
52628** by having its state changed to CURSOR_FAULT.
52629*/
52630static int countWriteCursors(BtShared *pBt){
52631  BtCursor *pCur;
52632  int r = 0;
52633  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
52634    if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
52635  }
52636  return r;
52637}
52638#endif
52639
52640/*
52641** This routine sets the state to CURSOR_FAULT and the error
52642** code to errCode for every cursor on BtShared that pBtree
52643** references.
52644**
52645** Every cursor is tripped, including cursors that belong
52646** to other database connections that happen to be sharing
52647** the cache with pBtree.
52648**
52649** This routine gets called when a rollback occurs.
52650** All cursors using the same cache must be tripped
52651** to prevent them from trying to use the btree after
52652** the rollback.  The rollback may have deleted tables
52653** or moved root pages, so it is not sufficient to
52654** save the state of the cursor.  The cursor must be
52655** invalidated.
52656*/
52657SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
52658  BtCursor *p;
52659  if( pBtree==0 ) return;
52660  sqlite3BtreeEnter(pBtree);
52661  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
52662    int i;
52663    sqlite3BtreeClearCursor(p);
52664    p->eState = CURSOR_FAULT;
52665    p->skipNext = errCode;
52666    for(i=0; i<=p->iPage; i++){
52667      releasePage(p->apPage[i]);
52668      p->apPage[i] = 0;
52669    }
52670  }
52671  sqlite3BtreeLeave(pBtree);
52672}
52673
52674/*
52675** Rollback the transaction in progress.  All cursors will be
52676** invalided by this operation.  Any attempt to use a cursor
52677** that was open at the beginning of this operation will result
52678** in an error.
52679**
52680** This will release the write lock on the database file.  If there
52681** are no active cursors, it also releases the read lock.
52682*/
52683SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
52684  int rc;
52685  BtShared *pBt = p->pBt;
52686  MemPage *pPage1;
52687
52688  sqlite3BtreeEnter(p);
52689  if( tripCode==SQLITE_OK ){
52690    rc = tripCode = saveAllCursors(pBt, 0, 0);
52691  }else{
52692    rc = SQLITE_OK;
52693  }
52694  if( tripCode ){
52695    sqlite3BtreeTripAllCursors(p, tripCode);
52696  }
52697  btreeIntegrity(p);
52698
52699  if( p->inTrans==TRANS_WRITE ){
52700    int rc2;
52701
52702    assert( TRANS_WRITE==pBt->inTransaction );
52703    rc2 = sqlite3PagerRollback(pBt->pPager);
52704    if( rc2!=SQLITE_OK ){
52705      rc = rc2;
52706    }
52707
52708    /* The rollback may have destroyed the pPage1->aData value.  So
52709    ** call btreeGetPage() on page 1 again to make
52710    ** sure pPage1->aData is set correctly. */
52711    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
52712      int nPage = get4byte(28+(u8*)pPage1->aData);
52713      testcase( nPage==0 );
52714      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
52715      testcase( pBt->nPage!=nPage );
52716      pBt->nPage = nPage;
52717      releasePage(pPage1);
52718    }
52719    assert( countWriteCursors(pBt)==0 );
52720    pBt->inTransaction = TRANS_READ;
52721  }
52722
52723  btreeEndTransaction(p);
52724  sqlite3BtreeLeave(p);
52725  return rc;
52726}
52727
52728/*
52729** Start a statement subtransaction. The subtransaction can can be rolled
52730** back independently of the main transaction. You must start a transaction
52731** before starting a subtransaction. The subtransaction is ended automatically
52732** if the main transaction commits or rolls back.
52733**
52734** Statement subtransactions are used around individual SQL statements
52735** that are contained within a BEGIN...COMMIT block.  If a constraint
52736** error occurs within the statement, the effect of that one statement
52737** can be rolled back without having to rollback the entire transaction.
52738**
52739** A statement sub-transaction is implemented as an anonymous savepoint. The
52740** value passed as the second parameter is the total number of savepoints,
52741** including the new anonymous savepoint, open on the B-Tree. i.e. if there
52742** are no active savepoints and no other statement-transactions open,
52743** iStatement is 1. This anonymous savepoint can be released or rolled back
52744** using the sqlite3BtreeSavepoint() function.
52745*/
52746SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
52747  int rc;
52748  BtShared *pBt = p->pBt;
52749  sqlite3BtreeEnter(p);
52750  assert( p->inTrans==TRANS_WRITE );
52751  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
52752  assert( iStatement>0 );
52753  assert( iStatement>p->db->nSavepoint );
52754  assert( pBt->inTransaction==TRANS_WRITE );
52755  /* At the pager level, a statement transaction is a savepoint with
52756  ** an index greater than all savepoints created explicitly using
52757  ** SQL statements. It is illegal to open, release or rollback any
52758  ** such savepoints while the statement transaction savepoint is active.
52759  */
52760  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
52761  sqlite3BtreeLeave(p);
52762  return rc;
52763}
52764
52765/*
52766** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
52767** or SAVEPOINT_RELEASE. This function either releases or rolls back the
52768** savepoint identified by parameter iSavepoint, depending on the value
52769** of op.
52770**
52771** Normally, iSavepoint is greater than or equal to zero. However, if op is
52772** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
52773** contents of the entire transaction are rolled back. This is different
52774** from a normal transaction rollback, as no locks are released and the
52775** transaction remains open.
52776*/
52777SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
52778  int rc = SQLITE_OK;
52779  if( p && p->inTrans==TRANS_WRITE ){
52780    BtShared *pBt = p->pBt;
52781    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
52782    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
52783    sqlite3BtreeEnter(p);
52784    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
52785    if( rc==SQLITE_OK ){
52786      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
52787        pBt->nPage = 0;
52788      }
52789      rc = newDatabase(pBt);
52790      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
52791
52792      /* The database size was written into the offset 28 of the header
52793      ** when the transaction started, so we know that the value at offset
52794      ** 28 is nonzero. */
52795      assert( pBt->nPage>0 );
52796    }
52797    sqlite3BtreeLeave(p);
52798  }
52799  return rc;
52800}
52801
52802/*
52803** Create a new cursor for the BTree whose root is on the page
52804** iTable. If a read-only cursor is requested, it is assumed that
52805** the caller already has at least a read-only transaction open
52806** on the database already. If a write-cursor is requested, then
52807** the caller is assumed to have an open write transaction.
52808**
52809** If wrFlag==0, then the cursor can only be used for reading.
52810** If wrFlag==1, then the cursor can be used for reading or for
52811** writing if other conditions for writing are also met.  These
52812** are the conditions that must be met in order for writing to
52813** be allowed:
52814**
52815** 1:  The cursor must have been opened with wrFlag==1
52816**
52817** 2:  Other database connections that share the same pager cache
52818**     but which are not in the READ_UNCOMMITTED state may not have
52819**     cursors open with wrFlag==0 on the same table.  Otherwise
52820**     the changes made by this write cursor would be visible to
52821**     the read cursors in the other database connection.
52822**
52823** 3:  The database must be writable (not on read-only media)
52824**
52825** 4:  There must be an active transaction.
52826**
52827** No checking is done to make sure that page iTable really is the
52828** root page of a b-tree.  If it is not, then the cursor acquired
52829** will not work correctly.
52830**
52831** It is assumed that the sqlite3BtreeCursorZero() has been called
52832** on pCur to initialize the memory space prior to invoking this routine.
52833*/
52834static int btreeCursor(
52835  Btree *p,                              /* The btree */
52836  int iTable,                            /* Root page of table to open */
52837  int wrFlag,                            /* 1 to write. 0 read-only */
52838  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
52839  BtCursor *pCur                         /* Space for new cursor */
52840){
52841  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
52842
52843  assert( sqlite3BtreeHoldsMutex(p) );
52844  assert( wrFlag==0 || wrFlag==1 );
52845
52846  /* The following assert statements verify that if this is a sharable
52847  ** b-tree database, the connection is holding the required table locks,
52848  ** and that no other connection has any open cursor that conflicts with
52849  ** this lock.  */
52850  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
52851  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
52852
52853  /* Assert that the caller has opened the required transaction. */
52854  assert( p->inTrans>TRANS_NONE );
52855  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
52856  assert( pBt->pPage1 && pBt->pPage1->aData );
52857
52858  if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
52859    return SQLITE_READONLY;
52860  }
52861  if( iTable==1 && btreePagecount(pBt)==0 ){
52862    assert( wrFlag==0 );
52863    iTable = 0;
52864  }
52865
52866  /* Now that no other errors can occur, finish filling in the BtCursor
52867  ** variables and link the cursor into the BtShared list.  */
52868  pCur->pgnoRoot = (Pgno)iTable;
52869  pCur->iPage = -1;
52870  pCur->pKeyInfo = pKeyInfo;
52871  pCur->pBtree = p;
52872  pCur->pBt = pBt;
52873  pCur->wrFlag = (u8)wrFlag;
52874  pCur->pNext = pBt->pCursor;
52875  if( pCur->pNext ){
52876    pCur->pNext->pPrev = pCur;
52877  }
52878  pBt->pCursor = pCur;
52879  pCur->eState = CURSOR_INVALID;
52880  pCur->cachedRowid = 0;
52881  return SQLITE_OK;
52882}
52883SQLITE_PRIVATE int sqlite3BtreeCursor(
52884  Btree *p,                                   /* The btree */
52885  int iTable,                                 /* Root page of table to open */
52886  int wrFlag,                                 /* 1 to write. 0 read-only */
52887  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
52888  BtCursor *pCur                              /* Write new cursor here */
52889){
52890  int rc;
52891  sqlite3BtreeEnter(p);
52892  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
52893  sqlite3BtreeLeave(p);
52894  return rc;
52895}
52896
52897/*
52898** Return the size of a BtCursor object in bytes.
52899**
52900** This interfaces is needed so that users of cursors can preallocate
52901** sufficient storage to hold a cursor.  The BtCursor object is opaque
52902** to users so they cannot do the sizeof() themselves - they must call
52903** this routine.
52904*/
52905SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
52906  return ROUND8(sizeof(BtCursor));
52907}
52908
52909/*
52910** Initialize memory that will be converted into a BtCursor object.
52911**
52912** The simple approach here would be to memset() the entire object
52913** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
52914** do not need to be zeroed and they are large, so we can save a lot
52915** of run-time by skipping the initialization of those elements.
52916*/
52917SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
52918  memset(p, 0, offsetof(BtCursor, iPage));
52919}
52920
52921/*
52922** Set the cached rowid value of every cursor in the same database file
52923** as pCur and having the same root page number as pCur.  The value is
52924** set to iRowid.
52925**
52926** Only positive rowid values are considered valid for this cache.
52927** The cache is initialized to zero, indicating an invalid cache.
52928** A btree will work fine with zero or negative rowids.  We just cannot
52929** cache zero or negative rowids, which means tables that use zero or
52930** negative rowids might run a little slower.  But in practice, zero
52931** or negative rowids are very uncommon so this should not be a problem.
52932*/
52933SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
52934  BtCursor *p;
52935  for(p=pCur->pBt->pCursor; p; p=p->pNext){
52936    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
52937  }
52938  assert( pCur->cachedRowid==iRowid );
52939}
52940
52941/*
52942** Return the cached rowid for the given cursor.  A negative or zero
52943** return value indicates that the rowid cache is invalid and should be
52944** ignored.  If the rowid cache has never before been set, then a
52945** zero is returned.
52946*/
52947SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
52948  return pCur->cachedRowid;
52949}
52950
52951/*
52952** Close a cursor.  The read lock on the database file is released
52953** when the last cursor is closed.
52954*/
52955SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
52956  Btree *pBtree = pCur->pBtree;
52957  if( pBtree ){
52958    int i;
52959    BtShared *pBt = pCur->pBt;
52960    sqlite3BtreeEnter(pBtree);
52961    sqlite3BtreeClearCursor(pCur);
52962    if( pCur->pPrev ){
52963      pCur->pPrev->pNext = pCur->pNext;
52964    }else{
52965      pBt->pCursor = pCur->pNext;
52966    }
52967    if( pCur->pNext ){
52968      pCur->pNext->pPrev = pCur->pPrev;
52969    }
52970    for(i=0; i<=pCur->iPage; i++){
52971      releasePage(pCur->apPage[i]);
52972    }
52973    unlockBtreeIfUnused(pBt);
52974    invalidateOverflowCache(pCur);
52975    /* sqlite3_free(pCur); */
52976    sqlite3BtreeLeave(pBtree);
52977  }
52978  return SQLITE_OK;
52979}
52980
52981/*
52982** Make sure the BtCursor* given in the argument has a valid
52983** BtCursor.info structure.  If it is not already valid, call
52984** btreeParseCell() to fill it in.
52985**
52986** BtCursor.info is a cache of the information in the current cell.
52987** Using this cache reduces the number of calls to btreeParseCell().
52988**
52989** 2007-06-25:  There is a bug in some versions of MSVC that cause the
52990** compiler to crash when getCellInfo() is implemented as a macro.
52991** But there is a measureable speed advantage to using the macro on gcc
52992** (when less compiler optimizations like -Os or -O0 are used and the
52993** compiler is not doing agressive inlining.)  So we use a real function
52994** for MSVC and a macro for everything else.  Ticket #2457.
52995*/
52996#ifndef NDEBUG
52997  static void assertCellInfo(BtCursor *pCur){
52998    CellInfo info;
52999    int iPage = pCur->iPage;
53000    memset(&info, 0, sizeof(info));
53001    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
53002    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
53003  }
53004#else
53005  #define assertCellInfo(x)
53006#endif
53007#ifdef _MSC_VER
53008  /* Use a real function in MSVC to work around bugs in that compiler. */
53009  static void getCellInfo(BtCursor *pCur){
53010    if( pCur->info.nSize==0 ){
53011      int iPage = pCur->iPage;
53012      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
53013      pCur->validNKey = 1;
53014    }else{
53015      assertCellInfo(pCur);
53016    }
53017  }
53018#else /* if not _MSC_VER */
53019  /* Use a macro in all other compilers so that the function is inlined */
53020#define getCellInfo(pCur)                                                      \
53021  if( pCur->info.nSize==0 ){                                                   \
53022    int iPage = pCur->iPage;                                                   \
53023    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
53024    pCur->validNKey = 1;                                                       \
53025  }else{                                                                       \
53026    assertCellInfo(pCur);                                                      \
53027  }
53028#endif /* _MSC_VER */
53029
53030#ifndef NDEBUG  /* The next routine used only within assert() statements */
53031/*
53032** Return true if the given BtCursor is valid.  A valid cursor is one
53033** that is currently pointing to a row in a (non-empty) table.
53034** This is a verification routine is used only within assert() statements.
53035*/
53036SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
53037  return pCur && pCur->eState==CURSOR_VALID;
53038}
53039#endif /* NDEBUG */
53040
53041/*
53042** Set *pSize to the size of the buffer needed to hold the value of
53043** the key for the current entry.  If the cursor is not pointing
53044** to a valid entry, *pSize is set to 0.
53045**
53046** For a table with the INTKEY flag set, this routine returns the key
53047** itself, not the number of bytes in the key.
53048**
53049** The caller must position the cursor prior to invoking this routine.
53050**
53051** This routine cannot fail.  It always returns SQLITE_OK.
53052*/
53053SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
53054  assert( cursorHoldsMutex(pCur) );
53055  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
53056  if( pCur->eState!=CURSOR_VALID ){
53057    *pSize = 0;
53058  }else{
53059    getCellInfo(pCur);
53060    *pSize = pCur->info.nKey;
53061  }
53062  return SQLITE_OK;
53063}
53064
53065/*
53066** Set *pSize to the number of bytes of data in the entry the
53067** cursor currently points to.
53068**
53069** The caller must guarantee that the cursor is pointing to a non-NULL
53070** valid entry.  In other words, the calling procedure must guarantee
53071** that the cursor has Cursor.eState==CURSOR_VALID.
53072**
53073** Failure is not possible.  This function always returns SQLITE_OK.
53074** It might just as well be a procedure (returning void) but we continue
53075** to return an integer result code for historical reasons.
53076*/
53077SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
53078  assert( cursorHoldsMutex(pCur) );
53079  assert( pCur->eState==CURSOR_VALID );
53080  getCellInfo(pCur);
53081  *pSize = pCur->info.nData;
53082  return SQLITE_OK;
53083}
53084
53085/*
53086** Given the page number of an overflow page in the database (parameter
53087** ovfl), this function finds the page number of the next page in the
53088** linked list of overflow pages. If possible, it uses the auto-vacuum
53089** pointer-map data instead of reading the content of page ovfl to do so.
53090**
53091** If an error occurs an SQLite error code is returned. Otherwise:
53092**
53093** The page number of the next overflow page in the linked list is
53094** written to *pPgnoNext. If page ovfl is the last page in its linked
53095** list, *pPgnoNext is set to zero.
53096**
53097** If ppPage is not NULL, and a reference to the MemPage object corresponding
53098** to page number pOvfl was obtained, then *ppPage is set to point to that
53099** reference. It is the responsibility of the caller to call releasePage()
53100** on *ppPage to free the reference. In no reference was obtained (because
53101** the pointer-map was used to obtain the value for *pPgnoNext), then
53102** *ppPage is set to zero.
53103*/
53104static int getOverflowPage(
53105  BtShared *pBt,               /* The database file */
53106  Pgno ovfl,                   /* Current overflow page number */
53107  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
53108  Pgno *pPgnoNext              /* OUT: Next overflow page number */
53109){
53110  Pgno next = 0;
53111  MemPage *pPage = 0;
53112  int rc = SQLITE_OK;
53113
53114  assert( sqlite3_mutex_held(pBt->mutex) );
53115  assert(pPgnoNext);
53116
53117#ifndef SQLITE_OMIT_AUTOVACUUM
53118  /* Try to find the next page in the overflow list using the
53119  ** autovacuum pointer-map pages. Guess that the next page in
53120  ** the overflow list is page number (ovfl+1). If that guess turns
53121  ** out to be wrong, fall back to loading the data of page
53122  ** number ovfl to determine the next page number.
53123  */
53124  if( pBt->autoVacuum ){
53125    Pgno pgno;
53126    Pgno iGuess = ovfl+1;
53127    u8 eType;
53128
53129    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
53130      iGuess++;
53131    }
53132
53133    if( iGuess<=btreePagecount(pBt) ){
53134      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
53135      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
53136        next = iGuess;
53137        rc = SQLITE_DONE;
53138      }
53139    }
53140  }
53141#endif
53142
53143  assert( next==0 || rc==SQLITE_DONE );
53144  if( rc==SQLITE_OK ){
53145    rc = btreeGetPage(pBt, ovfl, &pPage, 0);
53146    assert( rc==SQLITE_OK || pPage==0 );
53147    if( rc==SQLITE_OK ){
53148      next = get4byte(pPage->aData);
53149    }
53150  }
53151
53152  *pPgnoNext = next;
53153  if( ppPage ){
53154    *ppPage = pPage;
53155  }else{
53156    releasePage(pPage);
53157  }
53158  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
53159}
53160
53161/*
53162** Copy data from a buffer to a page, or from a page to a buffer.
53163**
53164** pPayload is a pointer to data stored on database page pDbPage.
53165** If argument eOp is false, then nByte bytes of data are copied
53166** from pPayload to the buffer pointed at by pBuf. If eOp is true,
53167** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
53168** of data are copied from the buffer pBuf to pPayload.
53169**
53170** SQLITE_OK is returned on success, otherwise an error code.
53171*/
53172static int copyPayload(
53173  void *pPayload,           /* Pointer to page data */
53174  void *pBuf,               /* Pointer to buffer */
53175  int nByte,                /* Number of bytes to copy */
53176  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
53177  DbPage *pDbPage           /* Page containing pPayload */
53178){
53179  if( eOp ){
53180    /* Copy data from buffer to page (a write operation) */
53181    int rc = sqlite3PagerWrite(pDbPage);
53182    if( rc!=SQLITE_OK ){
53183      return rc;
53184    }
53185    memcpy(pPayload, pBuf, nByte);
53186  }else{
53187    /* Copy data from page to buffer (a read operation) */
53188    memcpy(pBuf, pPayload, nByte);
53189  }
53190  return SQLITE_OK;
53191}
53192
53193/*
53194** This function is used to read or overwrite payload information
53195** for the entry that the pCur cursor is pointing to. If the eOp
53196** parameter is 0, this is a read operation (data copied into
53197** buffer pBuf). If it is non-zero, a write (data copied from
53198** buffer pBuf).
53199**
53200** A total of "amt" bytes are read or written beginning at "offset".
53201** Data is read to or from the buffer pBuf.
53202**
53203** The content being read or written might appear on the main page
53204** or be scattered out on multiple overflow pages.
53205**
53206** If the BtCursor.isIncrblobHandle flag is set, and the current
53207** cursor entry uses one or more overflow pages, this function
53208** allocates space for and lazily popluates the overflow page-list
53209** cache array (BtCursor.aOverflow). Subsequent calls use this
53210** cache to make seeking to the supplied offset more efficient.
53211**
53212** Once an overflow page-list cache has been allocated, it may be
53213** invalidated if some other cursor writes to the same table, or if
53214** the cursor is moved to a different row. Additionally, in auto-vacuum
53215** mode, the following events may invalidate an overflow page-list cache.
53216**
53217**   * An incremental vacuum,
53218**   * A commit in auto_vacuum="full" mode,
53219**   * Creating a table (may require moving an overflow page).
53220*/
53221static int accessPayload(
53222  BtCursor *pCur,      /* Cursor pointing to entry to read from */
53223  u32 offset,          /* Begin reading this far into payload */
53224  u32 amt,             /* Read this many bytes */
53225  unsigned char *pBuf, /* Write the bytes into this buffer */
53226  int eOp              /* zero to read. non-zero to write. */
53227){
53228  unsigned char *aPayload;
53229  int rc = SQLITE_OK;
53230  u32 nKey;
53231  int iIdx = 0;
53232  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
53233  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
53234
53235  assert( pPage );
53236  assert( pCur->eState==CURSOR_VALID );
53237  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53238  assert( cursorHoldsMutex(pCur) );
53239
53240  getCellInfo(pCur);
53241  aPayload = pCur->info.pCell + pCur->info.nHeader;
53242  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
53243
53244  if( NEVER(offset+amt > nKey+pCur->info.nData)
53245   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
53246  ){
53247    /* Trying to read or write past the end of the data is an error */
53248    return SQLITE_CORRUPT_BKPT;
53249  }
53250
53251  /* Check if data must be read/written to/from the btree page itself. */
53252  if( offset<pCur->info.nLocal ){
53253    int a = amt;
53254    if( a+offset>pCur->info.nLocal ){
53255      a = pCur->info.nLocal - offset;
53256    }
53257    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
53258    offset = 0;
53259    pBuf += a;
53260    amt -= a;
53261  }else{
53262    offset -= pCur->info.nLocal;
53263  }
53264
53265  if( rc==SQLITE_OK && amt>0 ){
53266    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
53267    Pgno nextPage;
53268
53269    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
53270
53271#ifndef SQLITE_OMIT_INCRBLOB
53272    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
53273    ** has not been allocated, allocate it now. The array is sized at
53274    ** one entry for each overflow page in the overflow chain. The
53275    ** page number of the first overflow page is stored in aOverflow[0],
53276    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
53277    ** (the cache is lazily populated).
53278    */
53279    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
53280      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
53281      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
53282      /* nOvfl is always positive.  If it were zero, fetchPayload would have
53283      ** been used instead of this routine. */
53284      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
53285        rc = SQLITE_NOMEM;
53286      }
53287    }
53288
53289    /* If the overflow page-list cache has been allocated and the
53290    ** entry for the first required overflow page is valid, skip
53291    ** directly to it.
53292    */
53293    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
53294      iIdx = (offset/ovflSize);
53295      nextPage = pCur->aOverflow[iIdx];
53296      offset = (offset%ovflSize);
53297    }
53298#endif
53299
53300    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
53301
53302#ifndef SQLITE_OMIT_INCRBLOB
53303      /* If required, populate the overflow page-list cache. */
53304      if( pCur->aOverflow ){
53305        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
53306        pCur->aOverflow[iIdx] = nextPage;
53307      }
53308#endif
53309
53310      if( offset>=ovflSize ){
53311        /* The only reason to read this page is to obtain the page
53312        ** number for the next page in the overflow chain. The page
53313        ** data is not required. So first try to lookup the overflow
53314        ** page-list cache, if any, then fall back to the getOverflowPage()
53315        ** function.
53316        */
53317#ifndef SQLITE_OMIT_INCRBLOB
53318        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
53319          nextPage = pCur->aOverflow[iIdx+1];
53320        } else
53321#endif
53322          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
53323        offset -= ovflSize;
53324      }else{
53325        /* Need to read this page properly. It contains some of the
53326        ** range of data that is being read (eOp==0) or written (eOp!=0).
53327        */
53328#ifdef SQLITE_DIRECT_OVERFLOW_READ
53329        sqlite3_file *fd;
53330#endif
53331        int a = amt;
53332        if( a + offset > ovflSize ){
53333          a = ovflSize - offset;
53334        }
53335
53336#ifdef SQLITE_DIRECT_OVERFLOW_READ
53337        /* If all the following are true:
53338        **
53339        **   1) this is a read operation, and
53340        **   2) data is required from the start of this overflow page, and
53341        **   3) the database is file-backed, and
53342        **   4) there is no open write-transaction, and
53343        **   5) the database is not a WAL database,
53344        **
53345        ** then data can be read directly from the database file into the
53346        ** output buffer, bypassing the page-cache altogether. This speeds
53347        ** up loading large records that span many overflow pages.
53348        */
53349        if( eOp==0                                             /* (1) */
53350         && offset==0                                          /* (2) */
53351         && pBt->inTransaction==TRANS_READ                     /* (4) */
53352         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
53353         && pBt->pPage1->aData[19]==0x01                       /* (5) */
53354        ){
53355          u8 aSave[4];
53356          u8 *aWrite = &pBuf[-4];
53357          memcpy(aSave, aWrite, 4);
53358          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
53359          nextPage = get4byte(aWrite);
53360          memcpy(aWrite, aSave, 4);
53361        }else
53362#endif
53363
53364        {
53365          DbPage *pDbPage;
53366          rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
53367          if( rc==SQLITE_OK ){
53368            aPayload = sqlite3PagerGetData(pDbPage);
53369            nextPage = get4byte(aPayload);
53370            rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
53371            sqlite3PagerUnref(pDbPage);
53372            offset = 0;
53373          }
53374        }
53375        amt -= a;
53376        pBuf += a;
53377      }
53378    }
53379  }
53380
53381  if( rc==SQLITE_OK && amt>0 ){
53382    return SQLITE_CORRUPT_BKPT;
53383  }
53384  return rc;
53385}
53386
53387/*
53388** Read part of the key associated with cursor pCur.  Exactly
53389** "amt" bytes will be transfered into pBuf[].  The transfer
53390** begins at "offset".
53391**
53392** The caller must ensure that pCur is pointing to a valid row
53393** in the table.
53394**
53395** Return SQLITE_OK on success or an error code if anything goes
53396** wrong.  An error is returned if "offset+amt" is larger than
53397** the available payload.
53398*/
53399SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53400  assert( cursorHoldsMutex(pCur) );
53401  assert( pCur->eState==CURSOR_VALID );
53402  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53403  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53404  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
53405}
53406
53407/*
53408** Read part of the data associated with cursor pCur.  Exactly
53409** "amt" bytes will be transfered into pBuf[].  The transfer
53410** begins at "offset".
53411**
53412** Return SQLITE_OK on success or an error code if anything goes
53413** wrong.  An error is returned if "offset+amt" is larger than
53414** the available payload.
53415*/
53416SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53417  int rc;
53418
53419#ifndef SQLITE_OMIT_INCRBLOB
53420  if ( pCur->eState==CURSOR_INVALID ){
53421    return SQLITE_ABORT;
53422  }
53423#endif
53424
53425  assert( cursorHoldsMutex(pCur) );
53426  rc = restoreCursorPosition(pCur);
53427  if( rc==SQLITE_OK ){
53428    assert( pCur->eState==CURSOR_VALID );
53429    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53430    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53431    rc = accessPayload(pCur, offset, amt, pBuf, 0);
53432  }
53433  return rc;
53434}
53435
53436/*
53437** Return a pointer to payload information from the entry that the
53438** pCur cursor is pointing to.  The pointer is to the beginning of
53439** the key if skipKey==0 and it points to the beginning of data if
53440** skipKey==1.  The number of bytes of available key/data is written
53441** into *pAmt.  If *pAmt==0, then the value returned will not be
53442** a valid pointer.
53443**
53444** This routine is an optimization.  It is common for the entire key
53445** and data to fit on the local page and for there to be no overflow
53446** pages.  When that is so, this routine can be used to access the
53447** key and data without making a copy.  If the key and/or data spills
53448** onto overflow pages, then accessPayload() must be used to reassemble
53449** the key/data and copy it into a preallocated buffer.
53450**
53451** The pointer returned by this routine looks directly into the cached
53452** page of the database.  The data might change or move the next time
53453** any btree routine is called.
53454*/
53455static const unsigned char *fetchPayload(
53456  BtCursor *pCur,      /* Cursor pointing to entry to read from */
53457  int *pAmt,           /* Write the number of available bytes here */
53458  int skipKey          /* read beginning at data if this is true */
53459){
53460  unsigned char *aPayload;
53461  MemPage *pPage;
53462  u32 nKey;
53463  u32 nLocal;
53464
53465  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
53466  assert( pCur->eState==CURSOR_VALID );
53467  assert( cursorHoldsMutex(pCur) );
53468  pPage = pCur->apPage[pCur->iPage];
53469  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53470  if( NEVER(pCur->info.nSize==0) ){
53471    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
53472                   &pCur->info);
53473  }
53474  aPayload = pCur->info.pCell;
53475  aPayload += pCur->info.nHeader;
53476  if( pPage->intKey ){
53477    nKey = 0;
53478  }else{
53479    nKey = (int)pCur->info.nKey;
53480  }
53481  if( skipKey ){
53482    aPayload += nKey;
53483    nLocal = pCur->info.nLocal - nKey;
53484  }else{
53485    nLocal = pCur->info.nLocal;
53486    assert( nLocal<=nKey );
53487  }
53488  *pAmt = nLocal;
53489  return aPayload;
53490}
53491
53492
53493/*
53494** For the entry that cursor pCur is point to, return as
53495** many bytes of the key or data as are available on the local
53496** b-tree page.  Write the number of available bytes into *pAmt.
53497**
53498** The pointer returned is ephemeral.  The key/data may move
53499** or be destroyed on the next call to any Btree routine,
53500** including calls from other threads against the same cache.
53501** Hence, a mutex on the BtShared should be held prior to calling
53502** this routine.
53503**
53504** These routines is used to get quick access to key and data
53505** in the common case where no overflow pages are used.
53506*/
53507SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
53508  const void *p = 0;
53509  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53510  assert( cursorHoldsMutex(pCur) );
53511  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53512    p = (const void*)fetchPayload(pCur, pAmt, 0);
53513  }
53514  return p;
53515}
53516SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
53517  const void *p = 0;
53518  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53519  assert( cursorHoldsMutex(pCur) );
53520  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53521    p = (const void*)fetchPayload(pCur, pAmt, 1);
53522  }
53523  return p;
53524}
53525
53526
53527/*
53528** Move the cursor down to a new child page.  The newPgno argument is the
53529** page number of the child page to move to.
53530**
53531** This function returns SQLITE_CORRUPT if the page-header flags field of
53532** the new child page does not match the flags field of the parent (i.e.
53533** if an intkey page appears to be the parent of a non-intkey page, or
53534** vice-versa).
53535*/
53536static int moveToChild(BtCursor *pCur, u32 newPgno){
53537  int rc;
53538  int i = pCur->iPage;
53539  MemPage *pNewPage;
53540  BtShared *pBt = pCur->pBt;
53541
53542  assert( cursorHoldsMutex(pCur) );
53543  assert( pCur->eState==CURSOR_VALID );
53544  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
53545  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
53546    return SQLITE_CORRUPT_BKPT;
53547  }
53548  rc = getAndInitPage(pBt, newPgno, &pNewPage);
53549  if( rc ) return rc;
53550  pCur->apPage[i+1] = pNewPage;
53551  pCur->aiIdx[i+1] = 0;
53552  pCur->iPage++;
53553
53554  pCur->info.nSize = 0;
53555  pCur->validNKey = 0;
53556  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
53557    return SQLITE_CORRUPT_BKPT;
53558  }
53559  return SQLITE_OK;
53560}
53561
53562#if 0
53563/*
53564** Page pParent is an internal (non-leaf) tree page. This function
53565** asserts that page number iChild is the left-child if the iIdx'th
53566** cell in page pParent. Or, if iIdx is equal to the total number of
53567** cells in pParent, that page number iChild is the right-child of
53568** the page.
53569*/
53570static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
53571  assert( iIdx<=pParent->nCell );
53572  if( iIdx==pParent->nCell ){
53573    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
53574  }else{
53575    assert( get4byte(findCell(pParent, iIdx))==iChild );
53576  }
53577}
53578#else
53579#  define assertParentIndex(x,y,z)
53580#endif
53581
53582/*
53583** Move the cursor up to the parent page.
53584**
53585** pCur->idx is set to the cell index that contains the pointer
53586** to the page we are coming from.  If we are coming from the
53587** right-most child page then pCur->idx is set to one more than
53588** the largest cell index.
53589*/
53590static void moveToParent(BtCursor *pCur){
53591  assert( cursorHoldsMutex(pCur) );
53592  assert( pCur->eState==CURSOR_VALID );
53593  assert( pCur->iPage>0 );
53594  assert( pCur->apPage[pCur->iPage] );
53595
53596  /* UPDATE: It is actually possible for the condition tested by the assert
53597  ** below to be untrue if the database file is corrupt. This can occur if
53598  ** one cursor has modified page pParent while a reference to it is held
53599  ** by a second cursor. Which can only happen if a single page is linked
53600  ** into more than one b-tree structure in a corrupt database.  */
53601#if 0
53602  assertParentIndex(
53603    pCur->apPage[pCur->iPage-1],
53604    pCur->aiIdx[pCur->iPage-1],
53605    pCur->apPage[pCur->iPage]->pgno
53606  );
53607#endif
53608  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
53609
53610  releasePage(pCur->apPage[pCur->iPage]);
53611  pCur->iPage--;
53612  pCur->info.nSize = 0;
53613  pCur->validNKey = 0;
53614}
53615
53616/*
53617** Move the cursor to point to the root page of its b-tree structure.
53618**
53619** If the table has a virtual root page, then the cursor is moved to point
53620** to the virtual root page instead of the actual root page. A table has a
53621** virtual root page when the actual root page contains no cells and a
53622** single child page. This can only happen with the table rooted at page 1.
53623**
53624** If the b-tree structure is empty, the cursor state is set to
53625** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
53626** cell located on the root (or virtual root) page and the cursor state
53627** is set to CURSOR_VALID.
53628**
53629** If this function returns successfully, it may be assumed that the
53630** page-header flags indicate that the [virtual] root-page is the expected
53631** kind of b-tree page (i.e. if when opening the cursor the caller did not
53632** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
53633** indicating a table b-tree, or if the caller did specify a KeyInfo
53634** structure the flags byte is set to 0x02 or 0x0A, indicating an index
53635** b-tree).
53636*/
53637static int moveToRoot(BtCursor *pCur){
53638  MemPage *pRoot;
53639  int rc = SQLITE_OK;
53640  Btree *p = pCur->pBtree;
53641  BtShared *pBt = p->pBt;
53642
53643  assert( cursorHoldsMutex(pCur) );
53644  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
53645  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
53646  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
53647  if( pCur->eState>=CURSOR_REQUIRESEEK ){
53648    if( pCur->eState==CURSOR_FAULT ){
53649      assert( pCur->skipNext!=SQLITE_OK );
53650      return pCur->skipNext;
53651    }
53652    sqlite3BtreeClearCursor(pCur);
53653  }
53654
53655  if( pCur->iPage>=0 ){
53656    int i;
53657    for(i=1; i<=pCur->iPage; i++){
53658      releasePage(pCur->apPage[i]);
53659    }
53660    pCur->iPage = 0;
53661  }else if( pCur->pgnoRoot==0 ){
53662    pCur->eState = CURSOR_INVALID;
53663    return SQLITE_OK;
53664  }else{
53665    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
53666    if( rc!=SQLITE_OK ){
53667      pCur->eState = CURSOR_INVALID;
53668      return rc;
53669    }
53670    pCur->iPage = 0;
53671
53672    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
53673    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
53674    ** NULL, the caller expects a table b-tree. If this is not the case,
53675    ** return an SQLITE_CORRUPT error.  */
53676    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
53677    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
53678      return SQLITE_CORRUPT_BKPT;
53679    }
53680  }
53681
53682  /* Assert that the root page is of the correct type. This must be the
53683  ** case as the call to this function that loaded the root-page (either
53684  ** this call or a previous invocation) would have detected corruption
53685  ** if the assumption were not true, and it is not possible for the flags
53686  ** byte to have been modified while this cursor is holding a reference
53687  ** to the page.  */
53688  pRoot = pCur->apPage[0];
53689  assert( pRoot->pgno==pCur->pgnoRoot );
53690  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
53691
53692  pCur->aiIdx[0] = 0;
53693  pCur->info.nSize = 0;
53694  pCur->atLast = 0;
53695  pCur->validNKey = 0;
53696
53697  if( pRoot->nCell==0 && !pRoot->leaf ){
53698    Pgno subpage;
53699    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
53700    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
53701    pCur->eState = CURSOR_VALID;
53702    rc = moveToChild(pCur, subpage);
53703  }else{
53704    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
53705  }
53706  return rc;
53707}
53708
53709/*
53710** Move the cursor down to the left-most leaf entry beneath the
53711** entry to which it is currently pointing.
53712**
53713** The left-most leaf is the one with the smallest key - the first
53714** in ascending order.
53715*/
53716static int moveToLeftmost(BtCursor *pCur){
53717  Pgno pgno;
53718  int rc = SQLITE_OK;
53719  MemPage *pPage;
53720
53721  assert( cursorHoldsMutex(pCur) );
53722  assert( pCur->eState==CURSOR_VALID );
53723  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
53724    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53725    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
53726    rc = moveToChild(pCur, pgno);
53727  }
53728  return rc;
53729}
53730
53731/*
53732** Move the cursor down to the right-most leaf entry beneath the
53733** page to which it is currently pointing.  Notice the difference
53734** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
53735** finds the left-most entry beneath the *entry* whereas moveToRightmost()
53736** finds the right-most entry beneath the *page*.
53737**
53738** The right-most entry is the one with the largest key - the last
53739** key in ascending order.
53740*/
53741static int moveToRightmost(BtCursor *pCur){
53742  Pgno pgno;
53743  int rc = SQLITE_OK;
53744  MemPage *pPage = 0;
53745
53746  assert( cursorHoldsMutex(pCur) );
53747  assert( pCur->eState==CURSOR_VALID );
53748  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
53749    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53750    pCur->aiIdx[pCur->iPage] = pPage->nCell;
53751    rc = moveToChild(pCur, pgno);
53752  }
53753  if( rc==SQLITE_OK ){
53754    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
53755    pCur->info.nSize = 0;
53756    pCur->validNKey = 0;
53757  }
53758  return rc;
53759}
53760
53761/* Move the cursor to the first entry in the table.  Return SQLITE_OK
53762** on success.  Set *pRes to 0 if the cursor actually points to something
53763** or set *pRes to 1 if the table is empty.
53764*/
53765SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
53766  int rc;
53767
53768  assert( cursorHoldsMutex(pCur) );
53769  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53770  rc = moveToRoot(pCur);
53771  if( rc==SQLITE_OK ){
53772    if( pCur->eState==CURSOR_INVALID ){
53773      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
53774      *pRes = 1;
53775    }else{
53776      assert( pCur->apPage[pCur->iPage]->nCell>0 );
53777      *pRes = 0;
53778      rc = moveToLeftmost(pCur);
53779    }
53780  }
53781  return rc;
53782}
53783
53784/* Move the cursor to the last entry in the table.  Return SQLITE_OK
53785** on success.  Set *pRes to 0 if the cursor actually points to something
53786** or set *pRes to 1 if the table is empty.
53787*/
53788SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
53789  int rc;
53790
53791  assert( cursorHoldsMutex(pCur) );
53792  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53793
53794  /* If the cursor already points to the last entry, this is a no-op. */
53795  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
53796#ifdef SQLITE_DEBUG
53797    /* This block serves to assert() that the cursor really does point
53798    ** to the last entry in the b-tree. */
53799    int ii;
53800    for(ii=0; ii<pCur->iPage; ii++){
53801      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
53802    }
53803    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
53804    assert( pCur->apPage[pCur->iPage]->leaf );
53805#endif
53806    return SQLITE_OK;
53807  }
53808
53809  rc = moveToRoot(pCur);
53810  if( rc==SQLITE_OK ){
53811    if( CURSOR_INVALID==pCur->eState ){
53812      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
53813      *pRes = 1;
53814    }else{
53815      assert( pCur->eState==CURSOR_VALID );
53816      *pRes = 0;
53817      rc = moveToRightmost(pCur);
53818      pCur->atLast = rc==SQLITE_OK ?1:0;
53819    }
53820  }
53821  return rc;
53822}
53823
53824/* Move the cursor so that it points to an entry near the key
53825** specified by pIdxKey or intKey.   Return a success code.
53826**
53827** For INTKEY tables, the intKey parameter is used.  pIdxKey
53828** must be NULL.  For index tables, pIdxKey is used and intKey
53829** is ignored.
53830**
53831** If an exact match is not found, then the cursor is always
53832** left pointing at a leaf page which would hold the entry if it
53833** were present.  The cursor might point to an entry that comes
53834** before or after the key.
53835**
53836** An integer is written into *pRes which is the result of
53837** comparing the key with the entry to which the cursor is
53838** pointing.  The meaning of the integer written into
53839** *pRes is as follows:
53840**
53841**     *pRes<0      The cursor is left pointing at an entry that
53842**                  is smaller than intKey/pIdxKey or if the table is empty
53843**                  and the cursor is therefore left point to nothing.
53844**
53845**     *pRes==0     The cursor is left pointing at an entry that
53846**                  exactly matches intKey/pIdxKey.
53847**
53848**     *pRes>0      The cursor is left pointing at an entry that
53849**                  is larger than intKey/pIdxKey.
53850**
53851*/
53852SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
53853  BtCursor *pCur,          /* The cursor to be moved */
53854  UnpackedRecord *pIdxKey, /* Unpacked index key */
53855  i64 intKey,              /* The table key */
53856  int biasRight,           /* If true, bias the search to the high end */
53857  int *pRes                /* Write search results here */
53858){
53859  int rc;
53860
53861  assert( cursorHoldsMutex(pCur) );
53862  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53863  assert( pRes );
53864  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
53865
53866  /* If the cursor is already positioned at the point we are trying
53867  ** to move to, then just return without doing any work */
53868  if( pCur->eState==CURSOR_VALID && pCur->validNKey
53869   && pCur->apPage[0]->intKey
53870  ){
53871    if( pCur->info.nKey==intKey ){
53872      *pRes = 0;
53873      return SQLITE_OK;
53874    }
53875    if( pCur->atLast && pCur->info.nKey<intKey ){
53876      *pRes = -1;
53877      return SQLITE_OK;
53878    }
53879  }
53880
53881  rc = moveToRoot(pCur);
53882  if( rc ){
53883    return rc;
53884  }
53885  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
53886  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
53887  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
53888  if( pCur->eState==CURSOR_INVALID ){
53889    *pRes = -1;
53890    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
53891    return SQLITE_OK;
53892  }
53893  assert( pCur->apPage[0]->intKey || pIdxKey );
53894  for(;;){
53895    int lwr, upr, idx;
53896    Pgno chldPg;
53897    MemPage *pPage = pCur->apPage[pCur->iPage];
53898    int c;
53899
53900    /* pPage->nCell must be greater than zero. If this is the root-page
53901    ** the cursor would have been INVALID above and this for(;;) loop
53902    ** not run. If this is not the root-page, then the moveToChild() routine
53903    ** would have already detected db corruption. Similarly, pPage must
53904    ** be the right kind (index or table) of b-tree page. Otherwise
53905    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
53906    assert( pPage->nCell>0 );
53907    assert( pPage->intKey==(pIdxKey==0) );
53908    lwr = 0;
53909    upr = pPage->nCell-1;
53910    if( biasRight ){
53911      pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
53912    }else{
53913      pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
53914    }
53915    for(;;){
53916      u8 *pCell;                          /* Pointer to current cell in pPage */
53917
53918      assert( idx==pCur->aiIdx[pCur->iPage] );
53919      pCur->info.nSize = 0;
53920      pCell = findCell(pPage, idx) + pPage->childPtrSize;
53921      if( pPage->intKey ){
53922        i64 nCellKey;
53923        if( pPage->hasData ){
53924          u32 dummy;
53925          pCell += getVarint32(pCell, dummy);
53926        }
53927        getVarint(pCell, (u64*)&nCellKey);
53928        if( nCellKey==intKey ){
53929          c = 0;
53930        }else if( nCellKey<intKey ){
53931          c = -1;
53932        }else{
53933          assert( nCellKey>intKey );
53934          c = +1;
53935        }
53936        pCur->validNKey = 1;
53937        pCur->info.nKey = nCellKey;
53938      }else{
53939        /* The maximum supported page-size is 65536 bytes. This means that
53940        ** the maximum number of record bytes stored on an index B-Tree
53941        ** page is less than 16384 bytes and may be stored as a 2-byte
53942        ** varint. This information is used to attempt to avoid parsing
53943        ** the entire cell by checking for the cases where the record is
53944        ** stored entirely within the b-tree page by inspecting the first
53945        ** 2 bytes of the cell.
53946        */
53947        int nCell = pCell[0];
53948        if( nCell<=pPage->max1bytePayload
53949         /* && (pCell+nCell)<pPage->aDataEnd */
53950        ){
53951          /* This branch runs if the record-size field of the cell is a
53952          ** single byte varint and the record fits entirely on the main
53953          ** b-tree page.  */
53954          testcase( pCell+nCell+1==pPage->aDataEnd );
53955          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
53956        }else if( !(pCell[1] & 0x80)
53957          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
53958          /* && (pCell+nCell+2)<=pPage->aDataEnd */
53959        ){
53960          /* The record-size field is a 2 byte varint and the record
53961          ** fits entirely on the main b-tree page.  */
53962          testcase( pCell+nCell+2==pPage->aDataEnd );
53963          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
53964        }else{
53965          /* The record flows over onto one or more overflow pages. In
53966          ** this case the whole cell needs to be parsed, a buffer allocated
53967          ** and accessPayload() used to retrieve the record into the
53968          ** buffer before VdbeRecordCompare() can be called. */
53969          void *pCellKey;
53970          u8 * const pCellBody = pCell - pPage->childPtrSize;
53971          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
53972          nCell = (int)pCur->info.nKey;
53973          pCellKey = sqlite3Malloc( nCell );
53974          if( pCellKey==0 ){
53975            rc = SQLITE_NOMEM;
53976            goto moveto_finish;
53977          }
53978          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
53979          if( rc ){
53980            sqlite3_free(pCellKey);
53981            goto moveto_finish;
53982          }
53983          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
53984          sqlite3_free(pCellKey);
53985        }
53986      }
53987      if( c==0 ){
53988        if( pPage->intKey && !pPage->leaf ){
53989          lwr = idx;
53990          break;
53991        }else{
53992          *pRes = 0;
53993          rc = SQLITE_OK;
53994          goto moveto_finish;
53995        }
53996      }
53997      if( c<0 ){
53998        lwr = idx+1;
53999      }else{
54000        upr = idx-1;
54001      }
54002      if( lwr>upr ){
54003        break;
54004      }
54005      pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
54006    }
54007    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
54008    assert( pPage->isInit );
54009    if( pPage->leaf ){
54010      chldPg = 0;
54011    }else if( lwr>=pPage->nCell ){
54012      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54013    }else{
54014      chldPg = get4byte(findCell(pPage, lwr));
54015    }
54016    if( chldPg==0 ){
54017      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54018      *pRes = c;
54019      rc = SQLITE_OK;
54020      goto moveto_finish;
54021    }
54022    pCur->aiIdx[pCur->iPage] = (u16)lwr;
54023    pCur->info.nSize = 0;
54024    pCur->validNKey = 0;
54025    rc = moveToChild(pCur, chldPg);
54026    if( rc ) goto moveto_finish;
54027  }
54028moveto_finish:
54029  return rc;
54030}
54031
54032
54033/*
54034** Return TRUE if the cursor is not pointing at an entry of the table.
54035**
54036** TRUE will be returned after a call to sqlite3BtreeNext() moves
54037** past the last entry in the table or sqlite3BtreePrev() moves past
54038** the first entry.  TRUE is also returned if the table is empty.
54039*/
54040SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
54041  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
54042  ** have been deleted? This API will need to change to return an error code
54043  ** as well as the boolean result value.
54044  */
54045  return (CURSOR_VALID!=pCur->eState);
54046}
54047
54048/*
54049** Advance the cursor to the next entry in the database.  If
54050** successful then set *pRes=0.  If the cursor
54051** was already pointing to the last entry in the database before
54052** this routine was called, then set *pRes=1.
54053*/
54054SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
54055  int rc;
54056  int idx;
54057  MemPage *pPage;
54058
54059  assert( cursorHoldsMutex(pCur) );
54060  rc = restoreCursorPosition(pCur);
54061  if( rc!=SQLITE_OK ){
54062    return rc;
54063  }
54064  assert( pRes!=0 );
54065  if( CURSOR_INVALID==pCur->eState ){
54066    *pRes = 1;
54067    return SQLITE_OK;
54068  }
54069  if( pCur->skipNext>0 ){
54070    pCur->skipNext = 0;
54071    *pRes = 0;
54072    return SQLITE_OK;
54073  }
54074  pCur->skipNext = 0;
54075
54076  pPage = pCur->apPage[pCur->iPage];
54077  idx = ++pCur->aiIdx[pCur->iPage];
54078  assert( pPage->isInit );
54079
54080  /* If the database file is corrupt, it is possible for the value of idx
54081  ** to be invalid here. This can only occur if a second cursor modifies
54082  ** the page while cursor pCur is holding a reference to it. Which can
54083  ** only happen if the database is corrupt in such a way as to link the
54084  ** page into more than one b-tree structure. */
54085  testcase( idx>pPage->nCell );
54086
54087  pCur->info.nSize = 0;
54088  pCur->validNKey = 0;
54089  if( idx>=pPage->nCell ){
54090    if( !pPage->leaf ){
54091      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54092      if( rc ) return rc;
54093      rc = moveToLeftmost(pCur);
54094      *pRes = 0;
54095      return rc;
54096    }
54097    do{
54098      if( pCur->iPage==0 ){
54099        *pRes = 1;
54100        pCur->eState = CURSOR_INVALID;
54101        return SQLITE_OK;
54102      }
54103      moveToParent(pCur);
54104      pPage = pCur->apPage[pCur->iPage];
54105    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
54106    *pRes = 0;
54107    if( pPage->intKey ){
54108      rc = sqlite3BtreeNext(pCur, pRes);
54109    }else{
54110      rc = SQLITE_OK;
54111    }
54112    return rc;
54113  }
54114  *pRes = 0;
54115  if( pPage->leaf ){
54116    return SQLITE_OK;
54117  }
54118  rc = moveToLeftmost(pCur);
54119  return rc;
54120}
54121
54122
54123/*
54124** Step the cursor to the back to the previous entry in the database.  If
54125** successful then set *pRes=0.  If the cursor
54126** was already pointing to the first entry in the database before
54127** this routine was called, then set *pRes=1.
54128*/
54129SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
54130  int rc;
54131  MemPage *pPage;
54132
54133  assert( cursorHoldsMutex(pCur) );
54134  rc = restoreCursorPosition(pCur);
54135  if( rc!=SQLITE_OK ){
54136    return rc;
54137  }
54138  pCur->atLast = 0;
54139  if( CURSOR_INVALID==pCur->eState ){
54140    *pRes = 1;
54141    return SQLITE_OK;
54142  }
54143  if( pCur->skipNext<0 ){
54144    pCur->skipNext = 0;
54145    *pRes = 0;
54146    return SQLITE_OK;
54147  }
54148  pCur->skipNext = 0;
54149
54150  pPage = pCur->apPage[pCur->iPage];
54151  assert( pPage->isInit );
54152  if( !pPage->leaf ){
54153    int idx = pCur->aiIdx[pCur->iPage];
54154    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
54155    if( rc ){
54156      return rc;
54157    }
54158    rc = moveToRightmost(pCur);
54159  }else{
54160    while( pCur->aiIdx[pCur->iPage]==0 ){
54161      if( pCur->iPage==0 ){
54162        pCur->eState = CURSOR_INVALID;
54163        *pRes = 1;
54164        return SQLITE_OK;
54165      }
54166      moveToParent(pCur);
54167    }
54168    pCur->info.nSize = 0;
54169    pCur->validNKey = 0;
54170
54171    pCur->aiIdx[pCur->iPage]--;
54172    pPage = pCur->apPage[pCur->iPage];
54173    if( pPage->intKey && !pPage->leaf ){
54174      rc = sqlite3BtreePrevious(pCur, pRes);
54175    }else{
54176      rc = SQLITE_OK;
54177    }
54178  }
54179  *pRes = 0;
54180  return rc;
54181}
54182
54183/*
54184** Allocate a new page from the database file.
54185**
54186** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
54187** has already been called on the new page.)  The new page has also
54188** been referenced and the calling routine is responsible for calling
54189** sqlite3PagerUnref() on the new page when it is done.
54190**
54191** SQLITE_OK is returned on success.  Any other return value indicates
54192** an error.  *ppPage and *pPgno are undefined in the event of an error.
54193** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
54194**
54195** If the "nearby" parameter is not 0, then a (feeble) effort is made to
54196** locate a page close to the page number "nearby".  This can be used in an
54197** attempt to keep related pages close to each other in the database file,
54198** which in turn can make database access faster.
54199**
54200** If the "exact" parameter is not 0, and the page-number nearby exists
54201** anywhere on the free-list, then it is guarenteed to be returned. This
54202** is only used by auto-vacuum databases when allocating a new table.
54203*/
54204static int allocateBtreePage(
54205  BtShared *pBt,
54206  MemPage **ppPage,
54207  Pgno *pPgno,
54208  Pgno nearby,
54209  u8 exact
54210){
54211  MemPage *pPage1;
54212  int rc;
54213  u32 n;     /* Number of pages on the freelist */
54214  u32 k;     /* Number of leaves on the trunk of the freelist */
54215  MemPage *pTrunk = 0;
54216  MemPage *pPrevTrunk = 0;
54217  Pgno mxPage;     /* Total size of the database file */
54218
54219  assert( sqlite3_mutex_held(pBt->mutex) );
54220  pPage1 = pBt->pPage1;
54221  mxPage = btreePagecount(pBt);
54222  n = get4byte(&pPage1->aData[36]);
54223  testcase( n==mxPage-1 );
54224  if( n>=mxPage ){
54225    return SQLITE_CORRUPT_BKPT;
54226  }
54227  if( n>0 ){
54228    /* There are pages on the freelist.  Reuse one of those pages. */
54229    Pgno iTrunk;
54230    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
54231
54232    /* If the 'exact' parameter was true and a query of the pointer-map
54233    ** shows that the page 'nearby' is somewhere on the free-list, then
54234    ** the entire-list will be searched for that page.
54235    */
54236#ifndef SQLITE_OMIT_AUTOVACUUM
54237    if( exact && nearby<=mxPage ){
54238      u8 eType;
54239      assert( nearby>0 );
54240      assert( pBt->autoVacuum );
54241      rc = ptrmapGet(pBt, nearby, &eType, 0);
54242      if( rc ) return rc;
54243      if( eType==PTRMAP_FREEPAGE ){
54244        searchList = 1;
54245      }
54246      *pPgno = nearby;
54247    }
54248#endif
54249
54250    /* Decrement the free-list count by 1. Set iTrunk to the index of the
54251    ** first free-list trunk page. iPrevTrunk is initially 1.
54252    */
54253    rc = sqlite3PagerWrite(pPage1->pDbPage);
54254    if( rc ) return rc;
54255    put4byte(&pPage1->aData[36], n-1);
54256
54257    /* The code within this loop is run only once if the 'searchList' variable
54258    ** is not true. Otherwise, it runs once for each trunk-page on the
54259    ** free-list until the page 'nearby' is located.
54260    */
54261    do {
54262      pPrevTrunk = pTrunk;
54263      if( pPrevTrunk ){
54264        iTrunk = get4byte(&pPrevTrunk->aData[0]);
54265      }else{
54266        iTrunk = get4byte(&pPage1->aData[32]);
54267      }
54268      testcase( iTrunk==mxPage );
54269      if( iTrunk>mxPage ){
54270        rc = SQLITE_CORRUPT_BKPT;
54271      }else{
54272        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
54273      }
54274      if( rc ){
54275        pTrunk = 0;
54276        goto end_allocate_page;
54277      }
54278      assert( pTrunk!=0 );
54279      assert( pTrunk->aData!=0 );
54280
54281      k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
54282      if( k==0 && !searchList ){
54283        /* The trunk has no leaves and the list is not being searched.
54284        ** So extract the trunk page itself and use it as the newly
54285        ** allocated page */
54286        assert( pPrevTrunk==0 );
54287        rc = sqlite3PagerWrite(pTrunk->pDbPage);
54288        if( rc ){
54289          goto end_allocate_page;
54290        }
54291        *pPgno = iTrunk;
54292        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54293        *ppPage = pTrunk;
54294        pTrunk = 0;
54295        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54296      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
54297        /* Value of k is out of range.  Database corruption */
54298        rc = SQLITE_CORRUPT_BKPT;
54299        goto end_allocate_page;
54300#ifndef SQLITE_OMIT_AUTOVACUUM
54301      }else if( searchList && nearby==iTrunk ){
54302        /* The list is being searched and this trunk page is the page
54303        ** to allocate, regardless of whether it has leaves.
54304        */
54305        assert( *pPgno==iTrunk );
54306        *ppPage = pTrunk;
54307        searchList = 0;
54308        rc = sqlite3PagerWrite(pTrunk->pDbPage);
54309        if( rc ){
54310          goto end_allocate_page;
54311        }
54312        if( k==0 ){
54313          if( !pPrevTrunk ){
54314            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54315          }else{
54316            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
54317            if( rc!=SQLITE_OK ){
54318              goto end_allocate_page;
54319            }
54320            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
54321          }
54322        }else{
54323          /* The trunk page is required by the caller but it contains
54324          ** pointers to free-list leaves. The first leaf becomes a trunk
54325          ** page in this case.
54326          */
54327          MemPage *pNewTrunk;
54328          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
54329          if( iNewTrunk>mxPage ){
54330            rc = SQLITE_CORRUPT_BKPT;
54331            goto end_allocate_page;
54332          }
54333          testcase( iNewTrunk==mxPage );
54334          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
54335          if( rc!=SQLITE_OK ){
54336            goto end_allocate_page;
54337          }
54338          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
54339          if( rc!=SQLITE_OK ){
54340            releasePage(pNewTrunk);
54341            goto end_allocate_page;
54342          }
54343          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
54344          put4byte(&pNewTrunk->aData[4], k-1);
54345          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
54346          releasePage(pNewTrunk);
54347          if( !pPrevTrunk ){
54348            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
54349            put4byte(&pPage1->aData[32], iNewTrunk);
54350          }else{
54351            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
54352            if( rc ){
54353              goto end_allocate_page;
54354            }
54355            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
54356          }
54357        }
54358        pTrunk = 0;
54359        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54360#endif
54361      }else if( k>0 ){
54362        /* Extract a leaf from the trunk */
54363        u32 closest;
54364        Pgno iPage;
54365        unsigned char *aData = pTrunk->aData;
54366        if( nearby>0 ){
54367          u32 i;
54368          int dist;
54369          closest = 0;
54370          dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
54371          for(i=1; i<k; i++){
54372            int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
54373            if( d2<dist ){
54374              closest = i;
54375              dist = d2;
54376            }
54377          }
54378        }else{
54379          closest = 0;
54380        }
54381
54382        iPage = get4byte(&aData[8+closest*4]);
54383        testcase( iPage==mxPage );
54384        if( iPage>mxPage ){
54385          rc = SQLITE_CORRUPT_BKPT;
54386          goto end_allocate_page;
54387        }
54388        testcase( iPage==mxPage );
54389        if( !searchList || iPage==nearby ){
54390          int noContent;
54391          *pPgno = iPage;
54392          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
54393                 ": %d more free pages\n",
54394                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
54395          rc = sqlite3PagerWrite(pTrunk->pDbPage);
54396          if( rc ) goto end_allocate_page;
54397          if( closest<k-1 ){
54398            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
54399          }
54400          put4byte(&aData[4], k-1);
54401          noContent = !btreeGetHasContent(pBt, *pPgno);
54402          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
54403          if( rc==SQLITE_OK ){
54404            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
54405            if( rc!=SQLITE_OK ){
54406              releasePage(*ppPage);
54407            }
54408          }
54409          searchList = 0;
54410        }
54411      }
54412      releasePage(pPrevTrunk);
54413      pPrevTrunk = 0;
54414    }while( searchList );
54415  }else{
54416    /* There are no pages on the freelist, so create a new page at the
54417    ** end of the file */
54418    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54419    if( rc ) return rc;
54420    pBt->nPage++;
54421    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
54422
54423#ifndef SQLITE_OMIT_AUTOVACUUM
54424    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
54425      /* If *pPgno refers to a pointer-map page, allocate two new pages
54426      ** at the end of the file instead of one. The first allocated page
54427      ** becomes a new pointer-map page, the second is used by the caller.
54428      */
54429      MemPage *pPg = 0;
54430      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
54431      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
54432      rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
54433      if( rc==SQLITE_OK ){
54434        rc = sqlite3PagerWrite(pPg->pDbPage);
54435        releasePage(pPg);
54436      }
54437      if( rc ) return rc;
54438      pBt->nPage++;
54439      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
54440    }
54441#endif
54442    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
54443    *pPgno = pBt->nPage;
54444
54445    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54446    rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
54447    if( rc ) return rc;
54448    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
54449    if( rc!=SQLITE_OK ){
54450      releasePage(*ppPage);
54451    }
54452    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
54453  }
54454
54455  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54456
54457end_allocate_page:
54458  releasePage(pTrunk);
54459  releasePage(pPrevTrunk);
54460  if( rc==SQLITE_OK ){
54461    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
54462      releasePage(*ppPage);
54463      return SQLITE_CORRUPT_BKPT;
54464    }
54465    (*ppPage)->isInit = 0;
54466  }else{
54467    *ppPage = 0;
54468  }
54469  assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
54470  return rc;
54471}
54472
54473/*
54474** This function is used to add page iPage to the database file free-list.
54475** It is assumed that the page is not already a part of the free-list.
54476**
54477** The value passed as the second argument to this function is optional.
54478** If the caller happens to have a pointer to the MemPage object
54479** corresponding to page iPage handy, it may pass it as the second value.
54480** Otherwise, it may pass NULL.
54481**
54482** If a pointer to a MemPage object is passed as the second argument,
54483** its reference count is not altered by this function.
54484*/
54485static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
54486  MemPage *pTrunk = 0;                /* Free-list trunk page */
54487  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
54488  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
54489  MemPage *pPage;                     /* Page being freed. May be NULL. */
54490  int rc;                             /* Return Code */
54491  int nFree;                          /* Initial number of pages on free-list */
54492
54493  assert( sqlite3_mutex_held(pBt->mutex) );
54494  assert( iPage>1 );
54495  assert( !pMemPage || pMemPage->pgno==iPage );
54496
54497  if( pMemPage ){
54498    pPage = pMemPage;
54499    sqlite3PagerRef(pPage->pDbPage);
54500  }else{
54501    pPage = btreePageLookup(pBt, iPage);
54502  }
54503
54504  /* Increment the free page count on pPage1 */
54505  rc = sqlite3PagerWrite(pPage1->pDbPage);
54506  if( rc ) goto freepage_out;
54507  nFree = get4byte(&pPage1->aData[36]);
54508  put4byte(&pPage1->aData[36], nFree+1);
54509
54510  if( pBt->btsFlags & BTS_SECURE_DELETE ){
54511    /* If the secure_delete option is enabled, then
54512    ** always fully overwrite deleted information with zeros.
54513    */
54514    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
54515     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
54516    ){
54517      goto freepage_out;
54518    }
54519    memset(pPage->aData, 0, pPage->pBt->pageSize);
54520  }
54521
54522  /* If the database supports auto-vacuum, write an entry in the pointer-map
54523  ** to indicate that the page is free.
54524  */
54525  if( ISAUTOVACUUM ){
54526    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
54527    if( rc ) goto freepage_out;
54528  }
54529
54530  /* Now manipulate the actual database free-list structure. There are two
54531  ** possibilities. If the free-list is currently empty, or if the first
54532  ** trunk page in the free-list is full, then this page will become a
54533  ** new free-list trunk page. Otherwise, it will become a leaf of the
54534  ** first trunk page in the current free-list. This block tests if it
54535  ** is possible to add the page as a new free-list leaf.
54536  */
54537  if( nFree!=0 ){
54538    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
54539
54540    iTrunk = get4byte(&pPage1->aData[32]);
54541    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
54542    if( rc!=SQLITE_OK ){
54543      goto freepage_out;
54544    }
54545
54546    nLeaf = get4byte(&pTrunk->aData[4]);
54547    assert( pBt->usableSize>32 );
54548    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
54549      rc = SQLITE_CORRUPT_BKPT;
54550      goto freepage_out;
54551    }
54552    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
54553      /* In this case there is room on the trunk page to insert the page
54554      ** being freed as a new leaf.
54555      **
54556      ** Note that the trunk page is not really full until it contains
54557      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
54558      ** coded.  But due to a coding error in versions of SQLite prior to
54559      ** 3.6.0, databases with freelist trunk pages holding more than
54560      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
54561      ** to maintain backwards compatibility with older versions of SQLite,
54562      ** we will continue to restrict the number of entries to usableSize/4 - 8
54563      ** for now.  At some point in the future (once everyone has upgraded
54564      ** to 3.6.0 or later) we should consider fixing the conditional above
54565      ** to read "usableSize/4-2" instead of "usableSize/4-8".
54566      */
54567      rc = sqlite3PagerWrite(pTrunk->pDbPage);
54568      if( rc==SQLITE_OK ){
54569        put4byte(&pTrunk->aData[4], nLeaf+1);
54570        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
54571        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
54572          sqlite3PagerDontWrite(pPage->pDbPage);
54573        }
54574        rc = btreeSetHasContent(pBt, iPage);
54575      }
54576      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
54577      goto freepage_out;
54578    }
54579  }
54580
54581  /* If control flows to this point, then it was not possible to add the
54582  ** the page being freed as a leaf page of the first trunk in the free-list.
54583  ** Possibly because the free-list is empty, or possibly because the
54584  ** first trunk in the free-list is full. Either way, the page being freed
54585  ** will become the new first trunk page in the free-list.
54586  */
54587  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
54588    goto freepage_out;
54589  }
54590  rc = sqlite3PagerWrite(pPage->pDbPage);
54591  if( rc!=SQLITE_OK ){
54592    goto freepage_out;
54593  }
54594  put4byte(pPage->aData, iTrunk);
54595  put4byte(&pPage->aData[4], 0);
54596  put4byte(&pPage1->aData[32], iPage);
54597  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
54598
54599freepage_out:
54600  if( pPage ){
54601    pPage->isInit = 0;
54602  }
54603  releasePage(pPage);
54604  releasePage(pTrunk);
54605  return rc;
54606}
54607static void freePage(MemPage *pPage, int *pRC){
54608  if( (*pRC)==SQLITE_OK ){
54609    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
54610  }
54611}
54612
54613/*
54614** Free any overflow pages associated with the given Cell.
54615*/
54616static int clearCell(MemPage *pPage, unsigned char *pCell){
54617  BtShared *pBt = pPage->pBt;
54618  CellInfo info;
54619  Pgno ovflPgno;
54620  int rc;
54621  int nOvfl;
54622  u32 ovflPageSize;
54623
54624  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54625  btreeParseCellPtr(pPage, pCell, &info);
54626  if( info.iOverflow==0 ){
54627    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
54628  }
54629  if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
54630    return SQLITE_CORRUPT;  /* Cell extends past end of page */
54631  }
54632  ovflPgno = get4byte(&pCell[info.iOverflow]);
54633  assert( pBt->usableSize > 4 );
54634  ovflPageSize = pBt->usableSize - 4;
54635  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
54636  assert( ovflPgno==0 || nOvfl>0 );
54637  while( nOvfl-- ){
54638    Pgno iNext = 0;
54639    MemPage *pOvfl = 0;
54640    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
54641      /* 0 is not a legal page number and page 1 cannot be an
54642      ** overflow page. Therefore if ovflPgno<2 or past the end of the
54643      ** file the database must be corrupt. */
54644      return SQLITE_CORRUPT_BKPT;
54645    }
54646    if( nOvfl ){
54647      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
54648      if( rc ) return rc;
54649    }
54650
54651    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
54652     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
54653    ){
54654      /* There is no reason any cursor should have an outstanding reference
54655      ** to an overflow page belonging to a cell that is being deleted/updated.
54656      ** So if there exists more than one reference to this page, then it
54657      ** must not really be an overflow page and the database must be corrupt.
54658      ** It is helpful to detect this before calling freePage2(), as
54659      ** freePage2() may zero the page contents if secure-delete mode is
54660      ** enabled. If this 'overflow' page happens to be a page that the
54661      ** caller is iterating through or using in some other way, this
54662      ** can be problematic.
54663      */
54664      rc = SQLITE_CORRUPT_BKPT;
54665    }else{
54666      rc = freePage2(pBt, pOvfl, ovflPgno);
54667    }
54668
54669    if( pOvfl ){
54670      sqlite3PagerUnref(pOvfl->pDbPage);
54671    }
54672    if( rc ) return rc;
54673    ovflPgno = iNext;
54674  }
54675  return SQLITE_OK;
54676}
54677
54678/*
54679** Create the byte sequence used to represent a cell on page pPage
54680** and write that byte sequence into pCell[].  Overflow pages are
54681** allocated and filled in as necessary.  The calling procedure
54682** is responsible for making sure sufficient space has been allocated
54683** for pCell[].
54684**
54685** Note that pCell does not necessary need to point to the pPage->aData
54686** area.  pCell might point to some temporary storage.  The cell will
54687** be constructed in this temporary area then copied into pPage->aData
54688** later.
54689*/
54690static int fillInCell(
54691  MemPage *pPage,                /* The page that contains the cell */
54692  unsigned char *pCell,          /* Complete text of the cell */
54693  const void *pKey, i64 nKey,    /* The key */
54694  const void *pData,int nData,   /* The data */
54695  int nZero,                     /* Extra zero bytes to append to pData */
54696  int *pnSize                    /* Write cell size here */
54697){
54698  int nPayload;
54699  const u8 *pSrc;
54700  int nSrc, n, rc;
54701  int spaceLeft;
54702  MemPage *pOvfl = 0;
54703  MemPage *pToRelease = 0;
54704  unsigned char *pPrior;
54705  unsigned char *pPayload;
54706  BtShared *pBt = pPage->pBt;
54707  Pgno pgnoOvfl = 0;
54708  int nHeader;
54709  CellInfo info;
54710
54711  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54712
54713  /* pPage is not necessarily writeable since pCell might be auxiliary
54714  ** buffer space that is separate from the pPage buffer area */
54715  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
54716            || sqlite3PagerIswriteable(pPage->pDbPage) );
54717
54718  /* Fill in the header. */
54719  nHeader = 0;
54720  if( !pPage->leaf ){
54721    nHeader += 4;
54722  }
54723  if( pPage->hasData ){
54724    nHeader += putVarint(&pCell[nHeader], nData+nZero);
54725  }else{
54726    nData = nZero = 0;
54727  }
54728  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
54729  btreeParseCellPtr(pPage, pCell, &info);
54730  assert( info.nHeader==nHeader );
54731  assert( info.nKey==nKey );
54732  assert( info.nData==(u32)(nData+nZero) );
54733
54734  /* Fill in the payload */
54735  nPayload = nData + nZero;
54736  if( pPage->intKey ){
54737    pSrc = pData;
54738    nSrc = nData;
54739    nData = 0;
54740  }else{
54741    if( NEVER(nKey>0x7fffffff || pKey==0) ){
54742      return SQLITE_CORRUPT_BKPT;
54743    }
54744    nPayload += (int)nKey;
54745    pSrc = pKey;
54746    nSrc = (int)nKey;
54747  }
54748  *pnSize = info.nSize;
54749  spaceLeft = info.nLocal;
54750  pPayload = &pCell[nHeader];
54751  pPrior = &pCell[info.iOverflow];
54752
54753  while( nPayload>0 ){
54754    if( spaceLeft==0 ){
54755#ifndef SQLITE_OMIT_AUTOVACUUM
54756      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
54757      if( pBt->autoVacuum ){
54758        do{
54759          pgnoOvfl++;
54760        } while(
54761          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
54762        );
54763      }
54764#endif
54765      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
54766#ifndef SQLITE_OMIT_AUTOVACUUM
54767      /* If the database supports auto-vacuum, and the second or subsequent
54768      ** overflow page is being allocated, add an entry to the pointer-map
54769      ** for that page now.
54770      **
54771      ** If this is the first overflow page, then write a partial entry
54772      ** to the pointer-map. If we write nothing to this pointer-map slot,
54773      ** then the optimistic overflow chain processing in clearCell()
54774      ** may misinterpret the uninitialised values and delete the
54775      ** wrong pages from the database.
54776      */
54777      if( pBt->autoVacuum && rc==SQLITE_OK ){
54778        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
54779        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
54780        if( rc ){
54781          releasePage(pOvfl);
54782        }
54783      }
54784#endif
54785      if( rc ){
54786        releasePage(pToRelease);
54787        return rc;
54788      }
54789
54790      /* If pToRelease is not zero than pPrior points into the data area
54791      ** of pToRelease.  Make sure pToRelease is still writeable. */
54792      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
54793
54794      /* If pPrior is part of the data area of pPage, then make sure pPage
54795      ** is still writeable */
54796      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
54797            || sqlite3PagerIswriteable(pPage->pDbPage) );
54798
54799      put4byte(pPrior, pgnoOvfl);
54800      releasePage(pToRelease);
54801      pToRelease = pOvfl;
54802      pPrior = pOvfl->aData;
54803      put4byte(pPrior, 0);
54804      pPayload = &pOvfl->aData[4];
54805      spaceLeft = pBt->usableSize - 4;
54806    }
54807    n = nPayload;
54808    if( n>spaceLeft ) n = spaceLeft;
54809
54810    /* If pToRelease is not zero than pPayload points into the data area
54811    ** of pToRelease.  Make sure pToRelease is still writeable. */
54812    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
54813
54814    /* If pPayload is part of the data area of pPage, then make sure pPage
54815    ** is still writeable */
54816    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
54817            || sqlite3PagerIswriteable(pPage->pDbPage) );
54818
54819    if( nSrc>0 ){
54820      if( n>nSrc ) n = nSrc;
54821      assert( pSrc );
54822      memcpy(pPayload, pSrc, n);
54823    }else{
54824      memset(pPayload, 0, n);
54825    }
54826    nPayload -= n;
54827    pPayload += n;
54828    pSrc += n;
54829    nSrc -= n;
54830    spaceLeft -= n;
54831    if( nSrc==0 ){
54832      nSrc = nData;
54833      pSrc = pData;
54834    }
54835  }
54836  releasePage(pToRelease);
54837  return SQLITE_OK;
54838}
54839
54840/*
54841** Remove the i-th cell from pPage.  This routine effects pPage only.
54842** The cell content is not freed or deallocated.  It is assumed that
54843** the cell content has been copied someplace else.  This routine just
54844** removes the reference to the cell from pPage.
54845**
54846** "sz" must be the number of bytes in the cell.
54847*/
54848static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
54849  u32 pc;         /* Offset to cell content of cell being deleted */
54850  u8 *data;       /* pPage->aData */
54851  u8 *ptr;        /* Used to move bytes around within data[] */
54852  u8 *endPtr;     /* End of loop */
54853  int rc;         /* The return code */
54854  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
54855
54856  if( *pRC ) return;
54857
54858  assert( idx>=0 && idx<pPage->nCell );
54859  assert( sz==cellSize(pPage, idx) );
54860  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54861  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54862  data = pPage->aData;
54863  ptr = &pPage->aCellIdx[2*idx];
54864  pc = get2byte(ptr);
54865  hdr = pPage->hdrOffset;
54866  testcase( pc==get2byte(&data[hdr+5]) );
54867  testcase( pc+sz==pPage->pBt->usableSize );
54868  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
54869    *pRC = SQLITE_CORRUPT_BKPT;
54870    return;
54871  }
54872  rc = freeSpace(pPage, pc, sz);
54873  if( rc ){
54874    *pRC = rc;
54875    return;
54876  }
54877  endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
54878  assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
54879  while( ptr<endPtr ){
54880    *(u16*)ptr = *(u16*)&ptr[2];
54881    ptr += 2;
54882  }
54883  pPage->nCell--;
54884  put2byte(&data[hdr+3], pPage->nCell);
54885  pPage->nFree += 2;
54886}
54887
54888/*
54889** Insert a new cell on pPage at cell index "i".  pCell points to the
54890** content of the cell.
54891**
54892** If the cell content will fit on the page, then put it there.  If it
54893** will not fit, then make a copy of the cell content into pTemp if
54894** pTemp is not null.  Regardless of pTemp, allocate a new entry
54895** in pPage->apOvfl[] and make it point to the cell content (either
54896** in pTemp or the original pCell) and also record its index.
54897** Allocating a new entry in pPage->aCell[] implies that
54898** pPage->nOverflow is incremented.
54899**
54900** If nSkip is non-zero, then do not copy the first nSkip bytes of the
54901** cell. The caller will overwrite them after this function returns. If
54902** nSkip is non-zero, then pCell may not point to an invalid memory location
54903** (but pCell+nSkip is always valid).
54904*/
54905static void insertCell(
54906  MemPage *pPage,   /* Page into which we are copying */
54907  int i,            /* New cell becomes the i-th cell of the page */
54908  u8 *pCell,        /* Content of the new cell */
54909  int sz,           /* Bytes of content in pCell */
54910  u8 *pTemp,        /* Temp storage space for pCell, if needed */
54911  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
54912  int *pRC          /* Read and write return code from here */
54913){
54914  int idx = 0;      /* Where to write new cell content in data[] */
54915  int j;            /* Loop counter */
54916  int end;          /* First byte past the last cell pointer in data[] */
54917  int ins;          /* Index in data[] where new cell pointer is inserted */
54918  int cellOffset;   /* Address of first cell pointer in data[] */
54919  u8 *data;         /* The content of the whole page */
54920  u8 *ptr;          /* Used for moving information around in data[] */
54921  u8 *endPtr;       /* End of the loop */
54922
54923  int nSkip = (iChild ? 4 : 0);
54924
54925  if( *pRC ) return;
54926
54927  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
54928  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
54929  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
54930  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
54931  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54932  /* The cell should normally be sized correctly.  However, when moving a
54933  ** malformed cell from a leaf page to an interior page, if the cell size
54934  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
54935  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
54936  ** the term after the || in the following assert(). */
54937  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
54938  if( pPage->nOverflow || sz+2>pPage->nFree ){
54939    if( pTemp ){
54940      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
54941      pCell = pTemp;
54942    }
54943    if( iChild ){
54944      put4byte(pCell, iChild);
54945    }
54946    j = pPage->nOverflow++;
54947    assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
54948    pPage->apOvfl[j] = pCell;
54949    pPage->aiOvfl[j] = (u16)i;
54950  }else{
54951    int rc = sqlite3PagerWrite(pPage->pDbPage);
54952    if( rc!=SQLITE_OK ){
54953      *pRC = rc;
54954      return;
54955    }
54956    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54957    data = pPage->aData;
54958    cellOffset = pPage->cellOffset;
54959    end = cellOffset + 2*pPage->nCell;
54960    ins = cellOffset + 2*i;
54961    rc = allocateSpace(pPage, sz, &idx);
54962    if( rc ){ *pRC = rc; return; }
54963    /* The allocateSpace() routine guarantees the following two properties
54964    ** if it returns success */
54965    assert( idx >= end+2 );
54966    assert( idx+sz <= (int)pPage->pBt->usableSize );
54967    pPage->nCell++;
54968    pPage->nFree -= (u16)(2 + sz);
54969    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
54970    if( iChild ){
54971      put4byte(&data[idx], iChild);
54972    }
54973    ptr = &data[end];
54974    endPtr = &data[ins];
54975    assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
54976    while( ptr>endPtr ){
54977      *(u16*)ptr = *(u16*)&ptr[-2];
54978      ptr -= 2;
54979    }
54980    put2byte(&data[ins], idx);
54981    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
54982#ifndef SQLITE_OMIT_AUTOVACUUM
54983    if( pPage->pBt->autoVacuum ){
54984      /* The cell may contain a pointer to an overflow page. If so, write
54985      ** the entry for the overflow page into the pointer map.
54986      */
54987      ptrmapPutOvflPtr(pPage, pCell, pRC);
54988    }
54989#endif
54990  }
54991}
54992
54993/*
54994** Add a list of cells to a page.  The page should be initially empty.
54995** The cells are guaranteed to fit on the page.
54996*/
54997static void assemblePage(
54998  MemPage *pPage,   /* The page to be assemblied */
54999  int nCell,        /* The number of cells to add to this page */
55000  u8 **apCell,      /* Pointers to cell bodies */
55001  u16 *aSize        /* Sizes of the cells */
55002){
55003  int i;            /* Loop counter */
55004  u8 *pCellptr;     /* Address of next cell pointer */
55005  int cellbody;     /* Address of next cell body */
55006  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
55007  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
55008  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
55009
55010  assert( pPage->nOverflow==0 );
55011  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55012  assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
55013            && (int)MX_CELL(pPage->pBt)<=10921);
55014  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55015
55016  /* Check that the page has just been zeroed by zeroPage() */
55017  assert( pPage->nCell==0 );
55018  assert( get2byteNotZero(&data[hdr+5])==nUsable );
55019
55020  pCellptr = &pPage->aCellIdx[nCell*2];
55021  cellbody = nUsable;
55022  for(i=nCell-1; i>=0; i--){
55023    u16 sz = aSize[i];
55024    pCellptr -= 2;
55025    cellbody -= sz;
55026    put2byte(pCellptr, cellbody);
55027    memcpy(&data[cellbody], apCell[i], sz);
55028  }
55029  put2byte(&data[hdr+3], nCell);
55030  put2byte(&data[hdr+5], cellbody);
55031  pPage->nFree -= (nCell*2 + nUsable - cellbody);
55032  pPage->nCell = (u16)nCell;
55033}
55034
55035/*
55036** The following parameters determine how many adjacent pages get involved
55037** in a balancing operation.  NN is the number of neighbors on either side
55038** of the page that participate in the balancing operation.  NB is the
55039** total number of pages that participate, including the target page and
55040** NN neighbors on either side.
55041**
55042** The minimum value of NN is 1 (of course).  Increasing NN above 1
55043** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
55044** in exchange for a larger degradation in INSERT and UPDATE performance.
55045** The value of NN appears to give the best results overall.
55046*/
55047#define NN 1             /* Number of neighbors on either side of pPage */
55048#define NB (NN*2+1)      /* Total pages involved in the balance */
55049
55050
55051#ifndef SQLITE_OMIT_QUICKBALANCE
55052/*
55053** This version of balance() handles the common special case where
55054** a new entry is being inserted on the extreme right-end of the
55055** tree, in other words, when the new entry will become the largest
55056** entry in the tree.
55057**
55058** Instead of trying to balance the 3 right-most leaf pages, just add
55059** a new page to the right-hand side and put the one new entry in
55060** that page.  This leaves the right side of the tree somewhat
55061** unbalanced.  But odds are that we will be inserting new entries
55062** at the end soon afterwards so the nearly empty page will quickly
55063** fill up.  On average.
55064**
55065** pPage is the leaf page which is the right-most page in the tree.
55066** pParent is its parent.  pPage must have a single overflow entry
55067** which is also the right-most entry on the page.
55068**
55069** The pSpace buffer is used to store a temporary copy of the divider
55070** cell that will be inserted into pParent. Such a cell consists of a 4
55071** byte page number followed by a variable length integer. In other
55072** words, at most 13 bytes. Hence the pSpace buffer must be at
55073** least 13 bytes in size.
55074*/
55075static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
55076  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
55077  MemPage *pNew;                       /* Newly allocated page */
55078  int rc;                              /* Return Code */
55079  Pgno pgnoNew;                        /* Page number of pNew */
55080
55081  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55082  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55083  assert( pPage->nOverflow==1 );
55084
55085  /* This error condition is now caught prior to reaching this function */
55086  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
55087
55088  /* Allocate a new page. This page will become the right-sibling of
55089  ** pPage. Make the parent page writable, so that the new divider cell
55090  ** may be inserted. If both these operations are successful, proceed.
55091  */
55092  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
55093
55094  if( rc==SQLITE_OK ){
55095
55096    u8 *pOut = &pSpace[4];
55097    u8 *pCell = pPage->apOvfl[0];
55098    u16 szCell = cellSizePtr(pPage, pCell);
55099    u8 *pStop;
55100
55101    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
55102    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
55103    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
55104    assemblePage(pNew, 1, &pCell, &szCell);
55105
55106    /* If this is an auto-vacuum database, update the pointer map
55107    ** with entries for the new page, and any pointer from the
55108    ** cell on the page to an overflow page. If either of these
55109    ** operations fails, the return code is set, but the contents
55110    ** of the parent page are still manipulated by thh code below.
55111    ** That is Ok, at this point the parent page is guaranteed to
55112    ** be marked as dirty. Returning an error code will cause a
55113    ** rollback, undoing any changes made to the parent page.
55114    */
55115    if( ISAUTOVACUUM ){
55116      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
55117      if( szCell>pNew->minLocal ){
55118        ptrmapPutOvflPtr(pNew, pCell, &rc);
55119      }
55120    }
55121
55122    /* Create a divider cell to insert into pParent. The divider cell
55123    ** consists of a 4-byte page number (the page number of pPage) and
55124    ** a variable length key value (which must be the same value as the
55125    ** largest key on pPage).
55126    **
55127    ** To find the largest key value on pPage, first find the right-most
55128    ** cell on pPage. The first two fields of this cell are the
55129    ** record-length (a variable length integer at most 32-bits in size)
55130    ** and the key value (a variable length integer, may have any value).
55131    ** The first of the while(...) loops below skips over the record-length
55132    ** field. The second while(...) loop copies the key value from the
55133    ** cell on pPage into the pSpace buffer.
55134    */
55135    pCell = findCell(pPage, pPage->nCell-1);
55136    pStop = &pCell[9];
55137    while( (*(pCell++)&0x80) && pCell<pStop );
55138    pStop = &pCell[9];
55139    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
55140
55141    /* Insert the new divider cell into pParent. */
55142    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
55143               0, pPage->pgno, &rc);
55144
55145    /* Set the right-child pointer of pParent to point to the new page. */
55146    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
55147
55148    /* Release the reference to the new page. */
55149    releasePage(pNew);
55150  }
55151
55152  return rc;
55153}
55154#endif /* SQLITE_OMIT_QUICKBALANCE */
55155
55156#if 0
55157/*
55158** This function does not contribute anything to the operation of SQLite.
55159** it is sometimes activated temporarily while debugging code responsible
55160** for setting pointer-map entries.
55161*/
55162static int ptrmapCheckPages(MemPage **apPage, int nPage){
55163  int i, j;
55164  for(i=0; i<nPage; i++){
55165    Pgno n;
55166    u8 e;
55167    MemPage *pPage = apPage[i];
55168    BtShared *pBt = pPage->pBt;
55169    assert( pPage->isInit );
55170
55171    for(j=0; j<pPage->nCell; j++){
55172      CellInfo info;
55173      u8 *z;
55174
55175      z = findCell(pPage, j);
55176      btreeParseCellPtr(pPage, z, &info);
55177      if( info.iOverflow ){
55178        Pgno ovfl = get4byte(&z[info.iOverflow]);
55179        ptrmapGet(pBt, ovfl, &e, &n);
55180        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
55181      }
55182      if( !pPage->leaf ){
55183        Pgno child = get4byte(z);
55184        ptrmapGet(pBt, child, &e, &n);
55185        assert( n==pPage->pgno && e==PTRMAP_BTREE );
55186      }
55187    }
55188    if( !pPage->leaf ){
55189      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55190      ptrmapGet(pBt, child, &e, &n);
55191      assert( n==pPage->pgno && e==PTRMAP_BTREE );
55192    }
55193  }
55194  return 1;
55195}
55196#endif
55197
55198/*
55199** This function is used to copy the contents of the b-tree node stored
55200** on page pFrom to page pTo. If page pFrom was not a leaf page, then
55201** the pointer-map entries for each child page are updated so that the
55202** parent page stored in the pointer map is page pTo. If pFrom contained
55203** any cells with overflow page pointers, then the corresponding pointer
55204** map entries are also updated so that the parent page is page pTo.
55205**
55206** If pFrom is currently carrying any overflow cells (entries in the
55207** MemPage.apOvfl[] array), they are not copied to pTo.
55208**
55209** Before returning, page pTo is reinitialized using btreeInitPage().
55210**
55211** The performance of this function is not critical. It is only used by
55212** the balance_shallower() and balance_deeper() procedures, neither of
55213** which are called often under normal circumstances.
55214*/
55215static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
55216  if( (*pRC)==SQLITE_OK ){
55217    BtShared * const pBt = pFrom->pBt;
55218    u8 * const aFrom = pFrom->aData;
55219    u8 * const aTo = pTo->aData;
55220    int const iFromHdr = pFrom->hdrOffset;
55221    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
55222    int rc;
55223    int iData;
55224
55225
55226    assert( pFrom->isInit );
55227    assert( pFrom->nFree>=iToHdr );
55228    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
55229
55230    /* Copy the b-tree node content from page pFrom to page pTo. */
55231    iData = get2byte(&aFrom[iFromHdr+5]);
55232    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
55233    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
55234
55235    /* Reinitialize page pTo so that the contents of the MemPage structure
55236    ** match the new data. The initialization of pTo can actually fail under
55237    ** fairly obscure circumstances, even though it is a copy of initialized
55238    ** page pFrom.
55239    */
55240    pTo->isInit = 0;
55241    rc = btreeInitPage(pTo);
55242    if( rc!=SQLITE_OK ){
55243      *pRC = rc;
55244      return;
55245    }
55246
55247    /* If this is an auto-vacuum database, update the pointer-map entries
55248    ** for any b-tree or overflow pages that pTo now contains the pointers to.
55249    */
55250    if( ISAUTOVACUUM ){
55251      *pRC = setChildPtrmaps(pTo);
55252    }
55253  }
55254}
55255
55256/*
55257** This routine redistributes cells on the iParentIdx'th child of pParent
55258** (hereafter "the page") and up to 2 siblings so that all pages have about the
55259** same amount of free space. Usually a single sibling on either side of the
55260** page are used in the balancing, though both siblings might come from one
55261** side if the page is the first or last child of its parent. If the page
55262** has fewer than 2 siblings (something which can only happen if the page
55263** is a root page or a child of a root page) then all available siblings
55264** participate in the balancing.
55265**
55266** The number of siblings of the page might be increased or decreased by
55267** one or two in an effort to keep pages nearly full but not over full.
55268**
55269** Note that when this routine is called, some of the cells on the page
55270** might not actually be stored in MemPage.aData[]. This can happen
55271** if the page is overfull. This routine ensures that all cells allocated
55272** to the page and its siblings fit into MemPage.aData[] before returning.
55273**
55274** In the course of balancing the page and its siblings, cells may be
55275** inserted into or removed from the parent page (pParent). Doing so
55276** may cause the parent page to become overfull or underfull. If this
55277** happens, it is the responsibility of the caller to invoke the correct
55278** balancing routine to fix this problem (see the balance() routine).
55279**
55280** If this routine fails for any reason, it might leave the database
55281** in a corrupted state. So if this routine fails, the database should
55282** be rolled back.
55283**
55284** The third argument to this function, aOvflSpace, is a pointer to a
55285** buffer big enough to hold one page. If while inserting cells into the parent
55286** page (pParent) the parent page becomes overfull, this buffer is
55287** used to store the parent's overflow cells. Because this function inserts
55288** a maximum of four divider cells into the parent page, and the maximum
55289** size of a cell stored within an internal node is always less than 1/4
55290** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
55291** enough for all overflow cells.
55292**
55293** If aOvflSpace is set to a null pointer, this function returns
55294** SQLITE_NOMEM.
55295*/
55296static int balance_nonroot(
55297  MemPage *pParent,               /* Parent page of siblings being balanced */
55298  int iParentIdx,                 /* Index of "the page" in pParent */
55299  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
55300  int isRoot                      /* True if pParent is a root-page */
55301){
55302  BtShared *pBt;               /* The whole database */
55303  int nCell = 0;               /* Number of cells in apCell[] */
55304  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
55305  int nNew = 0;                /* Number of pages in apNew[] */
55306  int nOld;                    /* Number of pages in apOld[] */
55307  int i, j, k;                 /* Loop counters */
55308  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
55309  int rc = SQLITE_OK;          /* The return code */
55310  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
55311  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
55312  int usableSpace;             /* Bytes in pPage beyond the header */
55313  int pageFlags;               /* Value of pPage->aData[0] */
55314  int subtotal;                /* Subtotal of bytes in cells on one page */
55315  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
55316  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
55317  int szScratch;               /* Size of scratch memory requested */
55318  MemPage *apOld[NB];          /* pPage and up to two siblings */
55319  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
55320  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
55321  u8 *pRight;                  /* Location in parent of right-sibling pointer */
55322  u8 *apDiv[NB-1];             /* Divider cells in pParent */
55323  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
55324  int szNew[NB+2];             /* Combined size of cells place on i-th page */
55325  u8 **apCell = 0;             /* All cells begin balanced */
55326  u16 *szCell;                 /* Local size of all cells in apCell[] */
55327  u8 *aSpace1;                 /* Space for copies of dividers cells */
55328  Pgno pgno;                   /* Temp var to store a page number in */
55329
55330  pBt = pParent->pBt;
55331  assert( sqlite3_mutex_held(pBt->mutex) );
55332  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55333
55334#if 0
55335  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
55336#endif
55337
55338  /* At this point pParent may have at most one overflow cell. And if
55339  ** this overflow cell is present, it must be the cell with
55340  ** index iParentIdx. This scenario comes about when this function
55341  ** is called (indirectly) from sqlite3BtreeDelete().
55342  */
55343  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
55344  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
55345
55346  if( !aOvflSpace ){
55347    return SQLITE_NOMEM;
55348  }
55349
55350  /* Find the sibling pages to balance. Also locate the cells in pParent
55351  ** that divide the siblings. An attempt is made to find NN siblings on
55352  ** either side of pPage. More siblings are taken from one side, however,
55353  ** if there are fewer than NN siblings on the other side. If pParent
55354  ** has NB or fewer children then all children of pParent are taken.
55355  **
55356  ** This loop also drops the divider cells from the parent page. This
55357  ** way, the remainder of the function does not have to deal with any
55358  ** overflow cells in the parent page, since if any existed they will
55359  ** have already been removed.
55360  */
55361  i = pParent->nOverflow + pParent->nCell;
55362  if( i<2 ){
55363    nxDiv = 0;
55364    nOld = i+1;
55365  }else{
55366    nOld = 3;
55367    if( iParentIdx==0 ){
55368      nxDiv = 0;
55369    }else if( iParentIdx==i ){
55370      nxDiv = i-2;
55371    }else{
55372      nxDiv = iParentIdx-1;
55373    }
55374    i = 2;
55375  }
55376  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
55377    pRight = &pParent->aData[pParent->hdrOffset+8];
55378  }else{
55379    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
55380  }
55381  pgno = get4byte(pRight);
55382  while( 1 ){
55383    rc = getAndInitPage(pBt, pgno, &apOld[i]);
55384    if( rc ){
55385      memset(apOld, 0, (i+1)*sizeof(MemPage*));
55386      goto balance_cleanup;
55387    }
55388    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
55389    if( (i--)==0 ) break;
55390
55391    if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
55392      apDiv[i] = pParent->apOvfl[0];
55393      pgno = get4byte(apDiv[i]);
55394      szNew[i] = cellSizePtr(pParent, apDiv[i]);
55395      pParent->nOverflow = 0;
55396    }else{
55397      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
55398      pgno = get4byte(apDiv[i]);
55399      szNew[i] = cellSizePtr(pParent, apDiv[i]);
55400
55401      /* Drop the cell from the parent page. apDiv[i] still points to
55402      ** the cell within the parent, even though it has been dropped.
55403      ** This is safe because dropping a cell only overwrites the first
55404      ** four bytes of it, and this function does not need the first
55405      ** four bytes of the divider cell. So the pointer is safe to use
55406      ** later on.
55407      **
55408      ** But not if we are in secure-delete mode. In secure-delete mode,
55409      ** the dropCell() routine will overwrite the entire cell with zeroes.
55410      ** In this case, temporarily copy the cell into the aOvflSpace[]
55411      ** buffer. It will be copied out again as soon as the aSpace[] buffer
55412      ** is allocated.  */
55413      if( pBt->btsFlags & BTS_SECURE_DELETE ){
55414        int iOff;
55415
55416        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
55417        if( (iOff+szNew[i])>(int)pBt->usableSize ){
55418          rc = SQLITE_CORRUPT_BKPT;
55419          memset(apOld, 0, (i+1)*sizeof(MemPage*));
55420          goto balance_cleanup;
55421        }else{
55422          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
55423          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
55424        }
55425      }
55426      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
55427    }
55428  }
55429
55430  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
55431  ** alignment */
55432  nMaxCells = (nMaxCells + 3)&~3;
55433
55434  /*
55435  ** Allocate space for memory structures
55436  */
55437  k = pBt->pageSize + ROUND8(sizeof(MemPage));
55438  szScratch =
55439       nMaxCells*sizeof(u8*)                       /* apCell */
55440     + nMaxCells*sizeof(u16)                       /* szCell */
55441     + pBt->pageSize                               /* aSpace1 */
55442     + k*nOld;                                     /* Page copies (apCopy) */
55443  apCell = sqlite3ScratchMalloc( szScratch );
55444  if( apCell==0 ){
55445    rc = SQLITE_NOMEM;
55446    goto balance_cleanup;
55447  }
55448  szCell = (u16*)&apCell[nMaxCells];
55449  aSpace1 = (u8*)&szCell[nMaxCells];
55450  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
55451
55452  /*
55453  ** Load pointers to all cells on sibling pages and the divider cells
55454  ** into the local apCell[] array.  Make copies of the divider cells
55455  ** into space obtained from aSpace1[] and remove the the divider Cells
55456  ** from pParent.
55457  **
55458  ** If the siblings are on leaf pages, then the child pointers of the
55459  ** divider cells are stripped from the cells before they are copied
55460  ** into aSpace1[].  In this way, all cells in apCell[] are without
55461  ** child pointers.  If siblings are not leaves, then all cell in
55462  ** apCell[] include child pointers.  Either way, all cells in apCell[]
55463  ** are alike.
55464  **
55465  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
55466  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
55467  */
55468  leafCorrection = apOld[0]->leaf*4;
55469  leafData = apOld[0]->hasData;
55470  for(i=0; i<nOld; i++){
55471    int limit;
55472
55473    /* Before doing anything else, take a copy of the i'th original sibling
55474    ** The rest of this function will use data from the copies rather
55475    ** that the original pages since the original pages will be in the
55476    ** process of being overwritten.  */
55477    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
55478    memcpy(pOld, apOld[i], sizeof(MemPage));
55479    pOld->aData = (void*)&pOld[1];
55480    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
55481
55482    limit = pOld->nCell+pOld->nOverflow;
55483    if( pOld->nOverflow>0 ){
55484      for(j=0; j<limit; j++){
55485        assert( nCell<nMaxCells );
55486        apCell[nCell] = findOverflowCell(pOld, j);
55487        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55488        nCell++;
55489      }
55490    }else{
55491      u8 *aData = pOld->aData;
55492      u16 maskPage = pOld->maskPage;
55493      u16 cellOffset = pOld->cellOffset;
55494      for(j=0; j<limit; j++){
55495        assert( nCell<nMaxCells );
55496        apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
55497        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55498        nCell++;
55499      }
55500    }
55501    if( i<nOld-1 && !leafData){
55502      u16 sz = (u16)szNew[i];
55503      u8 *pTemp;
55504      assert( nCell<nMaxCells );
55505      szCell[nCell] = sz;
55506      pTemp = &aSpace1[iSpace1];
55507      iSpace1 += sz;
55508      assert( sz<=pBt->maxLocal+23 );
55509      assert( iSpace1 <= (int)pBt->pageSize );
55510      memcpy(pTemp, apDiv[i], sz);
55511      apCell[nCell] = pTemp+leafCorrection;
55512      assert( leafCorrection==0 || leafCorrection==4 );
55513      szCell[nCell] = szCell[nCell] - leafCorrection;
55514      if( !pOld->leaf ){
55515        assert( leafCorrection==0 );
55516        assert( pOld->hdrOffset==0 );
55517        /* The right pointer of the child page pOld becomes the left
55518        ** pointer of the divider cell */
55519        memcpy(apCell[nCell], &pOld->aData[8], 4);
55520      }else{
55521        assert( leafCorrection==4 );
55522        if( szCell[nCell]<4 ){
55523          /* Do not allow any cells smaller than 4 bytes. */
55524          szCell[nCell] = 4;
55525        }
55526      }
55527      nCell++;
55528    }
55529  }
55530
55531  /*
55532  ** Figure out the number of pages needed to hold all nCell cells.
55533  ** Store this number in "k".  Also compute szNew[] which is the total
55534  ** size of all cells on the i-th page and cntNew[] which is the index
55535  ** in apCell[] of the cell that divides page i from page i+1.
55536  ** cntNew[k] should equal nCell.
55537  **
55538  ** Values computed by this block:
55539  **
55540  **           k: The total number of sibling pages
55541  **    szNew[i]: Spaced used on the i-th sibling page.
55542  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
55543  **              the right of the i-th sibling page.
55544  ** usableSpace: Number of bytes of space available on each sibling.
55545  **
55546  */
55547  usableSpace = pBt->usableSize - 12 + leafCorrection;
55548  for(subtotal=k=i=0; i<nCell; i++){
55549    assert( i<nMaxCells );
55550    subtotal += szCell[i] + 2;
55551    if( subtotal > usableSpace ){
55552      szNew[k] = subtotal - szCell[i];
55553      cntNew[k] = i;
55554      if( leafData ){ i--; }
55555      subtotal = 0;
55556      k++;
55557      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
55558    }
55559  }
55560  szNew[k] = subtotal;
55561  cntNew[k] = nCell;
55562  k++;
55563
55564  /*
55565  ** The packing computed by the previous block is biased toward the siblings
55566  ** on the left side.  The left siblings are always nearly full, while the
55567  ** right-most sibling might be nearly empty.  This block of code attempts
55568  ** to adjust the packing of siblings to get a better balance.
55569  **
55570  ** This adjustment is more than an optimization.  The packing above might
55571  ** be so out of balance as to be illegal.  For example, the right-most
55572  ** sibling might be completely empty.  This adjustment is not optional.
55573  */
55574  for(i=k-1; i>0; i--){
55575    int szRight = szNew[i];  /* Size of sibling on the right */
55576    int szLeft = szNew[i-1]; /* Size of sibling on the left */
55577    int r;              /* Index of right-most cell in left sibling */
55578    int d;              /* Index of first cell to the left of right sibling */
55579
55580    r = cntNew[i-1] - 1;
55581    d = r + 1 - leafData;
55582    assert( d<nMaxCells );
55583    assert( r<nMaxCells );
55584    while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
55585      szRight += szCell[d] + 2;
55586      szLeft -= szCell[r] + 2;
55587      cntNew[i-1]--;
55588      r = cntNew[i-1] - 1;
55589      d = r + 1 - leafData;
55590    }
55591    szNew[i] = szRight;
55592    szNew[i-1] = szLeft;
55593  }
55594
55595  /* Either we found one or more cells (cntnew[0])>0) or pPage is
55596  ** a virtual root page.  A virtual root page is when the real root
55597  ** page is page 1 and we are the only child of that page.
55598  **
55599  ** UPDATE:  The assert() below is not necessarily true if the database
55600  ** file is corrupt.  The corruption will be detected and reported later
55601  ** in this procedure so there is no need to act upon it now.
55602  */
55603#if 0
55604  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
55605#endif
55606
55607  TRACE(("BALANCE: old: %d %d %d  ",
55608    apOld[0]->pgno,
55609    nOld>=2 ? apOld[1]->pgno : 0,
55610    nOld>=3 ? apOld[2]->pgno : 0
55611  ));
55612
55613  /*
55614  ** Allocate k new pages.  Reuse old pages where possible.
55615  */
55616  if( apOld[0]->pgno<=1 ){
55617    rc = SQLITE_CORRUPT_BKPT;
55618    goto balance_cleanup;
55619  }
55620  pageFlags = apOld[0]->aData[0];
55621  for(i=0; i<k; i++){
55622    MemPage *pNew;
55623    if( i<nOld ){
55624      pNew = apNew[i] = apOld[i];
55625      apOld[i] = 0;
55626      rc = sqlite3PagerWrite(pNew->pDbPage);
55627      nNew++;
55628      if( rc ) goto balance_cleanup;
55629    }else{
55630      assert( i>0 );
55631      rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
55632      if( rc ) goto balance_cleanup;
55633      apNew[i] = pNew;
55634      nNew++;
55635
55636      /* Set the pointer-map entry for the new sibling page. */
55637      if( ISAUTOVACUUM ){
55638        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
55639        if( rc!=SQLITE_OK ){
55640          goto balance_cleanup;
55641        }
55642      }
55643    }
55644  }
55645
55646  /* Free any old pages that were not reused as new pages.
55647  */
55648  while( i<nOld ){
55649    freePage(apOld[i], &rc);
55650    if( rc ) goto balance_cleanup;
55651    releasePage(apOld[i]);
55652    apOld[i] = 0;
55653    i++;
55654  }
55655
55656  /*
55657  ** Put the new pages in accending order.  This helps to
55658  ** keep entries in the disk file in order so that a scan
55659  ** of the table is a linear scan through the file.  That
55660  ** in turn helps the operating system to deliver pages
55661  ** from the disk more rapidly.
55662  **
55663  ** An O(n^2) insertion sort algorithm is used, but since
55664  ** n is never more than NB (a small constant), that should
55665  ** not be a problem.
55666  **
55667  ** When NB==3, this one optimization makes the database
55668  ** about 25% faster for large insertions and deletions.
55669  */
55670  for(i=0; i<k-1; i++){
55671    int minV = apNew[i]->pgno;
55672    int minI = i;
55673    for(j=i+1; j<k; j++){
55674      if( apNew[j]->pgno<(unsigned)minV ){
55675        minI = j;
55676        minV = apNew[j]->pgno;
55677      }
55678    }
55679    if( minI>i ){
55680      MemPage *pT;
55681      pT = apNew[i];
55682      apNew[i] = apNew[minI];
55683      apNew[minI] = pT;
55684    }
55685  }
55686  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
55687    apNew[0]->pgno, szNew[0],
55688    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
55689    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
55690    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
55691    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
55692
55693  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55694  put4byte(pRight, apNew[nNew-1]->pgno);
55695
55696  /*
55697  ** Evenly distribute the data in apCell[] across the new pages.
55698  ** Insert divider cells into pParent as necessary.
55699  */
55700  j = 0;
55701  for(i=0; i<nNew; i++){
55702    /* Assemble the new sibling page. */
55703    MemPage *pNew = apNew[i];
55704    assert( j<nMaxCells );
55705    zeroPage(pNew, pageFlags);
55706    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
55707    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
55708    assert( pNew->nOverflow==0 );
55709
55710    j = cntNew[i];
55711
55712    /* If the sibling page assembled above was not the right-most sibling,
55713    ** insert a divider cell into the parent page.
55714    */
55715    assert( i<nNew-1 || j==nCell );
55716    if( j<nCell ){
55717      u8 *pCell;
55718      u8 *pTemp;
55719      int sz;
55720
55721      assert( j<nMaxCells );
55722      pCell = apCell[j];
55723      sz = szCell[j] + leafCorrection;
55724      pTemp = &aOvflSpace[iOvflSpace];
55725      if( !pNew->leaf ){
55726        memcpy(&pNew->aData[8], pCell, 4);
55727      }else if( leafData ){
55728        /* If the tree is a leaf-data tree, and the siblings are leaves,
55729        ** then there is no divider cell in apCell[]. Instead, the divider
55730        ** cell consists of the integer key for the right-most cell of
55731        ** the sibling-page assembled above only.
55732        */
55733        CellInfo info;
55734        j--;
55735        btreeParseCellPtr(pNew, apCell[j], &info);
55736        pCell = pTemp;
55737        sz = 4 + putVarint(&pCell[4], info.nKey);
55738        pTemp = 0;
55739      }else{
55740        pCell -= 4;
55741        /* Obscure case for non-leaf-data trees: If the cell at pCell was
55742        ** previously stored on a leaf node, and its reported size was 4
55743        ** bytes, then it may actually be smaller than this
55744        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
55745        ** any cell). But it is important to pass the correct size to
55746        ** insertCell(), so reparse the cell now.
55747        **
55748        ** Note that this can never happen in an SQLite data file, as all
55749        ** cells are at least 4 bytes. It only happens in b-trees used
55750        ** to evaluate "IN (SELECT ...)" and similar clauses.
55751        */
55752        if( szCell[j]==4 ){
55753          assert(leafCorrection==4);
55754          sz = cellSizePtr(pParent, pCell);
55755        }
55756      }
55757      iOvflSpace += sz;
55758      assert( sz<=pBt->maxLocal+23 );
55759      assert( iOvflSpace <= (int)pBt->pageSize );
55760      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
55761      if( rc!=SQLITE_OK ) goto balance_cleanup;
55762      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55763
55764      j++;
55765      nxDiv++;
55766    }
55767  }
55768  assert( j==nCell );
55769  assert( nOld>0 );
55770  assert( nNew>0 );
55771  if( (pageFlags & PTF_LEAF)==0 ){
55772    u8 *zChild = &apCopy[nOld-1]->aData[8];
55773    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
55774  }
55775
55776  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
55777    /* The root page of the b-tree now contains no cells. The only sibling
55778    ** page is the right-child of the parent. Copy the contents of the
55779    ** child page into the parent, decreasing the overall height of the
55780    ** b-tree structure by one. This is described as the "balance-shallower"
55781    ** sub-algorithm in some documentation.
55782    **
55783    ** If this is an auto-vacuum database, the call to copyNodeContent()
55784    ** sets all pointer-map entries corresponding to database image pages
55785    ** for which the pointer is stored within the content being copied.
55786    **
55787    ** The second assert below verifies that the child page is defragmented
55788    ** (it must be, as it was just reconstructed using assemblePage()). This
55789    ** is important if the parent page happens to be page 1 of the database
55790    ** image.  */
55791    assert( nNew==1 );
55792    assert( apNew[0]->nFree ==
55793        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
55794    );
55795    copyNodeContent(apNew[0], pParent, &rc);
55796    freePage(apNew[0], &rc);
55797  }else if( ISAUTOVACUUM ){
55798    /* Fix the pointer-map entries for all the cells that were shifted around.
55799    ** There are several different types of pointer-map entries that need to
55800    ** be dealt with by this routine. Some of these have been set already, but
55801    ** many have not. The following is a summary:
55802    **
55803    **   1) The entries associated with new sibling pages that were not
55804    **      siblings when this function was called. These have already
55805    **      been set. We don't need to worry about old siblings that were
55806    **      moved to the free-list - the freePage() code has taken care
55807    **      of those.
55808    **
55809    **   2) The pointer-map entries associated with the first overflow
55810    **      page in any overflow chains used by new divider cells. These
55811    **      have also already been taken care of by the insertCell() code.
55812    **
55813    **   3) If the sibling pages are not leaves, then the child pages of
55814    **      cells stored on the sibling pages may need to be updated.
55815    **
55816    **   4) If the sibling pages are not internal intkey nodes, then any
55817    **      overflow pages used by these cells may need to be updated
55818    **      (internal intkey nodes never contain pointers to overflow pages).
55819    **
55820    **   5) If the sibling pages are not leaves, then the pointer-map
55821    **      entries for the right-child pages of each sibling may need
55822    **      to be updated.
55823    **
55824    ** Cases 1 and 2 are dealt with above by other code. The next
55825    ** block deals with cases 3 and 4 and the one after that, case 5. Since
55826    ** setting a pointer map entry is a relatively expensive operation, this
55827    ** code only sets pointer map entries for child or overflow pages that have
55828    ** actually moved between pages.  */
55829    MemPage *pNew = apNew[0];
55830    MemPage *pOld = apCopy[0];
55831    int nOverflow = pOld->nOverflow;
55832    int iNextOld = pOld->nCell + nOverflow;
55833    int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
55834    j = 0;                             /* Current 'old' sibling page */
55835    k = 0;                             /* Current 'new' sibling page */
55836    for(i=0; i<nCell; i++){
55837      int isDivider = 0;
55838      while( i==iNextOld ){
55839        /* Cell i is the cell immediately following the last cell on old
55840        ** sibling page j. If the siblings are not leaf pages of an
55841        ** intkey b-tree, then cell i was a divider cell. */
55842        assert( j+1 < ArraySize(apCopy) );
55843        pOld = apCopy[++j];
55844        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
55845        if( pOld->nOverflow ){
55846          nOverflow = pOld->nOverflow;
55847          iOverflow = i + !leafData + pOld->aiOvfl[0];
55848        }
55849        isDivider = !leafData;
55850      }
55851
55852      assert(nOverflow>0 || iOverflow<i );
55853      assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
55854      assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
55855      if( i==iOverflow ){
55856        isDivider = 1;
55857        if( (--nOverflow)>0 ){
55858          iOverflow++;
55859        }
55860      }
55861
55862      if( i==cntNew[k] ){
55863        /* Cell i is the cell immediately following the last cell on new
55864        ** sibling page k. If the siblings are not leaf pages of an
55865        ** intkey b-tree, then cell i is a divider cell.  */
55866        pNew = apNew[++k];
55867        if( !leafData ) continue;
55868      }
55869      assert( j<nOld );
55870      assert( k<nNew );
55871
55872      /* If the cell was originally divider cell (and is not now) or
55873      ** an overflow cell, or if the cell was located on a different sibling
55874      ** page before the balancing, then the pointer map entries associated
55875      ** with any child or overflow pages need to be updated.  */
55876      if( isDivider || pOld->pgno!=pNew->pgno ){
55877        if( !leafCorrection ){
55878          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
55879        }
55880        if( szCell[i]>pNew->minLocal ){
55881          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
55882        }
55883      }
55884    }
55885
55886    if( !leafCorrection ){
55887      for(i=0; i<nNew; i++){
55888        u32 key = get4byte(&apNew[i]->aData[8]);
55889        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
55890      }
55891    }
55892
55893#if 0
55894    /* The ptrmapCheckPages() contains assert() statements that verify that
55895    ** all pointer map pages are set correctly. This is helpful while
55896    ** debugging. This is usually disabled because a corrupt database may
55897    ** cause an assert() statement to fail.  */
55898    ptrmapCheckPages(apNew, nNew);
55899    ptrmapCheckPages(&pParent, 1);
55900#endif
55901  }
55902
55903  assert( pParent->isInit );
55904  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
55905          nOld, nNew, nCell));
55906
55907  /*
55908  ** Cleanup before returning.
55909  */
55910balance_cleanup:
55911  sqlite3ScratchFree(apCell);
55912  for(i=0; i<nOld; i++){
55913    releasePage(apOld[i]);
55914  }
55915  for(i=0; i<nNew; i++){
55916    releasePage(apNew[i]);
55917  }
55918
55919  return rc;
55920}
55921
55922
55923/*
55924** This function is called when the root page of a b-tree structure is
55925** overfull (has one or more overflow pages).
55926**
55927** A new child page is allocated and the contents of the current root
55928** page, including overflow cells, are copied into the child. The root
55929** page is then overwritten to make it an empty page with the right-child
55930** pointer pointing to the new page.
55931**
55932** Before returning, all pointer-map entries corresponding to pages
55933** that the new child-page now contains pointers to are updated. The
55934** entry corresponding to the new right-child pointer of the root
55935** page is also updated.
55936**
55937** If successful, *ppChild is set to contain a reference to the child
55938** page and SQLITE_OK is returned. In this case the caller is required
55939** to call releasePage() on *ppChild exactly once. If an error occurs,
55940** an error code is returned and *ppChild is set to 0.
55941*/
55942static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
55943  int rc;                        /* Return value from subprocedures */
55944  MemPage *pChild = 0;           /* Pointer to a new child page */
55945  Pgno pgnoChild = 0;            /* Page number of the new child page */
55946  BtShared *pBt = pRoot->pBt;    /* The BTree */
55947
55948  assert( pRoot->nOverflow>0 );
55949  assert( sqlite3_mutex_held(pBt->mutex) );
55950
55951  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
55952  ** page that will become the new right-child of pPage. Copy the contents
55953  ** of the node stored on pRoot into the new child page.
55954  */
55955  rc = sqlite3PagerWrite(pRoot->pDbPage);
55956  if( rc==SQLITE_OK ){
55957    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
55958    copyNodeContent(pRoot, pChild, &rc);
55959    if( ISAUTOVACUUM ){
55960      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
55961    }
55962  }
55963  if( rc ){
55964    *ppChild = 0;
55965    releasePage(pChild);
55966    return rc;
55967  }
55968  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
55969  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
55970  assert( pChild->nCell==pRoot->nCell );
55971
55972  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
55973
55974  /* Copy the overflow cells from pRoot to pChild */
55975  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
55976         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
55977  memcpy(pChild->apOvfl, pRoot->apOvfl,
55978         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
55979  pChild->nOverflow = pRoot->nOverflow;
55980
55981  /* Zero the contents of pRoot. Then install pChild as the right-child. */
55982  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
55983  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
55984
55985  *ppChild = pChild;
55986  return SQLITE_OK;
55987}
55988
55989/*
55990** The page that pCur currently points to has just been modified in
55991** some way. This function figures out if this modification means the
55992** tree needs to be balanced, and if so calls the appropriate balancing
55993** routine. Balancing routines are:
55994**
55995**   balance_quick()
55996**   balance_deeper()
55997**   balance_nonroot()
55998*/
55999static int balance(BtCursor *pCur){
56000  int rc = SQLITE_OK;
56001  const int nMin = pCur->pBt->usableSize * 2 / 3;
56002  u8 aBalanceQuickSpace[13];
56003  u8 *pFree = 0;
56004
56005  TESTONLY( int balance_quick_called = 0 );
56006  TESTONLY( int balance_deeper_called = 0 );
56007
56008  do {
56009    int iPage = pCur->iPage;
56010    MemPage *pPage = pCur->apPage[iPage];
56011
56012    if( iPage==0 ){
56013      if( pPage->nOverflow ){
56014        /* The root page of the b-tree is overfull. In this case call the
56015        ** balance_deeper() function to create a new child for the root-page
56016        ** and copy the current contents of the root-page to it. The
56017        ** next iteration of the do-loop will balance the child page.
56018        */
56019        assert( (balance_deeper_called++)==0 );
56020        rc = balance_deeper(pPage, &pCur->apPage[1]);
56021        if( rc==SQLITE_OK ){
56022          pCur->iPage = 1;
56023          pCur->aiIdx[0] = 0;
56024          pCur->aiIdx[1] = 0;
56025          assert( pCur->apPage[1]->nOverflow );
56026        }
56027      }else{
56028        break;
56029      }
56030    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
56031      break;
56032    }else{
56033      MemPage * const pParent = pCur->apPage[iPage-1];
56034      int const iIdx = pCur->aiIdx[iPage-1];
56035
56036      rc = sqlite3PagerWrite(pParent->pDbPage);
56037      if( rc==SQLITE_OK ){
56038#ifndef SQLITE_OMIT_QUICKBALANCE
56039        if( pPage->hasData
56040         && pPage->nOverflow==1
56041         && pPage->aiOvfl[0]==pPage->nCell
56042         && pParent->pgno!=1
56043         && pParent->nCell==iIdx
56044        ){
56045          /* Call balance_quick() to create a new sibling of pPage on which
56046          ** to store the overflow cell. balance_quick() inserts a new cell
56047          ** into pParent, which may cause pParent overflow. If this
56048          ** happens, the next interation of the do-loop will balance pParent
56049          ** use either balance_nonroot() or balance_deeper(). Until this
56050          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
56051          ** buffer.
56052          **
56053          ** The purpose of the following assert() is to check that only a
56054          ** single call to balance_quick() is made for each call to this
56055          ** function. If this were not verified, a subtle bug involving reuse
56056          ** of the aBalanceQuickSpace[] might sneak in.
56057          */
56058          assert( (balance_quick_called++)==0 );
56059          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
56060        }else
56061#endif
56062        {
56063          /* In this case, call balance_nonroot() to redistribute cells
56064          ** between pPage and up to 2 of its sibling pages. This involves
56065          ** modifying the contents of pParent, which may cause pParent to
56066          ** become overfull or underfull. The next iteration of the do-loop
56067          ** will balance the parent page to correct this.
56068          **
56069          ** If the parent page becomes overfull, the overflow cell or cells
56070          ** are stored in the pSpace buffer allocated immediately below.
56071          ** A subsequent iteration of the do-loop will deal with this by
56072          ** calling balance_nonroot() (balance_deeper() may be called first,
56073          ** but it doesn't deal with overflow cells - just moves them to a
56074          ** different page). Once this subsequent call to balance_nonroot()
56075          ** has completed, it is safe to release the pSpace buffer used by
56076          ** the previous call, as the overflow cell data will have been
56077          ** copied either into the body of a database page or into the new
56078          ** pSpace buffer passed to the latter call to balance_nonroot().
56079          */
56080          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
56081          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
56082          if( pFree ){
56083            /* If pFree is not NULL, it points to the pSpace buffer used
56084            ** by a previous call to balance_nonroot(). Its contents are
56085            ** now stored either on real database pages or within the
56086            ** new pSpace buffer, so it may be safely freed here. */
56087            sqlite3PageFree(pFree);
56088          }
56089
56090          /* The pSpace buffer will be freed after the next call to
56091          ** balance_nonroot(), or just before this function returns, whichever
56092          ** comes first. */
56093          pFree = pSpace;
56094        }
56095      }
56096
56097      pPage->nOverflow = 0;
56098
56099      /* The next iteration of the do-loop balances the parent page. */
56100      releasePage(pPage);
56101      pCur->iPage--;
56102    }
56103  }while( rc==SQLITE_OK );
56104
56105  if( pFree ){
56106    sqlite3PageFree(pFree);
56107  }
56108  return rc;
56109}
56110
56111
56112/*
56113** Insert a new record into the BTree.  The key is given by (pKey,nKey)
56114** and the data is given by (pData,nData).  The cursor is used only to
56115** define what table the record should be inserted into.  The cursor
56116** is left pointing at a random location.
56117**
56118** For an INTKEY table, only the nKey value of the key is used.  pKey is
56119** ignored.  For a ZERODATA table, the pData and nData are both ignored.
56120**
56121** If the seekResult parameter is non-zero, then a successful call to
56122** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
56123** been performed. seekResult is the search result returned (a negative
56124** number if pCur points at an entry that is smaller than (pKey, nKey), or
56125** a positive value if pCur points at an etry that is larger than
56126** (pKey, nKey)).
56127**
56128** If the seekResult parameter is non-zero, then the caller guarantees that
56129** cursor pCur is pointing at the existing copy of a row that is to be
56130** overwritten.  If the seekResult parameter is 0, then cursor pCur may
56131** point to any entry or to no entry at all and so this function has to seek
56132** the cursor before the new key can be inserted.
56133*/
56134SQLITE_PRIVATE int sqlite3BtreeInsert(
56135  BtCursor *pCur,                /* Insert data into the table of this cursor */
56136  const void *pKey, i64 nKey,    /* The key of the new record */
56137  const void *pData, int nData,  /* The data of the new record */
56138  int nZero,                     /* Number of extra 0 bytes to append to data */
56139  int appendBias,                /* True if this is likely an append */
56140  int seekResult                 /* Result of prior MovetoUnpacked() call */
56141){
56142  int rc;
56143  int loc = seekResult;          /* -1: before desired location  +1: after */
56144  int szNew = 0;
56145  int idx;
56146  MemPage *pPage;
56147  Btree *p = pCur->pBtree;
56148  BtShared *pBt = p->pBt;
56149  unsigned char *oldCell;
56150  unsigned char *newCell = 0;
56151
56152  if( pCur->eState==CURSOR_FAULT ){
56153    assert( pCur->skipNext!=SQLITE_OK );
56154    return pCur->skipNext;
56155  }
56156
56157  assert( cursorHoldsMutex(pCur) );
56158  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
56159              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
56160  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56161
56162  /* Assert that the caller has been consistent. If this cursor was opened
56163  ** expecting an index b-tree, then the caller should be inserting blob
56164  ** keys with no associated data. If the cursor was opened expecting an
56165  ** intkey table, the caller should be inserting integer keys with a
56166  ** blob of associated data.  */
56167  assert( (pKey==0)==(pCur->pKeyInfo==0) );
56168
56169  /* If this is an insert into a table b-tree, invalidate any incrblob
56170  ** cursors open on the row being replaced (assuming this is a replace
56171  ** operation - if it is not, the following is a no-op).  */
56172  if( pCur->pKeyInfo==0 ){
56173    invalidateIncrblobCursors(p, nKey, 0);
56174  }
56175
56176  /* Save the positions of any other cursors open on this table.
56177  **
56178  ** In some cases, the call to btreeMoveto() below is a no-op. For
56179  ** example, when inserting data into a table with auto-generated integer
56180  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
56181  ** integer key to use. It then calls this function to actually insert the
56182  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
56183  ** that the cursor is already where it needs to be and returns without
56184  ** doing any work. To avoid thwarting these optimizations, it is important
56185  ** not to clear the cursor here.
56186  */
56187  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56188  if( rc ) return rc;
56189  if( !loc ){
56190    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
56191    if( rc ) return rc;
56192  }
56193  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
56194
56195  pPage = pCur->apPage[pCur->iPage];
56196  assert( pPage->intKey || nKey>=0 );
56197  assert( pPage->leaf || !pPage->intKey );
56198
56199  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
56200          pCur->pgnoRoot, nKey, nData, pPage->pgno,
56201          loc==0 ? "overwrite" : "new entry"));
56202  assert( pPage->isInit );
56203  allocateTempSpace(pBt);
56204  newCell = pBt->pTmpSpace;
56205  if( newCell==0 ) return SQLITE_NOMEM;
56206  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
56207  if( rc ) goto end_insert;
56208  assert( szNew==cellSizePtr(pPage, newCell) );
56209  assert( szNew <= MX_CELL_SIZE(pBt) );
56210  idx = pCur->aiIdx[pCur->iPage];
56211  if( loc==0 ){
56212    u16 szOld;
56213    assert( idx<pPage->nCell );
56214    rc = sqlite3PagerWrite(pPage->pDbPage);
56215    if( rc ){
56216      goto end_insert;
56217    }
56218    oldCell = findCell(pPage, idx);
56219    if( !pPage->leaf ){
56220      memcpy(newCell, oldCell, 4);
56221    }
56222    szOld = cellSizePtr(pPage, oldCell);
56223    rc = clearCell(pPage, oldCell);
56224    dropCell(pPage, idx, szOld, &rc);
56225    if( rc ) goto end_insert;
56226  }else if( loc<0 && pPage->nCell>0 ){
56227    assert( pPage->leaf );
56228    idx = ++pCur->aiIdx[pCur->iPage];
56229  }else{
56230    assert( pPage->leaf );
56231  }
56232  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
56233  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
56234
56235  /* If no error has occured and pPage has an overflow cell, call balance()
56236  ** to redistribute the cells within the tree. Since balance() may move
56237  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
56238  ** variables.
56239  **
56240  ** Previous versions of SQLite called moveToRoot() to move the cursor
56241  ** back to the root page as balance() used to invalidate the contents
56242  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
56243  ** set the cursor state to "invalid". This makes common insert operations
56244  ** slightly faster.
56245  **
56246  ** There is a subtle but important optimization here too. When inserting
56247  ** multiple records into an intkey b-tree using a single cursor (as can
56248  ** happen while processing an "INSERT INTO ... SELECT" statement), it
56249  ** is advantageous to leave the cursor pointing to the last entry in
56250  ** the b-tree if possible. If the cursor is left pointing to the last
56251  ** entry in the table, and the next row inserted has an integer key
56252  ** larger than the largest existing key, it is possible to insert the
56253  ** row without seeking the cursor. This can be a big performance boost.
56254  */
56255  pCur->info.nSize = 0;
56256  pCur->validNKey = 0;
56257  if( rc==SQLITE_OK && pPage->nOverflow ){
56258    rc = balance(pCur);
56259
56260    /* Must make sure nOverflow is reset to zero even if the balance()
56261    ** fails. Internal data structure corruption will result otherwise.
56262    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
56263    ** from trying to save the current position of the cursor.  */
56264    pCur->apPage[pCur->iPage]->nOverflow = 0;
56265    pCur->eState = CURSOR_INVALID;
56266  }
56267  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
56268
56269end_insert:
56270  return rc;
56271}
56272
56273/*
56274** Delete the entry that the cursor is pointing to.  The cursor
56275** is left pointing at a arbitrary location.
56276*/
56277SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
56278  Btree *p = pCur->pBtree;
56279  BtShared *pBt = p->pBt;
56280  int rc;                              /* Return code */
56281  MemPage *pPage;                      /* Page to delete cell from */
56282  unsigned char *pCell;                /* Pointer to cell to delete */
56283  int iCellIdx;                        /* Index of cell to delete */
56284  int iCellDepth;                      /* Depth of node containing pCell */
56285
56286  assert( cursorHoldsMutex(pCur) );
56287  assert( pBt->inTransaction==TRANS_WRITE );
56288  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56289  assert( pCur->wrFlag );
56290  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56291  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
56292
56293  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
56294   || NEVER(pCur->eState!=CURSOR_VALID)
56295  ){
56296    return SQLITE_ERROR;  /* Something has gone awry. */
56297  }
56298
56299  /* If this is a delete operation to remove a row from a table b-tree,
56300  ** invalidate any incrblob cursors open on the row being deleted.  */
56301  if( pCur->pKeyInfo==0 ){
56302    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
56303  }
56304
56305  iCellDepth = pCur->iPage;
56306  iCellIdx = pCur->aiIdx[iCellDepth];
56307  pPage = pCur->apPage[iCellDepth];
56308  pCell = findCell(pPage, iCellIdx);
56309
56310  /* If the page containing the entry to delete is not a leaf page, move
56311  ** the cursor to the largest entry in the tree that is smaller than
56312  ** the entry being deleted. This cell will replace the cell being deleted
56313  ** from the internal node. The 'previous' entry is used for this instead
56314  ** of the 'next' entry, as the previous entry is always a part of the
56315  ** sub-tree headed by the child page of the cell being deleted. This makes
56316  ** balancing the tree following the delete operation easier.  */
56317  if( !pPage->leaf ){
56318    int notUsed;
56319    rc = sqlite3BtreePrevious(pCur, &notUsed);
56320    if( rc ) return rc;
56321  }
56322
56323  /* Save the positions of any other cursors open on this table before
56324  ** making any modifications. Make the page containing the entry to be
56325  ** deleted writable. Then free any overflow pages associated with the
56326  ** entry and finally remove the cell itself from within the page.
56327  */
56328  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56329  if( rc ) return rc;
56330  rc = sqlite3PagerWrite(pPage->pDbPage);
56331  if( rc ) return rc;
56332  rc = clearCell(pPage, pCell);
56333  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
56334  if( rc ) return rc;
56335
56336  /* If the cell deleted was not located on a leaf page, then the cursor
56337  ** is currently pointing to the largest entry in the sub-tree headed
56338  ** by the child-page of the cell that was just deleted from an internal
56339  ** node. The cell from the leaf node needs to be moved to the internal
56340  ** node to replace the deleted cell.  */
56341  if( !pPage->leaf ){
56342    MemPage *pLeaf = pCur->apPage[pCur->iPage];
56343    int nCell;
56344    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
56345    unsigned char *pTmp;
56346
56347    pCell = findCell(pLeaf, pLeaf->nCell-1);
56348    nCell = cellSizePtr(pLeaf, pCell);
56349    assert( MX_CELL_SIZE(pBt) >= nCell );
56350
56351    allocateTempSpace(pBt);
56352    pTmp = pBt->pTmpSpace;
56353
56354    rc = sqlite3PagerWrite(pLeaf->pDbPage);
56355    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
56356    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
56357    if( rc ) return rc;
56358  }
56359
56360  /* Balance the tree. If the entry deleted was located on a leaf page,
56361  ** then the cursor still points to that page. In this case the first
56362  ** call to balance() repairs the tree, and the if(...) condition is
56363  ** never true.
56364  **
56365  ** Otherwise, if the entry deleted was on an internal node page, then
56366  ** pCur is pointing to the leaf page from which a cell was removed to
56367  ** replace the cell deleted from the internal node. This is slightly
56368  ** tricky as the leaf node may be underfull, and the internal node may
56369  ** be either under or overfull. In this case run the balancing algorithm
56370  ** on the leaf node first. If the balance proceeds far enough up the
56371  ** tree that we can be sure that any problem in the internal node has
56372  ** been corrected, so be it. Otherwise, after balancing the leaf node,
56373  ** walk the cursor up the tree to the internal node and balance it as
56374  ** well.  */
56375  rc = balance(pCur);
56376  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
56377    while( pCur->iPage>iCellDepth ){
56378      releasePage(pCur->apPage[pCur->iPage--]);
56379    }
56380    rc = balance(pCur);
56381  }
56382
56383  if( rc==SQLITE_OK ){
56384    moveToRoot(pCur);
56385  }
56386  return rc;
56387}
56388
56389/*
56390** Create a new BTree table.  Write into *piTable the page
56391** number for the root page of the new table.
56392**
56393** The type of type is determined by the flags parameter.  Only the
56394** following values of flags are currently in use.  Other values for
56395** flags might not work:
56396**
56397**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
56398**     BTREE_ZERODATA                  Used for SQL indices
56399*/
56400static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
56401  BtShared *pBt = p->pBt;
56402  MemPage *pRoot;
56403  Pgno pgnoRoot;
56404  int rc;
56405  int ptfFlags;          /* Page-type flage for the root page of new table */
56406
56407  assert( sqlite3BtreeHoldsMutex(p) );
56408  assert( pBt->inTransaction==TRANS_WRITE );
56409  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56410
56411#ifdef SQLITE_OMIT_AUTOVACUUM
56412  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56413  if( rc ){
56414    return rc;
56415  }
56416#else
56417  if( pBt->autoVacuum ){
56418    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
56419    MemPage *pPageMove; /* The page to move to. */
56420
56421    /* Creating a new table may probably require moving an existing database
56422    ** to make room for the new tables root page. In case this page turns
56423    ** out to be an overflow page, delete all overflow page-map caches
56424    ** held by open cursors.
56425    */
56426    invalidateAllOverflowCache(pBt);
56427
56428    /* Read the value of meta[3] from the database to determine where the
56429    ** root page of the new table should go. meta[3] is the largest root-page
56430    ** created so far, so the new root-page is (meta[3]+1).
56431    */
56432    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
56433    pgnoRoot++;
56434
56435    /* The new root-page may not be allocated on a pointer-map page, or the
56436    ** PENDING_BYTE page.
56437    */
56438    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
56439        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
56440      pgnoRoot++;
56441    }
56442    assert( pgnoRoot>=3 );
56443
56444    /* Allocate a page. The page that currently resides at pgnoRoot will
56445    ** be moved to the allocated page (unless the allocated page happens
56446    ** to reside at pgnoRoot).
56447    */
56448    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
56449    if( rc!=SQLITE_OK ){
56450      return rc;
56451    }
56452
56453    if( pgnoMove!=pgnoRoot ){
56454      /* pgnoRoot is the page that will be used for the root-page of
56455      ** the new table (assuming an error did not occur). But we were
56456      ** allocated pgnoMove. If required (i.e. if it was not allocated
56457      ** by extending the file), the current page at position pgnoMove
56458      ** is already journaled.
56459      */
56460      u8 eType = 0;
56461      Pgno iPtrPage = 0;
56462
56463      releasePage(pPageMove);
56464
56465      /* Move the page currently at pgnoRoot to pgnoMove. */
56466      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
56467      if( rc!=SQLITE_OK ){
56468        return rc;
56469      }
56470      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
56471      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
56472        rc = SQLITE_CORRUPT_BKPT;
56473      }
56474      if( rc!=SQLITE_OK ){
56475        releasePage(pRoot);
56476        return rc;
56477      }
56478      assert( eType!=PTRMAP_ROOTPAGE );
56479      assert( eType!=PTRMAP_FREEPAGE );
56480      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
56481      releasePage(pRoot);
56482
56483      /* Obtain the page at pgnoRoot */
56484      if( rc!=SQLITE_OK ){
56485        return rc;
56486      }
56487      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
56488      if( rc!=SQLITE_OK ){
56489        return rc;
56490      }
56491      rc = sqlite3PagerWrite(pRoot->pDbPage);
56492      if( rc!=SQLITE_OK ){
56493        releasePage(pRoot);
56494        return rc;
56495      }
56496    }else{
56497      pRoot = pPageMove;
56498    }
56499
56500    /* Update the pointer-map and meta-data with the new root-page number. */
56501    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
56502    if( rc ){
56503      releasePage(pRoot);
56504      return rc;
56505    }
56506
56507    /* When the new root page was allocated, page 1 was made writable in
56508    ** order either to increase the database filesize, or to decrement the
56509    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
56510    */
56511    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
56512    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
56513    if( NEVER(rc) ){
56514      releasePage(pRoot);
56515      return rc;
56516    }
56517
56518  }else{
56519    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56520    if( rc ) return rc;
56521  }
56522#endif
56523  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
56524  if( createTabFlags & BTREE_INTKEY ){
56525    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
56526  }else{
56527    ptfFlags = PTF_ZERODATA | PTF_LEAF;
56528  }
56529  zeroPage(pRoot, ptfFlags);
56530  sqlite3PagerUnref(pRoot->pDbPage);
56531  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
56532  *piTable = (int)pgnoRoot;
56533  return SQLITE_OK;
56534}
56535SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
56536  int rc;
56537  sqlite3BtreeEnter(p);
56538  rc = btreeCreateTable(p, piTable, flags);
56539  sqlite3BtreeLeave(p);
56540  return rc;
56541}
56542
56543/*
56544** Erase the given database page and all its children.  Return
56545** the page to the freelist.
56546*/
56547static int clearDatabasePage(
56548  BtShared *pBt,           /* The BTree that contains the table */
56549  Pgno pgno,               /* Page number to clear */
56550  int freePageFlag,        /* Deallocate page if true */
56551  int *pnChange            /* Add number of Cells freed to this counter */
56552){
56553  MemPage *pPage;
56554  int rc;
56555  unsigned char *pCell;
56556  int i;
56557
56558  assert( sqlite3_mutex_held(pBt->mutex) );
56559  if( pgno>btreePagecount(pBt) ){
56560    return SQLITE_CORRUPT_BKPT;
56561  }
56562
56563  rc = getAndInitPage(pBt, pgno, &pPage);
56564  if( rc ) return rc;
56565  for(i=0; i<pPage->nCell; i++){
56566    pCell = findCell(pPage, i);
56567    if( !pPage->leaf ){
56568      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
56569      if( rc ) goto cleardatabasepage_out;
56570    }
56571    rc = clearCell(pPage, pCell);
56572    if( rc ) goto cleardatabasepage_out;
56573  }
56574  if( !pPage->leaf ){
56575    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
56576    if( rc ) goto cleardatabasepage_out;
56577  }else if( pnChange ){
56578    assert( pPage->intKey );
56579    *pnChange += pPage->nCell;
56580  }
56581  if( freePageFlag ){
56582    freePage(pPage, &rc);
56583  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
56584    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
56585  }
56586
56587cleardatabasepage_out:
56588  releasePage(pPage);
56589  return rc;
56590}
56591
56592/*
56593** Delete all information from a single table in the database.  iTable is
56594** the page number of the root of the table.  After this routine returns,
56595** the root page is empty, but still exists.
56596**
56597** This routine will fail with SQLITE_LOCKED if there are any open
56598** read cursors on the table.  Open write cursors are moved to the
56599** root of the table.
56600**
56601** If pnChange is not NULL, then table iTable must be an intkey table. The
56602** integer value pointed to by pnChange is incremented by the number of
56603** entries in the table.
56604*/
56605SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
56606  int rc;
56607  BtShared *pBt = p->pBt;
56608  sqlite3BtreeEnter(p);
56609  assert( p->inTrans==TRANS_WRITE );
56610
56611  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
56612  ** is the root of a table b-tree - if it is not, the following call is
56613  ** a no-op).  */
56614  invalidateIncrblobCursors(p, 0, 1);
56615
56616  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
56617  if( SQLITE_OK==rc ){
56618    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
56619  }
56620  sqlite3BtreeLeave(p);
56621  return rc;
56622}
56623
56624/*
56625** Erase all information in a table and add the root of the table to
56626** the freelist.  Except, the root of the principle table (the one on
56627** page 1) is never added to the freelist.
56628**
56629** This routine will fail with SQLITE_LOCKED if there are any open
56630** cursors on the table.
56631**
56632** If AUTOVACUUM is enabled and the page at iTable is not the last
56633** root page in the database file, then the last root page
56634** in the database file is moved into the slot formerly occupied by
56635** iTable and that last slot formerly occupied by the last root page
56636** is added to the freelist instead of iTable.  In this say, all
56637** root pages are kept at the beginning of the database file, which
56638** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
56639** page number that used to be the last root page in the file before
56640** the move.  If no page gets moved, *piMoved is set to 0.
56641** The last root page is recorded in meta[3] and the value of
56642** meta[3] is updated by this procedure.
56643*/
56644static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
56645  int rc;
56646  MemPage *pPage = 0;
56647  BtShared *pBt = p->pBt;
56648
56649  assert( sqlite3BtreeHoldsMutex(p) );
56650  assert( p->inTrans==TRANS_WRITE );
56651
56652  /* It is illegal to drop a table if any cursors are open on the
56653  ** database. This is because in auto-vacuum mode the backend may
56654  ** need to move another root-page to fill a gap left by the deleted
56655  ** root page. If an open cursor was using this page a problem would
56656  ** occur.
56657  **
56658  ** This error is caught long before control reaches this point.
56659  */
56660  if( NEVER(pBt->pCursor) ){
56661    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
56662    return SQLITE_LOCKED_SHAREDCACHE;
56663  }
56664
56665  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
56666  if( rc ) return rc;
56667  rc = sqlite3BtreeClearTable(p, iTable, 0);
56668  if( rc ){
56669    releasePage(pPage);
56670    return rc;
56671  }
56672
56673  *piMoved = 0;
56674
56675  if( iTable>1 ){
56676#ifdef SQLITE_OMIT_AUTOVACUUM
56677    freePage(pPage, &rc);
56678    releasePage(pPage);
56679#else
56680    if( pBt->autoVacuum ){
56681      Pgno maxRootPgno;
56682      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
56683
56684      if( iTable==maxRootPgno ){
56685        /* If the table being dropped is the table with the largest root-page
56686        ** number in the database, put the root page on the free list.
56687        */
56688        freePage(pPage, &rc);
56689        releasePage(pPage);
56690        if( rc!=SQLITE_OK ){
56691          return rc;
56692        }
56693      }else{
56694        /* The table being dropped does not have the largest root-page
56695        ** number in the database. So move the page that does into the
56696        ** gap left by the deleted root-page.
56697        */
56698        MemPage *pMove;
56699        releasePage(pPage);
56700        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
56701        if( rc!=SQLITE_OK ){
56702          return rc;
56703        }
56704        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
56705        releasePage(pMove);
56706        if( rc!=SQLITE_OK ){
56707          return rc;
56708        }
56709        pMove = 0;
56710        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
56711        freePage(pMove, &rc);
56712        releasePage(pMove);
56713        if( rc!=SQLITE_OK ){
56714          return rc;
56715        }
56716        *piMoved = maxRootPgno;
56717      }
56718
56719      /* Set the new 'max-root-page' value in the database header. This
56720      ** is the old value less one, less one more if that happens to
56721      ** be a root-page number, less one again if that is the
56722      ** PENDING_BYTE_PAGE.
56723      */
56724      maxRootPgno--;
56725      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
56726             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
56727        maxRootPgno--;
56728      }
56729      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
56730
56731      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
56732    }else{
56733      freePage(pPage, &rc);
56734      releasePage(pPage);
56735    }
56736#endif
56737  }else{
56738    /* If sqlite3BtreeDropTable was called on page 1.
56739    ** This really never should happen except in a corrupt
56740    ** database.
56741    */
56742    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
56743    releasePage(pPage);
56744  }
56745  return rc;
56746}
56747SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
56748  int rc;
56749  sqlite3BtreeEnter(p);
56750  rc = btreeDropTable(p, iTable, piMoved);
56751  sqlite3BtreeLeave(p);
56752  return rc;
56753}
56754
56755
56756/*
56757** This function may only be called if the b-tree connection already
56758** has a read or write transaction open on the database.
56759**
56760** Read the meta-information out of a database file.  Meta[0]
56761** is the number of free pages currently in the database.  Meta[1]
56762** through meta[15] are available for use by higher layers.  Meta[0]
56763** is read-only, the others are read/write.
56764**
56765** The schema layer numbers meta values differently.  At the schema
56766** layer (and the SetCookie and ReadCookie opcodes) the number of
56767** free pages is not visible.  So Cookie[0] is the same as Meta[1].
56768*/
56769SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
56770  BtShared *pBt = p->pBt;
56771
56772  sqlite3BtreeEnter(p);
56773  assert( p->inTrans>TRANS_NONE );
56774  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
56775  assert( pBt->pPage1 );
56776  assert( idx>=0 && idx<=15 );
56777
56778  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
56779
56780  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
56781  ** database, mark the database as read-only.  */
56782#ifdef SQLITE_OMIT_AUTOVACUUM
56783  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
56784    pBt->btsFlags |= BTS_READ_ONLY;
56785  }
56786#endif
56787
56788  sqlite3BtreeLeave(p);
56789}
56790
56791/*
56792** Write meta-information back into the database.  Meta[0] is
56793** read-only and may not be written.
56794*/
56795SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
56796  BtShared *pBt = p->pBt;
56797  unsigned char *pP1;
56798  int rc;
56799  assert( idx>=1 && idx<=15 );
56800  sqlite3BtreeEnter(p);
56801  assert( p->inTrans==TRANS_WRITE );
56802  assert( pBt->pPage1!=0 );
56803  pP1 = pBt->pPage1->aData;
56804  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56805  if( rc==SQLITE_OK ){
56806    put4byte(&pP1[36 + idx*4], iMeta);
56807#ifndef SQLITE_OMIT_AUTOVACUUM
56808    if( idx==BTREE_INCR_VACUUM ){
56809      assert( pBt->autoVacuum || iMeta==0 );
56810      assert( iMeta==0 || iMeta==1 );
56811      pBt->incrVacuum = (u8)iMeta;
56812    }
56813#endif
56814  }
56815  sqlite3BtreeLeave(p);
56816  return rc;
56817}
56818
56819#ifndef SQLITE_OMIT_BTREECOUNT
56820/*
56821** The first argument, pCur, is a cursor opened on some b-tree. Count the
56822** number of entries in the b-tree and write the result to *pnEntry.
56823**
56824** SQLITE_OK is returned if the operation is successfully executed.
56825** Otherwise, if an error is encountered (i.e. an IO error or database
56826** corruption) an SQLite error code is returned.
56827*/
56828SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
56829  i64 nEntry = 0;                      /* Value to return in *pnEntry */
56830  int rc;                              /* Return code */
56831
56832  if( pCur->pgnoRoot==0 ){
56833    *pnEntry = 0;
56834    return SQLITE_OK;
56835  }
56836  rc = moveToRoot(pCur);
56837
56838  /* Unless an error occurs, the following loop runs one iteration for each
56839  ** page in the B-Tree structure (not including overflow pages).
56840  */
56841  while( rc==SQLITE_OK ){
56842    int iIdx;                          /* Index of child node in parent */
56843    MemPage *pPage;                    /* Current page of the b-tree */
56844
56845    /* If this is a leaf page or the tree is not an int-key tree, then
56846    ** this page contains countable entries. Increment the entry counter
56847    ** accordingly.
56848    */
56849    pPage = pCur->apPage[pCur->iPage];
56850    if( pPage->leaf || !pPage->intKey ){
56851      nEntry += pPage->nCell;
56852    }
56853
56854    /* pPage is a leaf node. This loop navigates the cursor so that it
56855    ** points to the first interior cell that it points to the parent of
56856    ** the next page in the tree that has not yet been visited. The
56857    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
56858    ** of the page, or to the number of cells in the page if the next page
56859    ** to visit is the right-child of its parent.
56860    **
56861    ** If all pages in the tree have been visited, return SQLITE_OK to the
56862    ** caller.
56863    */
56864    if( pPage->leaf ){
56865      do {
56866        if( pCur->iPage==0 ){
56867          /* All pages of the b-tree have been visited. Return successfully. */
56868          *pnEntry = nEntry;
56869          return SQLITE_OK;
56870        }
56871        moveToParent(pCur);
56872      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
56873
56874      pCur->aiIdx[pCur->iPage]++;
56875      pPage = pCur->apPage[pCur->iPage];
56876    }
56877
56878    /* Descend to the child node of the cell that the cursor currently
56879    ** points at. This is the right-child if (iIdx==pPage->nCell).
56880    */
56881    iIdx = pCur->aiIdx[pCur->iPage];
56882    if( iIdx==pPage->nCell ){
56883      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
56884    }else{
56885      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
56886    }
56887  }
56888
56889  /* An error has occurred. Return an error code. */
56890  return rc;
56891}
56892#endif
56893
56894/*
56895** Return the pager associated with a BTree.  This routine is used for
56896** testing and debugging only.
56897*/
56898SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
56899  return p->pBt->pPager;
56900}
56901
56902#ifndef SQLITE_OMIT_INTEGRITY_CHECK
56903/*
56904** Append a message to the error message string.
56905*/
56906static void checkAppendMsg(
56907  IntegrityCk *pCheck,
56908  char *zMsg1,
56909  const char *zFormat,
56910  ...
56911){
56912  va_list ap;
56913  if( !pCheck->mxErr ) return;
56914  pCheck->mxErr--;
56915  pCheck->nErr++;
56916  va_start(ap, zFormat);
56917  if( pCheck->errMsg.nChar ){
56918    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
56919  }
56920  if( zMsg1 ){
56921    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
56922  }
56923  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
56924  va_end(ap);
56925  if( pCheck->errMsg.mallocFailed ){
56926    pCheck->mallocFailed = 1;
56927  }
56928}
56929#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56930
56931#ifndef SQLITE_OMIT_INTEGRITY_CHECK
56932/*
56933** Add 1 to the reference count for page iPage.  If this is the second
56934** reference to the page, add an error message to pCheck->zErrMsg.
56935** Return 1 if there are 2 ore more references to the page and 0 if
56936** if this is the first reference to the page.
56937**
56938** Also check that the page number is in bounds.
56939*/
56940static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
56941  if( iPage==0 ) return 1;
56942  if( iPage>pCheck->nPage ){
56943    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
56944    return 1;
56945  }
56946  if( pCheck->anRef[iPage]==1 ){
56947    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
56948    return 1;
56949  }
56950  return  (pCheck->anRef[iPage]++)>1;
56951}
56952
56953#ifndef SQLITE_OMIT_AUTOVACUUM
56954/*
56955** Check that the entry in the pointer-map for page iChild maps to
56956** page iParent, pointer type ptrType. If not, append an error message
56957** to pCheck.
56958*/
56959static void checkPtrmap(
56960  IntegrityCk *pCheck,   /* Integrity check context */
56961  Pgno iChild,           /* Child page number */
56962  u8 eType,              /* Expected pointer map type */
56963  Pgno iParent,          /* Expected pointer map parent page number */
56964  char *zContext         /* Context description (used for error msg) */
56965){
56966  int rc;
56967  u8 ePtrmapType;
56968  Pgno iPtrmapParent;
56969
56970  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
56971  if( rc!=SQLITE_OK ){
56972    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
56973    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
56974    return;
56975  }
56976
56977  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
56978    checkAppendMsg(pCheck, zContext,
56979      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
56980      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
56981  }
56982}
56983#endif
56984
56985/*
56986** Check the integrity of the freelist or of an overflow page list.
56987** Verify that the number of pages on the list is N.
56988*/
56989static void checkList(
56990  IntegrityCk *pCheck,  /* Integrity checking context */
56991  int isFreeList,       /* True for a freelist.  False for overflow page list */
56992  int iPage,            /* Page number for first page in the list */
56993  int N,                /* Expected number of pages in the list */
56994  char *zContext        /* Context for error messages */
56995){
56996  int i;
56997  int expected = N;
56998  int iFirst = iPage;
56999  while( N-- > 0 && pCheck->mxErr ){
57000    DbPage *pOvflPage;
57001    unsigned char *pOvflData;
57002    if( iPage<1 ){
57003      checkAppendMsg(pCheck, zContext,
57004         "%d of %d pages missing from overflow list starting at %d",
57005          N+1, expected, iFirst);
57006      break;
57007    }
57008    if( checkRef(pCheck, iPage, zContext) ) break;
57009    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
57010      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
57011      break;
57012    }
57013    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
57014    if( isFreeList ){
57015      int n = get4byte(&pOvflData[4]);
57016#ifndef SQLITE_OMIT_AUTOVACUUM
57017      if( pCheck->pBt->autoVacuum ){
57018        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
57019      }
57020#endif
57021      if( n>(int)pCheck->pBt->usableSize/4-2 ){
57022        checkAppendMsg(pCheck, zContext,
57023           "freelist leaf count too big on page %d", iPage);
57024        N--;
57025      }else{
57026        for(i=0; i<n; i++){
57027          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
57028#ifndef SQLITE_OMIT_AUTOVACUUM
57029          if( pCheck->pBt->autoVacuum ){
57030            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
57031          }
57032#endif
57033          checkRef(pCheck, iFreePage, zContext);
57034        }
57035        N -= n;
57036      }
57037    }
57038#ifndef SQLITE_OMIT_AUTOVACUUM
57039    else{
57040      /* If this database supports auto-vacuum and iPage is not the last
57041      ** page in this overflow list, check that the pointer-map entry for
57042      ** the following page matches iPage.
57043      */
57044      if( pCheck->pBt->autoVacuum && N>0 ){
57045        i = get4byte(pOvflData);
57046        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
57047      }
57048    }
57049#endif
57050    iPage = get4byte(pOvflData);
57051    sqlite3PagerUnref(pOvflPage);
57052  }
57053}
57054#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57055
57056#ifndef SQLITE_OMIT_INTEGRITY_CHECK
57057/*
57058** Do various sanity checks on a single page of a tree.  Return
57059** the tree depth.  Root pages return 0.  Parents of root pages
57060** return 1, and so forth.
57061**
57062** These checks are done:
57063**
57064**      1.  Make sure that cells and freeblocks do not overlap
57065**          but combine to completely cover the page.
57066**  NO  2.  Make sure cell keys are in order.
57067**  NO  3.  Make sure no key is less than or equal to zLowerBound.
57068**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
57069**      5.  Check the integrity of overflow pages.
57070**      6.  Recursively call checkTreePage on all children.
57071**      7.  Verify that the depth of all children is the same.
57072**      8.  Make sure this page is at least 33% full or else it is
57073**          the root of the tree.
57074*/
57075static int checkTreePage(
57076  IntegrityCk *pCheck,  /* Context for the sanity check */
57077  int iPage,            /* Page number of the page to check */
57078  char *zParentContext, /* Parent context */
57079  i64 *pnParentMinKey,
57080  i64 *pnParentMaxKey
57081){
57082  MemPage *pPage;
57083  int i, rc, depth, d2, pgno, cnt;
57084  int hdr, cellStart;
57085  int nCell;
57086  u8 *data;
57087  BtShared *pBt;
57088  int usableSize;
57089  char zContext[100];
57090  char *hit = 0;
57091  i64 nMinKey = 0;
57092  i64 nMaxKey = 0;
57093
57094  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
57095
57096  /* Check that the page exists
57097  */
57098  pBt = pCheck->pBt;
57099  usableSize = pBt->usableSize;
57100  if( iPage==0 ) return 0;
57101  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
57102  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
57103    checkAppendMsg(pCheck, zContext,
57104       "unable to get the page. error code=%d", rc);
57105    return 0;
57106  }
57107
57108  /* Clear MemPage.isInit to make sure the corruption detection code in
57109  ** btreeInitPage() is executed.  */
57110  pPage->isInit = 0;
57111  if( (rc = btreeInitPage(pPage))!=0 ){
57112    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
57113    checkAppendMsg(pCheck, zContext,
57114                   "btreeInitPage() returns error code %d", rc);
57115    releasePage(pPage);
57116    return 0;
57117  }
57118
57119  /* Check out all the cells.
57120  */
57121  depth = 0;
57122  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
57123    u8 *pCell;
57124    u32 sz;
57125    CellInfo info;
57126
57127    /* Check payload overflow pages
57128    */
57129    sqlite3_snprintf(sizeof(zContext), zContext,
57130             "On tree page %d cell %d: ", iPage, i);
57131    pCell = findCell(pPage,i);
57132    btreeParseCellPtr(pPage, pCell, &info);
57133    sz = info.nData;
57134    if( !pPage->intKey ) sz += (int)info.nKey;
57135    /* For intKey pages, check that the keys are in order.
57136    */
57137    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
57138    else{
57139      if( info.nKey <= nMaxKey ){
57140        checkAppendMsg(pCheck, zContext,
57141            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
57142      }
57143      nMaxKey = info.nKey;
57144    }
57145    assert( sz==info.nPayload );
57146    if( (sz>info.nLocal)
57147     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
57148    ){
57149      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
57150      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
57151#ifndef SQLITE_OMIT_AUTOVACUUM
57152      if( pBt->autoVacuum ){
57153        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
57154      }
57155#endif
57156      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
57157    }
57158
57159    /* Check sanity of left child page.
57160    */
57161    if( !pPage->leaf ){
57162      pgno = get4byte(pCell);
57163#ifndef SQLITE_OMIT_AUTOVACUUM
57164      if( pBt->autoVacuum ){
57165        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57166      }
57167#endif
57168      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
57169      if( i>0 && d2!=depth ){
57170        checkAppendMsg(pCheck, zContext, "Child page depth differs");
57171      }
57172      depth = d2;
57173    }
57174  }
57175
57176  if( !pPage->leaf ){
57177    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57178    sqlite3_snprintf(sizeof(zContext), zContext,
57179                     "On page %d at right child: ", iPage);
57180#ifndef SQLITE_OMIT_AUTOVACUUM
57181    if( pBt->autoVacuum ){
57182      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57183    }
57184#endif
57185    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
57186  }
57187
57188  /* For intKey leaf pages, check that the min/max keys are in order
57189  ** with any left/parent/right pages.
57190  */
57191  if( pPage->leaf && pPage->intKey ){
57192    /* if we are a left child page */
57193    if( pnParentMinKey ){
57194      /* if we are the left most child page */
57195      if( !pnParentMaxKey ){
57196        if( nMaxKey > *pnParentMinKey ){
57197          checkAppendMsg(pCheck, zContext,
57198              "Rowid %lld out of order (max larger than parent min of %lld)",
57199              nMaxKey, *pnParentMinKey);
57200        }
57201      }else{
57202        if( nMinKey <= *pnParentMinKey ){
57203          checkAppendMsg(pCheck, zContext,
57204              "Rowid %lld out of order (min less than parent min of %lld)",
57205              nMinKey, *pnParentMinKey);
57206        }
57207        if( nMaxKey > *pnParentMaxKey ){
57208          checkAppendMsg(pCheck, zContext,
57209              "Rowid %lld out of order (max larger than parent max of %lld)",
57210              nMaxKey, *pnParentMaxKey);
57211        }
57212        *pnParentMinKey = nMaxKey;
57213      }
57214    /* else if we're a right child page */
57215    } else if( pnParentMaxKey ){
57216      if( nMinKey <= *pnParentMaxKey ){
57217        checkAppendMsg(pCheck, zContext,
57218            "Rowid %lld out of order (min less than parent max of %lld)",
57219            nMinKey, *pnParentMaxKey);
57220      }
57221    }
57222  }
57223
57224  /* Check for complete coverage of the page
57225  */
57226  data = pPage->aData;
57227  hdr = pPage->hdrOffset;
57228  hit = sqlite3PageMalloc( pBt->pageSize );
57229  if( hit==0 ){
57230    pCheck->mallocFailed = 1;
57231  }else{
57232    int contentOffset = get2byteNotZero(&data[hdr+5]);
57233    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
57234    memset(hit+contentOffset, 0, usableSize-contentOffset);
57235    memset(hit, 1, contentOffset);
57236    nCell = get2byte(&data[hdr+3]);
57237    cellStart = hdr + 12 - 4*pPage->leaf;
57238    for(i=0; i<nCell; i++){
57239      int pc = get2byte(&data[cellStart+i*2]);
57240      u32 size = 65536;
57241      int j;
57242      if( pc<=usableSize-4 ){
57243        size = cellSizePtr(pPage, &data[pc]);
57244      }
57245      if( (int)(pc+size-1)>=usableSize ){
57246        checkAppendMsg(pCheck, 0,
57247            "Corruption detected in cell %d on page %d",i,iPage);
57248      }else{
57249        for(j=pc+size-1; j>=pc; j--) hit[j]++;
57250      }
57251    }
57252    i = get2byte(&data[hdr+1]);
57253    while( i>0 ){
57254      int size, j;
57255      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
57256      size = get2byte(&data[i+2]);
57257      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
57258      for(j=i+size-1; j>=i; j--) hit[j]++;
57259      j = get2byte(&data[i]);
57260      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
57261      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
57262      i = j;
57263    }
57264    for(i=cnt=0; i<usableSize; i++){
57265      if( hit[i]==0 ){
57266        cnt++;
57267      }else if( hit[i]>1 ){
57268        checkAppendMsg(pCheck, 0,
57269          "Multiple uses for byte %d of page %d", i, iPage);
57270        break;
57271      }
57272    }
57273    if( cnt!=data[hdr+7] ){
57274      checkAppendMsg(pCheck, 0,
57275          "Fragmentation of %d bytes reported as %d on page %d",
57276          cnt, data[hdr+7], iPage);
57277    }
57278  }
57279  sqlite3PageFree(hit);
57280  releasePage(pPage);
57281  return depth+1;
57282}
57283#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57284
57285#ifndef SQLITE_OMIT_INTEGRITY_CHECK
57286/*
57287** This routine does a complete check of the given BTree file.  aRoot[] is
57288** an array of pages numbers were each page number is the root page of
57289** a table.  nRoot is the number of entries in aRoot.
57290**
57291** A read-only or read-write transaction must be opened before calling
57292** this function.
57293**
57294** Write the number of error seen in *pnErr.  Except for some memory
57295** allocation errors,  an error message held in memory obtained from
57296** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
57297** returned.  If a memory allocation error occurs, NULL is returned.
57298*/
57299SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
57300  Btree *p,     /* The btree to be checked */
57301  int *aRoot,   /* An array of root pages numbers for individual trees */
57302  int nRoot,    /* Number of entries in aRoot[] */
57303  int mxErr,    /* Stop reporting errors after this many */
57304  int *pnErr    /* Write number of errors seen to this variable */
57305){
57306  Pgno i;
57307  int nRef;
57308  IntegrityCk sCheck;
57309  BtShared *pBt = p->pBt;
57310  char zErr[100];
57311
57312  sqlite3BtreeEnter(p);
57313  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
57314  nRef = sqlite3PagerRefcount(pBt->pPager);
57315  sCheck.pBt = pBt;
57316  sCheck.pPager = pBt->pPager;
57317  sCheck.nPage = btreePagecount(sCheck.pBt);
57318  sCheck.mxErr = mxErr;
57319  sCheck.nErr = 0;
57320  sCheck.mallocFailed = 0;
57321  *pnErr = 0;
57322  if( sCheck.nPage==0 ){
57323    sqlite3BtreeLeave(p);
57324    return 0;
57325  }
57326  sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
57327  if( !sCheck.anRef ){
57328    *pnErr = 1;
57329    sqlite3BtreeLeave(p);
57330    return 0;
57331  }
57332  for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
57333  i = PENDING_BYTE_PAGE(pBt);
57334  if( i<=sCheck.nPage ){
57335    sCheck.anRef[i] = 1;
57336  }
57337  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
57338  sCheck.errMsg.useMalloc = 2;
57339
57340  /* Check the integrity of the freelist
57341  */
57342  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
57343            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
57344
57345  /* Check all the tables.
57346  */
57347  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
57348    if( aRoot[i]==0 ) continue;
57349#ifndef SQLITE_OMIT_AUTOVACUUM
57350    if( pBt->autoVacuum && aRoot[i]>1 ){
57351      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
57352    }
57353#endif
57354    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
57355  }
57356
57357  /* Make sure every page in the file is referenced
57358  */
57359  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
57360#ifdef SQLITE_OMIT_AUTOVACUUM
57361    if( sCheck.anRef[i]==0 ){
57362      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57363    }
57364#else
57365    /* If the database supports auto-vacuum, make sure no tables contain
57366    ** references to pointer-map pages.
57367    */
57368    if( sCheck.anRef[i]==0 &&
57369       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
57370      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57371    }
57372    if( sCheck.anRef[i]!=0 &&
57373       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
57374      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
57375    }
57376#endif
57377  }
57378
57379  /* Make sure this analysis did not leave any unref() pages.
57380  ** This is an internal consistency check; an integrity check
57381  ** of the integrity check.
57382  */
57383  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
57384    checkAppendMsg(&sCheck, 0,
57385      "Outstanding page count goes from %d to %d during this analysis",
57386      nRef, sqlite3PagerRefcount(pBt->pPager)
57387    );
57388  }
57389
57390  /* Clean  up and report errors.
57391  */
57392  sqlite3BtreeLeave(p);
57393  sqlite3_free(sCheck.anRef);
57394  if( sCheck.mallocFailed ){
57395    sqlite3StrAccumReset(&sCheck.errMsg);
57396    *pnErr = sCheck.nErr+1;
57397    return 0;
57398  }
57399  *pnErr = sCheck.nErr;
57400  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
57401  return sqlite3StrAccumFinish(&sCheck.errMsg);
57402}
57403#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57404
57405/*
57406** Return the full pathname of the underlying database file.
57407**
57408** The pager filename is invariant as long as the pager is
57409** open so it is safe to access without the BtShared mutex.
57410*/
57411SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
57412  assert( p->pBt->pPager!=0 );
57413  return sqlite3PagerFilename(p->pBt->pPager);
57414}
57415
57416/*
57417** Return the pathname of the journal file for this database. The return
57418** value of this routine is the same regardless of whether the journal file
57419** has been created or not.
57420**
57421** The pager journal filename is invariant as long as the pager is
57422** open so it is safe to access without the BtShared mutex.
57423*/
57424SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
57425  assert( p->pBt->pPager!=0 );
57426  return sqlite3PagerJournalname(p->pBt->pPager);
57427}
57428
57429/*
57430** Return non-zero if a transaction is active.
57431*/
57432SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
57433  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
57434  return (p && (p->inTrans==TRANS_WRITE));
57435}
57436
57437#ifndef SQLITE_OMIT_WAL
57438/*
57439** Run a checkpoint on the Btree passed as the first argument.
57440**
57441** Return SQLITE_LOCKED if this or any other connection has an open
57442** transaction on the shared-cache the argument Btree is connected to.
57443**
57444** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
57445*/
57446SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
57447  int rc = SQLITE_OK;
57448  if( p ){
57449    BtShared *pBt = p->pBt;
57450    sqlite3BtreeEnter(p);
57451    if( pBt->inTransaction!=TRANS_NONE ){
57452      rc = SQLITE_LOCKED;
57453    }else{
57454      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
57455    }
57456    sqlite3BtreeLeave(p);
57457  }
57458  return rc;
57459}
57460#endif
57461
57462/*
57463** Return non-zero if a read (or write) transaction is active.
57464*/
57465SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
57466  assert( p );
57467  assert( sqlite3_mutex_held(p->db->mutex) );
57468  return p->inTrans!=TRANS_NONE;
57469}
57470
57471SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
57472  assert( p );
57473  assert( sqlite3_mutex_held(p->db->mutex) );
57474  return p->nBackup!=0;
57475}
57476
57477/*
57478** This function returns a pointer to a blob of memory associated with
57479** a single shared-btree. The memory is used by client code for its own
57480** purposes (for example, to store a high-level schema associated with
57481** the shared-btree). The btree layer manages reference counting issues.
57482**
57483** The first time this is called on a shared-btree, nBytes bytes of memory
57484** are allocated, zeroed, and returned to the caller. For each subsequent
57485** call the nBytes parameter is ignored and a pointer to the same blob
57486** of memory returned.
57487**
57488** If the nBytes parameter is 0 and the blob of memory has not yet been
57489** allocated, a null pointer is returned. If the blob has already been
57490** allocated, it is returned as normal.
57491**
57492** Just before the shared-btree is closed, the function passed as the
57493** xFree argument when the memory allocation was made is invoked on the
57494** blob of allocated memory. The xFree function should not call sqlite3_free()
57495** on the memory, the btree layer does that.
57496*/
57497SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
57498  BtShared *pBt = p->pBt;
57499  sqlite3BtreeEnter(p);
57500  if( !pBt->pSchema && nBytes ){
57501    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
57502    pBt->xFreeSchema = xFree;
57503  }
57504  sqlite3BtreeLeave(p);
57505  return pBt->pSchema;
57506}
57507
57508/*
57509** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
57510** btree as the argument handle holds an exclusive lock on the
57511** sqlite_master table. Otherwise SQLITE_OK.
57512*/
57513SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
57514  int rc;
57515  assert( sqlite3_mutex_held(p->db->mutex) );
57516  sqlite3BtreeEnter(p);
57517  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
57518  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
57519  sqlite3BtreeLeave(p);
57520  return rc;
57521}
57522
57523
57524#ifndef SQLITE_OMIT_SHARED_CACHE
57525/*
57526** Obtain a lock on the table whose root page is iTab.  The
57527** lock is a write lock if isWritelock is true or a read lock
57528** if it is false.
57529*/
57530SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
57531  int rc = SQLITE_OK;
57532  assert( p->inTrans!=TRANS_NONE );
57533  if( p->sharable ){
57534    u8 lockType = READ_LOCK + isWriteLock;
57535    assert( READ_LOCK+1==WRITE_LOCK );
57536    assert( isWriteLock==0 || isWriteLock==1 );
57537
57538    sqlite3BtreeEnter(p);
57539    rc = querySharedCacheTableLock(p, iTab, lockType);
57540    if( rc==SQLITE_OK ){
57541      rc = setSharedCacheTableLock(p, iTab, lockType);
57542    }
57543    sqlite3BtreeLeave(p);
57544  }
57545  return rc;
57546}
57547#endif
57548
57549#ifndef SQLITE_OMIT_INCRBLOB
57550/*
57551** Argument pCsr must be a cursor opened for writing on an
57552** INTKEY table currently pointing at a valid table entry.
57553** This function modifies the data stored as part of that entry.
57554**
57555** Only the data content may only be modified, it is not possible to
57556** change the length of the data stored. If this function is called with
57557** parameters that attempt to write past the end of the existing data,
57558** no modifications are made and SQLITE_CORRUPT is returned.
57559*/
57560SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
57561  int rc;
57562  assert( cursorHoldsMutex(pCsr) );
57563  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
57564  assert( pCsr->isIncrblobHandle );
57565
57566  rc = restoreCursorPosition(pCsr);
57567  if( rc!=SQLITE_OK ){
57568    return rc;
57569  }
57570  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
57571  if( pCsr->eState!=CURSOR_VALID ){
57572    return SQLITE_ABORT;
57573  }
57574
57575  /* Check some assumptions:
57576  **   (a) the cursor is open for writing,
57577  **   (b) there is a read/write transaction open,
57578  **   (c) the connection holds a write-lock on the table (if required),
57579  **   (d) there are no conflicting read-locks, and
57580  **   (e) the cursor points at a valid row of an intKey table.
57581  */
57582  if( !pCsr->wrFlag ){
57583    return SQLITE_READONLY;
57584  }
57585  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
57586              && pCsr->pBt->inTransaction==TRANS_WRITE );
57587  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
57588  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
57589  assert( pCsr->apPage[pCsr->iPage]->intKey );
57590
57591  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
57592}
57593
57594/*
57595** Set a flag on this cursor to cache the locations of pages from the
57596** overflow list for the current row. This is used by cursors opened
57597** for incremental blob IO only.
57598**
57599** This function sets a flag only. The actual page location cache
57600** (stored in BtCursor.aOverflow[]) is allocated and used by function
57601** accessPayload() (the worker function for sqlite3BtreeData() and
57602** sqlite3BtreePutData()).
57603*/
57604SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
57605  assert( cursorHoldsMutex(pCur) );
57606  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57607  invalidateOverflowCache(pCur);
57608  pCur->isIncrblobHandle = 1;
57609}
57610#endif
57611
57612/*
57613** Set both the "read version" (single byte at byte offset 18) and
57614** "write version" (single byte at byte offset 19) fields in the database
57615** header to iVersion.
57616*/
57617SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
57618  BtShared *pBt = pBtree->pBt;
57619  int rc;                         /* Return code */
57620
57621  assert( iVersion==1 || iVersion==2 );
57622
57623  /* If setting the version fields to 1, do not automatically open the
57624  ** WAL connection, even if the version fields are currently set to 2.
57625  */
57626  pBt->btsFlags &= ~BTS_NO_WAL;
57627  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
57628
57629  rc = sqlite3BtreeBeginTrans(pBtree, 0);
57630  if( rc==SQLITE_OK ){
57631    u8 *aData = pBt->pPage1->aData;
57632    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
57633      rc = sqlite3BtreeBeginTrans(pBtree, 2);
57634      if( rc==SQLITE_OK ){
57635        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
57636        if( rc==SQLITE_OK ){
57637          aData[18] = (u8)iVersion;
57638          aData[19] = (u8)iVersion;
57639        }
57640      }
57641    }
57642  }
57643
57644  pBt->btsFlags &= ~BTS_NO_WAL;
57645  return rc;
57646}
57647
57648/************** End of btree.c ***********************************************/
57649/************** Begin file backup.c ******************************************/
57650/*
57651** 2009 January 28
57652**
57653** The author disclaims copyright to this source code.  In place of
57654** a legal notice, here is a blessing:
57655**
57656**    May you do good and not evil.
57657**    May you find forgiveness for yourself and forgive others.
57658**    May you share freely, never taking more than you give.
57659**
57660*************************************************************************
57661** This file contains the implementation of the sqlite3_backup_XXX()
57662** API functions and the related features.
57663*/
57664
57665/* Macro to find the minimum of two numeric values.
57666*/
57667#ifndef MIN
57668# define MIN(x,y) ((x)<(y)?(x):(y))
57669#endif
57670
57671/*
57672** Structure allocated for each backup operation.
57673*/
57674struct sqlite3_backup {
57675  sqlite3* pDestDb;        /* Destination database handle */
57676  Btree *pDest;            /* Destination b-tree file */
57677  u32 iDestSchema;         /* Original schema cookie in destination */
57678  int bDestLocked;         /* True once a write-transaction is open on pDest */
57679
57680  Pgno iNext;              /* Page number of the next source page to copy */
57681  sqlite3* pSrcDb;         /* Source database handle */
57682  Btree *pSrc;             /* Source b-tree file */
57683
57684  int rc;                  /* Backup process error code */
57685
57686  /* These two variables are set by every call to backup_step(). They are
57687  ** read by calls to backup_remaining() and backup_pagecount().
57688  */
57689  Pgno nRemaining;         /* Number of pages left to copy */
57690  Pgno nPagecount;         /* Total number of pages to copy */
57691
57692  int isAttached;          /* True once backup has been registered with pager */
57693  sqlite3_backup *pNext;   /* Next backup associated with source pager */
57694};
57695
57696/*
57697** THREAD SAFETY NOTES:
57698**
57699**   Once it has been created using backup_init(), a single sqlite3_backup
57700**   structure may be accessed via two groups of thread-safe entry points:
57701**
57702**     * Via the sqlite3_backup_XXX() API function backup_step() and
57703**       backup_finish(). Both these functions obtain the source database
57704**       handle mutex and the mutex associated with the source BtShared
57705**       structure, in that order.
57706**
57707**     * Via the BackupUpdate() and BackupRestart() functions, which are
57708**       invoked by the pager layer to report various state changes in
57709**       the page cache associated with the source database. The mutex
57710**       associated with the source database BtShared structure will always
57711**       be held when either of these functions are invoked.
57712**
57713**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
57714**   backup_pagecount() are not thread-safe functions. If they are called
57715**   while some other thread is calling backup_step() or backup_finish(),
57716**   the values returned may be invalid. There is no way for a call to
57717**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
57718**   or backup_pagecount().
57719**
57720**   Depending on the SQLite configuration, the database handles and/or
57721**   the Btree objects may have their own mutexes that require locking.
57722**   Non-sharable Btrees (in-memory databases for example), do not have
57723**   associated mutexes.
57724*/
57725
57726/*
57727** Return a pointer corresponding to database zDb (i.e. "main", "temp")
57728** in connection handle pDb. If such a database cannot be found, return
57729** a NULL pointer and write an error message to pErrorDb.
57730**
57731** If the "temp" database is requested, it may need to be opened by this
57732** function. If an error occurs while doing so, return 0 and write an
57733** error message to pErrorDb.
57734*/
57735static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
57736  int i = sqlite3FindDbName(pDb, zDb);
57737
57738  if( i==1 ){
57739    Parse *pParse;
57740    int rc = 0;
57741    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
57742    if( pParse==0 ){
57743      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
57744      rc = SQLITE_NOMEM;
57745    }else{
57746      pParse->db = pDb;
57747      if( sqlite3OpenTempDatabase(pParse) ){
57748        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
57749        rc = SQLITE_ERROR;
57750      }
57751      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
57752      sqlite3StackFree(pErrorDb, pParse);
57753    }
57754    if( rc ){
57755      return 0;
57756    }
57757  }
57758
57759  if( i<0 ){
57760    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
57761    return 0;
57762  }
57763
57764  return pDb->aDb[i].pBt;
57765}
57766
57767/*
57768** Attempt to set the page size of the destination to match the page size
57769** of the source.
57770*/
57771static int setDestPgsz(sqlite3_backup *p){
57772  int rc;
57773  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
57774  return rc;
57775}
57776
57777/*
57778** Create an sqlite3_backup process to copy the contents of zSrcDb from
57779** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
57780** a pointer to the new sqlite3_backup object.
57781**
57782** If an error occurs, NULL is returned and an error code and error message
57783** stored in database handle pDestDb.
57784*/
57785SQLITE_API sqlite3_backup *sqlite3_backup_init(
57786  sqlite3* pDestDb,                     /* Database to write to */
57787  const char *zDestDb,                  /* Name of database within pDestDb */
57788  sqlite3* pSrcDb,                      /* Database connection to read from */
57789  const char *zSrcDb                    /* Name of database within pSrcDb */
57790){
57791  sqlite3_backup *p;                    /* Value to return */
57792
57793  /* Lock the source database handle. The destination database
57794  ** handle is not locked in this routine, but it is locked in
57795  ** sqlite3_backup_step(). The user is required to ensure that no
57796  ** other thread accesses the destination handle for the duration
57797  ** of the backup operation.  Any attempt to use the destination
57798  ** database connection while a backup is in progress may cause
57799  ** a malfunction or a deadlock.
57800  */
57801  sqlite3_mutex_enter(pSrcDb->mutex);
57802  sqlite3_mutex_enter(pDestDb->mutex);
57803
57804  if( pSrcDb==pDestDb ){
57805    sqlite3Error(
57806        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
57807    );
57808    p = 0;
57809  }else {
57810    /* Allocate space for a new sqlite3_backup object...
57811    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
57812    ** call to sqlite3_backup_init() and is destroyed by a call to
57813    ** sqlite3_backup_finish(). */
57814    p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
57815    if( !p ){
57816      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
57817    }
57818  }
57819
57820  /* If the allocation succeeded, populate the new object. */
57821  if( p ){
57822    memset(p, 0, sizeof(sqlite3_backup));
57823    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
57824    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
57825    p->pDestDb = pDestDb;
57826    p->pSrcDb = pSrcDb;
57827    p->iNext = 1;
57828    p->isAttached = 0;
57829
57830    if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
57831      /* One (or both) of the named databases did not exist or an OOM
57832      ** error was hit.  The error has already been written into the
57833      ** pDestDb handle.  All that is left to do here is free the
57834      ** sqlite3_backup structure.
57835      */
57836      sqlite3_free(p);
57837      p = 0;
57838    }
57839  }
57840  if( p ){
57841    p->pSrc->nBackup++;
57842  }
57843
57844  sqlite3_mutex_leave(pDestDb->mutex);
57845  sqlite3_mutex_leave(pSrcDb->mutex);
57846  return p;
57847}
57848
57849/*
57850** Argument rc is an SQLite error code. Return true if this error is
57851** considered fatal if encountered during a backup operation. All errors
57852** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
57853*/
57854static int isFatalError(int rc){
57855  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
57856}
57857
57858/*
57859** Parameter zSrcData points to a buffer containing the data for
57860** page iSrcPg from the source database. Copy this data into the
57861** destination database.
57862*/
57863static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
57864  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
57865  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
57866  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
57867  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
57868  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
57869#ifdef SQLITE_HAS_CODEC
57870  int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
57871  int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
57872#endif
57873
57874  int rc = SQLITE_OK;
57875  i64 iOff;
57876
57877  assert( p->bDestLocked );
57878  assert( !isFatalError(p->rc) );
57879  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
57880  assert( zSrcData );
57881
57882  /* Catch the case where the destination is an in-memory database and the
57883  ** page sizes of the source and destination differ.
57884  */
57885  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
57886    rc = SQLITE_READONLY;
57887  }
57888
57889#ifdef SQLITE_HAS_CODEC
57890  /* Backup is not possible if the page size of the destination is changing
57891  ** and a codec is in use.
57892  */
57893  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
57894    rc = SQLITE_READONLY;
57895  }
57896
57897  /* Backup is not possible if the number of bytes of reserve space differ
57898  ** between source and destination.  If there is a difference, try to
57899  ** fix the destination to agree with the source.  If that is not possible,
57900  ** then the backup cannot proceed.
57901  */
57902  if( nSrcReserve!=nDestReserve ){
57903    u32 newPgsz = nSrcPgsz;
57904    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
57905    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
57906  }
57907#endif
57908
57909  /* This loop runs once for each destination page spanned by the source
57910  ** page. For each iteration, variable iOff is set to the byte offset
57911  ** of the destination page.
57912  */
57913  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
57914    DbPage *pDestPg = 0;
57915    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
57916    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
57917    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
57918     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
57919    ){
57920      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
57921      u8 *zDestData = sqlite3PagerGetData(pDestPg);
57922      u8 *zOut = &zDestData[iOff%nDestPgsz];
57923
57924      /* Copy the data from the source page into the destination page.
57925      ** Then clear the Btree layer MemPage.isInit flag. Both this module
57926      ** and the pager code use this trick (clearing the first byte
57927      ** of the page 'extra' space to invalidate the Btree layers
57928      ** cached parse of the page). MemPage.isInit is marked
57929      ** "MUST BE FIRST" for this purpose.
57930      */
57931      memcpy(zOut, zIn, nCopy);
57932      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
57933    }
57934    sqlite3PagerUnref(pDestPg);
57935  }
57936
57937  return rc;
57938}
57939
57940/*
57941** If pFile is currently larger than iSize bytes, then truncate it to
57942** exactly iSize bytes. If pFile is not larger than iSize bytes, then
57943** this function is a no-op.
57944**
57945** Return SQLITE_OK if everything is successful, or an SQLite error
57946** code if an error occurs.
57947*/
57948static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
57949  i64 iCurrent;
57950  int rc = sqlite3OsFileSize(pFile, &iCurrent);
57951  if( rc==SQLITE_OK && iCurrent>iSize ){
57952    rc = sqlite3OsTruncate(pFile, iSize);
57953  }
57954  return rc;
57955}
57956
57957/*
57958** Register this backup object with the associated source pager for
57959** callbacks when pages are changed or the cache invalidated.
57960*/
57961static void attachBackupObject(sqlite3_backup *p){
57962  sqlite3_backup **pp;
57963  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
57964  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
57965  p->pNext = *pp;
57966  *pp = p;
57967  p->isAttached = 1;
57968}
57969
57970/*
57971** Copy nPage pages from the source b-tree to the destination.
57972*/
57973SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
57974  int rc;
57975  int destMode;       /* Destination journal mode */
57976  int pgszSrc = 0;    /* Source page size */
57977  int pgszDest = 0;   /* Destination page size */
57978
57979  sqlite3_mutex_enter(p->pSrcDb->mutex);
57980  sqlite3BtreeEnter(p->pSrc);
57981  if( p->pDestDb ){
57982    sqlite3_mutex_enter(p->pDestDb->mutex);
57983  }
57984
57985  rc = p->rc;
57986  if( !isFatalError(rc) ){
57987    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
57988    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
57989    int ii;                            /* Iterator variable */
57990    int nSrcPage = -1;                 /* Size of source db in pages */
57991    int bCloseTrans = 0;               /* True if src db requires unlocking */
57992
57993    /* If the source pager is currently in a write-transaction, return
57994    ** SQLITE_BUSY immediately.
57995    */
57996    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
57997      rc = SQLITE_BUSY;
57998    }else{
57999      rc = SQLITE_OK;
58000    }
58001
58002    /* Lock the destination database, if it is not locked already. */
58003    if( SQLITE_OK==rc && p->bDestLocked==0
58004     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
58005    ){
58006      p->bDestLocked = 1;
58007      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
58008    }
58009
58010    /* If there is no open read-transaction on the source database, open
58011    ** one now. If a transaction is opened here, then it will be closed
58012    ** before this function exits.
58013    */
58014    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
58015      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
58016      bCloseTrans = 1;
58017    }
58018
58019    /* Do not allow backup if the destination database is in WAL mode
58020    ** and the page sizes are different between source and destination */
58021    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
58022    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
58023    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
58024    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
58025      rc = SQLITE_READONLY;
58026    }
58027
58028    /* Now that there is a read-lock on the source database, query the
58029    ** source pager for the number of pages in the database.
58030    */
58031    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
58032    assert( nSrcPage>=0 );
58033    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
58034      const Pgno iSrcPg = p->iNext;                 /* Source page number */
58035      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
58036        DbPage *pSrcPg;                             /* Source page object */
58037        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58038        if( rc==SQLITE_OK ){
58039          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
58040          sqlite3PagerUnref(pSrcPg);
58041        }
58042      }
58043      p->iNext++;
58044    }
58045    if( rc==SQLITE_OK ){
58046      p->nPagecount = nSrcPage;
58047      p->nRemaining = nSrcPage+1-p->iNext;
58048      if( p->iNext>(Pgno)nSrcPage ){
58049        rc = SQLITE_DONE;
58050      }else if( !p->isAttached ){
58051        attachBackupObject(p);
58052      }
58053    }
58054
58055    /* Update the schema version field in the destination database. This
58056    ** is to make sure that the schema-version really does change in
58057    ** the case where the source and destination databases have the
58058    ** same schema version.
58059    */
58060    if( rc==SQLITE_DONE ){
58061      rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
58062      if( rc==SQLITE_OK ){
58063        if( p->pDestDb ){
58064          sqlite3ResetInternalSchema(p->pDestDb, -1);
58065        }
58066        if( destMode==PAGER_JOURNALMODE_WAL ){
58067          rc = sqlite3BtreeSetVersion(p->pDest, 2);
58068        }
58069      }
58070      if( rc==SQLITE_OK ){
58071        int nDestTruncate;
58072        /* Set nDestTruncate to the final number of pages in the destination
58073        ** database. The complication here is that the destination page
58074        ** size may be different to the source page size.
58075        **
58076        ** If the source page size is smaller than the destination page size,
58077        ** round up. In this case the call to sqlite3OsTruncate() below will
58078        ** fix the size of the file. However it is important to call
58079        ** sqlite3PagerTruncateImage() here so that any pages in the
58080        ** destination file that lie beyond the nDestTruncate page mark are
58081        ** journalled by PagerCommitPhaseOne() before they are destroyed
58082        ** by the file truncation.
58083        */
58084        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
58085        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
58086        if( pgszSrc<pgszDest ){
58087          int ratio = pgszDest/pgszSrc;
58088          nDestTruncate = (nSrcPage+ratio-1)/ratio;
58089          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
58090            nDestTruncate--;
58091          }
58092        }else{
58093          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
58094        }
58095        sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
58096
58097        if( pgszSrc<pgszDest ){
58098          /* If the source page-size is smaller than the destination page-size,
58099          ** two extra things may need to happen:
58100          **
58101          **   * The destination may need to be truncated, and
58102          **
58103          **   * Data stored on the pages immediately following the
58104          **     pending-byte page in the source database may need to be
58105          **     copied into the destination database.
58106          */
58107          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
58108          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
58109          i64 iOff;
58110          i64 iEnd;
58111
58112          assert( pFile );
58113          assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
58114                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
58115             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
58116          ));
58117
58118          /* This call ensures that all data required to recreate the original
58119          ** database has been stored in the journal for pDestPager and the
58120          ** journal synced to disk. So at this point we may safely modify
58121          ** the database file in any way, knowing that if a power failure
58122          ** occurs, the original database will be reconstructed from the
58123          ** journal file.  */
58124          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
58125
58126          /* Write the extra pages and truncate the database file as required */
58127          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
58128          for(
58129            iOff=PENDING_BYTE+pgszSrc;
58130            rc==SQLITE_OK && iOff<iEnd;
58131            iOff+=pgszSrc
58132          ){
58133            PgHdr *pSrcPg = 0;
58134            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
58135            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58136            if( rc==SQLITE_OK ){
58137              u8 *zData = sqlite3PagerGetData(pSrcPg);
58138              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
58139            }
58140            sqlite3PagerUnref(pSrcPg);
58141          }
58142          if( rc==SQLITE_OK ){
58143            rc = backupTruncateFile(pFile, iSize);
58144          }
58145
58146          /* Sync the database file to disk. */
58147          if( rc==SQLITE_OK ){
58148            rc = sqlite3PagerSync(pDestPager);
58149          }
58150        }else{
58151          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
58152        }
58153
58154        /* Finish committing the transaction to the destination database. */
58155        if( SQLITE_OK==rc
58156         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
58157        ){
58158          rc = SQLITE_DONE;
58159        }
58160      }
58161    }
58162
58163    /* If bCloseTrans is true, then this function opened a read transaction
58164    ** on the source database. Close the read transaction here. There is
58165    ** no need to check the return values of the btree methods here, as
58166    ** "committing" a read-only transaction cannot fail.
58167    */
58168    if( bCloseTrans ){
58169      TESTONLY( int rc2 );
58170      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
58171      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
58172      assert( rc2==SQLITE_OK );
58173    }
58174
58175    if( rc==SQLITE_IOERR_NOMEM ){
58176      rc = SQLITE_NOMEM;
58177    }
58178    p->rc = rc;
58179  }
58180  if( p->pDestDb ){
58181    sqlite3_mutex_leave(p->pDestDb->mutex);
58182  }
58183  sqlite3BtreeLeave(p->pSrc);
58184  sqlite3_mutex_leave(p->pSrcDb->mutex);
58185  return rc;
58186}
58187
58188/*
58189** Release all resources associated with an sqlite3_backup* handle.
58190*/
58191SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
58192  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
58193  MUTEX_LOGIC( sqlite3_mutex *mutex; ) /* Mutex to protect source database */
58194  int rc;                              /* Value to return */
58195
58196  /* Enter the mutexes */
58197  if( p==0 ) return SQLITE_OK;
58198  sqlite3_mutex_enter(p->pSrcDb->mutex);
58199  sqlite3BtreeEnter(p->pSrc);
58200  MUTEX_LOGIC( mutex = p->pSrcDb->mutex; )
58201  if( p->pDestDb ){
58202    sqlite3_mutex_enter(p->pDestDb->mutex);
58203  }
58204
58205  /* Detach this backup from the source pager. */
58206  if( p->pDestDb ){
58207    p->pSrc->nBackup--;
58208  }
58209  if( p->isAttached ){
58210    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
58211    while( *pp!=p ){
58212      pp = &(*pp)->pNext;
58213    }
58214    *pp = p->pNext;
58215  }
58216
58217  /* If a transaction is still open on the Btree, roll it back. */
58218  sqlite3BtreeRollback(p->pDest, SQLITE_OK);
58219
58220  /* Set the error code of the destination database handle. */
58221  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
58222  sqlite3Error(p->pDestDb, rc, 0);
58223
58224  /* Exit the mutexes and free the backup context structure. */
58225  if( p->pDestDb ){
58226    sqlite3_mutex_leave(p->pDestDb->mutex);
58227  }
58228  sqlite3BtreeLeave(p->pSrc);
58229  if( p->pDestDb ){
58230    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
58231    ** call to sqlite3_backup_init() and is destroyed by a call to
58232    ** sqlite3_backup_finish(). */
58233    sqlite3_free(p);
58234  }
58235  sqlite3_mutex_leave(mutex);
58236  return rc;
58237}
58238
58239/*
58240** Return the number of pages still to be backed up as of the most recent
58241** call to sqlite3_backup_step().
58242*/
58243SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
58244  return p->nRemaining;
58245}
58246
58247/*
58248** Return the total number of pages in the source database as of the most
58249** recent call to sqlite3_backup_step().
58250*/
58251SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
58252  return p->nPagecount;
58253}
58254
58255/*
58256** This function is called after the contents of page iPage of the
58257** source database have been modified. If page iPage has already been
58258** copied into the destination database, then the data written to the
58259** destination is now invalidated. The destination copy of iPage needs
58260** to be updated with the new data before the backup operation is
58261** complete.
58262**
58263** It is assumed that the mutex associated with the BtShared object
58264** corresponding to the source database is held when this function is
58265** called.
58266*/
58267SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
58268  sqlite3_backup *p;                   /* Iterator variable */
58269  for(p=pBackup; p; p=p->pNext){
58270    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
58271    if( !isFatalError(p->rc) && iPage<p->iNext ){
58272      /* The backup process p has already copied page iPage. But now it
58273      ** has been modified by a transaction on the source pager. Copy
58274      ** the new data into the backup.
58275      */
58276      int rc;
58277      assert( p->pDestDb );
58278      sqlite3_mutex_enter(p->pDestDb->mutex);
58279      rc = backupOnePage(p, iPage, aData);
58280      sqlite3_mutex_leave(p->pDestDb->mutex);
58281      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
58282      if( rc!=SQLITE_OK ){
58283        p->rc = rc;
58284      }
58285    }
58286  }
58287}
58288
58289/*
58290** Restart the backup process. This is called when the pager layer
58291** detects that the database has been modified by an external database
58292** connection. In this case there is no way of knowing which of the
58293** pages that have been copied into the destination database are still
58294** valid and which are not, so the entire process needs to be restarted.
58295**
58296** It is assumed that the mutex associated with the BtShared object
58297** corresponding to the source database is held when this function is
58298** called.
58299*/
58300SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
58301  sqlite3_backup *p;                   /* Iterator variable */
58302  for(p=pBackup; p; p=p->pNext){
58303    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
58304    p->iNext = 1;
58305  }
58306}
58307
58308#ifndef SQLITE_OMIT_VACUUM
58309/*
58310** Copy the complete content of pBtFrom into pBtTo.  A transaction
58311** must be active for both files.
58312**
58313** The size of file pTo may be reduced by this operation. If anything
58314** goes wrong, the transaction on pTo is rolled back. If successful, the
58315** transaction is committed before returning.
58316*/
58317SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
58318  int rc;
58319  sqlite3_file *pFd;              /* File descriptor for database pTo */
58320  sqlite3_backup b;
58321  sqlite3BtreeEnter(pTo);
58322  sqlite3BtreeEnter(pFrom);
58323
58324  assert( sqlite3BtreeIsInTrans(pTo) );
58325  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
58326  if( pFd->pMethods ){
58327    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
58328    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
58329    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
58330    if( rc ) goto copy_finished;
58331  }
58332
58333  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
58334  ** to 0. This is used by the implementations of sqlite3_backup_step()
58335  ** and sqlite3_backup_finish() to detect that they are being called
58336  ** from this function, not directly by the user.
58337  */
58338  memset(&b, 0, sizeof(b));
58339  b.pSrcDb = pFrom->db;
58340  b.pSrc = pFrom;
58341  b.pDest = pTo;
58342  b.iNext = 1;
58343
58344  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
58345  ** file. By passing this as the number of pages to copy to
58346  ** sqlite3_backup_step(), we can guarantee that the copy finishes
58347  ** within a single call (unless an error occurs). The assert() statement
58348  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
58349  ** or an error code.
58350  */
58351  sqlite3_backup_step(&b, 0x7FFFFFFF);
58352  assert( b.rc!=SQLITE_OK );
58353  rc = sqlite3_backup_finish(&b);
58354  if( rc==SQLITE_OK ){
58355    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
58356  }else{
58357    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
58358  }
58359
58360  assert( sqlite3BtreeIsInTrans(pTo)==0 );
58361copy_finished:
58362  sqlite3BtreeLeave(pFrom);
58363  sqlite3BtreeLeave(pTo);
58364  return rc;
58365}
58366#endif /* SQLITE_OMIT_VACUUM */
58367
58368/************** End of backup.c **********************************************/
58369/************** Begin file vdbemem.c *****************************************/
58370/*
58371** 2004 May 26
58372**
58373** The author disclaims copyright to this source code.  In place of
58374** a legal notice, here is a blessing:
58375**
58376**    May you do good and not evil.
58377**    May you find forgiveness for yourself and forgive others.
58378**    May you share freely, never taking more than you give.
58379**
58380*************************************************************************
58381**
58382** This file contains code use to manipulate "Mem" structure.  A "Mem"
58383** stores a single value in the VDBE.  Mem is an opaque structure visible
58384** only within the VDBE.  Interface routines refer to a Mem using the
58385** name sqlite_value
58386*/
58387
58388/*
58389** If pMem is an object with a valid string representation, this routine
58390** ensures the internal encoding for the string representation is
58391** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
58392**
58393** If pMem is not a string object, or the encoding of the string
58394** representation is already stored using the requested encoding, then this
58395** routine is a no-op.
58396**
58397** SQLITE_OK is returned if the conversion is successful (or not required).
58398** SQLITE_NOMEM may be returned if a malloc() fails during conversion
58399** between formats.
58400*/
58401SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
58402  int rc;
58403  assert( (pMem->flags&MEM_RowSet)==0 );
58404  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
58405           || desiredEnc==SQLITE_UTF16BE );
58406  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
58407    return SQLITE_OK;
58408  }
58409  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58410#ifdef SQLITE_OMIT_UTF16
58411  return SQLITE_ERROR;
58412#else
58413
58414  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
58415  ** then the encoding of the value may not have changed.
58416  */
58417  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
58418  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
58419  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
58420  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
58421  return rc;
58422#endif
58423}
58424
58425/*
58426** Make sure pMem->z points to a writable allocation of at least
58427** n bytes.
58428**
58429** If the memory cell currently contains string or blob data
58430** and the third argument passed to this function is true, the
58431** current content of the cell is preserved. Otherwise, it may
58432** be discarded.
58433**
58434** This function sets the MEM_Dyn flag and clears any xDel callback.
58435** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
58436** not set, Mem.n is zeroed.
58437*/
58438SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
58439  assert( 1 >=
58440    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
58441    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
58442    ((pMem->flags&MEM_Ephem) ? 1 : 0) +
58443    ((pMem->flags&MEM_Static) ? 1 : 0)
58444  );
58445  assert( (pMem->flags&MEM_RowSet)==0 );
58446
58447  if( n<32 ) n = 32;
58448  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
58449    if( preserve && pMem->z==pMem->zMalloc ){
58450      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
58451      preserve = 0;
58452    }else{
58453      sqlite3DbFree(pMem->db, pMem->zMalloc);
58454      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
58455    }
58456  }
58457
58458  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
58459    memcpy(pMem->zMalloc, pMem->z, pMem->n);
58460  }
58461  if( pMem->flags&MEM_Dyn && pMem->xDel ){
58462    assert( pMem->xDel!=SQLITE_DYNAMIC );
58463    pMem->xDel((void *)(pMem->z));
58464  }
58465
58466  pMem->z = pMem->zMalloc;
58467  if( pMem->z==0 ){
58468    pMem->flags = MEM_Null;
58469  }else{
58470    pMem->flags &= ~(MEM_Ephem|MEM_Static);
58471  }
58472  pMem->xDel = 0;
58473  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
58474}
58475
58476/*
58477** Make the given Mem object MEM_Dyn.  In other words, make it so
58478** that any TEXT or BLOB content is stored in memory obtained from
58479** malloc().  In this way, we know that the memory is safe to be
58480** overwritten or altered.
58481**
58482** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
58483*/
58484SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
58485  int f;
58486  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58487  assert( (pMem->flags&MEM_RowSet)==0 );
58488  ExpandBlob(pMem);
58489  f = pMem->flags;
58490  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
58491    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
58492      return SQLITE_NOMEM;
58493    }
58494    pMem->z[pMem->n] = 0;
58495    pMem->z[pMem->n+1] = 0;
58496    pMem->flags |= MEM_Term;
58497#ifdef SQLITE_DEBUG
58498    pMem->pScopyFrom = 0;
58499#endif
58500  }
58501
58502  return SQLITE_OK;
58503}
58504
58505/*
58506** If the given Mem* has a zero-filled tail, turn it into an ordinary
58507** blob stored in dynamically allocated space.
58508*/
58509#ifndef SQLITE_OMIT_INCRBLOB
58510SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
58511  if( pMem->flags & MEM_Zero ){
58512    int nByte;
58513    assert( pMem->flags&MEM_Blob );
58514    assert( (pMem->flags&MEM_RowSet)==0 );
58515    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58516
58517    /* Set nByte to the number of bytes required to store the expanded blob. */
58518    nByte = pMem->n + pMem->u.nZero;
58519    if( nByte<=0 ){
58520      nByte = 1;
58521    }
58522    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
58523      return SQLITE_NOMEM;
58524    }
58525
58526    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
58527    pMem->n += pMem->u.nZero;
58528    pMem->flags &= ~(MEM_Zero|MEM_Term);
58529  }
58530  return SQLITE_OK;
58531}
58532#endif
58533
58534
58535/*
58536** Make sure the given Mem is \u0000 terminated.
58537*/
58538SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
58539  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58540  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
58541    return SQLITE_OK;   /* Nothing to do */
58542  }
58543  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
58544    return SQLITE_NOMEM;
58545  }
58546  pMem->z[pMem->n] = 0;
58547  pMem->z[pMem->n+1] = 0;
58548  pMem->flags |= MEM_Term;
58549  return SQLITE_OK;
58550}
58551
58552/*
58553** Add MEM_Str to the set of representations for the given Mem.  Numbers
58554** are converted using sqlite3_snprintf().  Converting a BLOB to a string
58555** is a no-op.
58556**
58557** Existing representations MEM_Int and MEM_Real are *not* invalidated.
58558**
58559** A MEM_Null value will never be passed to this function. This function is
58560** used for converting values to text for returning to the user (i.e. via
58561** sqlite3_value_text()), or for ensuring that values to be used as btree
58562** keys are strings. In the former case a NULL pointer is returned the
58563** user and the later is an internal programming error.
58564*/
58565SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
58566  int rc = SQLITE_OK;
58567  int fg = pMem->flags;
58568  const int nByte = 32;
58569
58570  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58571  assert( !(fg&MEM_Zero) );
58572  assert( !(fg&(MEM_Str|MEM_Blob)) );
58573  assert( fg&(MEM_Int|MEM_Real) );
58574  assert( (pMem->flags&MEM_RowSet)==0 );
58575  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58576
58577
58578  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
58579    return SQLITE_NOMEM;
58580  }
58581
58582  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
58583  ** string representation of the value. Then, if the required encoding
58584  ** is UTF-16le or UTF-16be do a translation.
58585  **
58586  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
58587  */
58588  if( fg & MEM_Int ){
58589    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
58590  }else{
58591    assert( fg & MEM_Real );
58592    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
58593  }
58594  pMem->n = sqlite3Strlen30(pMem->z);
58595  pMem->enc = SQLITE_UTF8;
58596  pMem->flags |= MEM_Str|MEM_Term;
58597  sqlite3VdbeChangeEncoding(pMem, enc);
58598  return rc;
58599}
58600
58601/*
58602** Memory cell pMem contains the context of an aggregate function.
58603** This routine calls the finalize method for that function.  The
58604** result of the aggregate is stored back into pMem.
58605**
58606** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
58607** otherwise.
58608*/
58609SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
58610  int rc = SQLITE_OK;
58611  if( ALWAYS(pFunc && pFunc->xFinalize) ){
58612    sqlite3_context ctx;
58613    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
58614    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58615    memset(&ctx, 0, sizeof(ctx));
58616    ctx.s.flags = MEM_Null;
58617    ctx.s.db = pMem->db;
58618    ctx.pMem = pMem;
58619    ctx.pFunc = pFunc;
58620    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
58621    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
58622    sqlite3DbFree(pMem->db, pMem->zMalloc);
58623    memcpy(pMem, &ctx.s, sizeof(ctx.s));
58624    rc = ctx.isError;
58625  }
58626  return rc;
58627}
58628
58629/*
58630** If the memory cell contains a string value that must be freed by
58631** invoking an external callback, free it now. Calling this function
58632** does not free any Mem.zMalloc buffer.
58633*/
58634SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
58635  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
58636  if( p->flags&MEM_Agg ){
58637    sqlite3VdbeMemFinalize(p, p->u.pDef);
58638    assert( (p->flags & MEM_Agg)==0 );
58639    sqlite3VdbeMemRelease(p);
58640  }else if( p->flags&MEM_Dyn && p->xDel ){
58641    assert( (p->flags&MEM_RowSet)==0 );
58642    assert( p->xDel!=SQLITE_DYNAMIC );
58643    p->xDel((void *)p->z);
58644    p->xDel = 0;
58645  }else if( p->flags&MEM_RowSet ){
58646    sqlite3RowSetClear(p->u.pRowSet);
58647  }else if( p->flags&MEM_Frame ){
58648    sqlite3VdbeMemSetNull(p);
58649  }
58650}
58651
58652/*
58653** Release any memory held by the Mem. This may leave the Mem in an
58654** inconsistent state, for example with (Mem.z==0) and
58655** (Mem.type==SQLITE_TEXT).
58656*/
58657SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
58658  VdbeMemRelease(p);
58659  sqlite3DbFree(p->db, p->zMalloc);
58660  p->z = 0;
58661  p->zMalloc = 0;
58662  p->xDel = 0;
58663}
58664
58665/*
58666** Convert a 64-bit IEEE double into a 64-bit signed integer.
58667** If the double is too large, return 0x8000000000000000.
58668**
58669** Most systems appear to do this simply by assigning
58670** variables and without the extra range tests.  But
58671** there are reports that windows throws an expection
58672** if the floating point value is out of range. (See ticket #2880.)
58673** Because we do not completely understand the problem, we will
58674** take the conservative approach and always do range tests
58675** before attempting the conversion.
58676*/
58677static i64 doubleToInt64(double r){
58678#ifdef SQLITE_OMIT_FLOATING_POINT
58679  /* When floating-point is omitted, double and int64 are the same thing */
58680  return r;
58681#else
58682  /*
58683  ** Many compilers we encounter do not define constants for the
58684  ** minimum and maximum 64-bit integers, or they define them
58685  ** inconsistently.  And many do not understand the "LL" notation.
58686  ** So we define our own static constants here using nothing
58687  ** larger than a 32-bit integer constant.
58688  */
58689  static const i64 maxInt = LARGEST_INT64;
58690  static const i64 minInt = SMALLEST_INT64;
58691
58692  if( r<(double)minInt ){
58693    return minInt;
58694  }else if( r>(double)maxInt ){
58695    /* minInt is correct here - not maxInt.  It turns out that assigning
58696    ** a very large positive number to an integer results in a very large
58697    ** negative integer.  This makes no sense, but it is what x86 hardware
58698    ** does so for compatibility we will do the same in software. */
58699    return minInt;
58700  }else{
58701    return (i64)r;
58702  }
58703#endif
58704}
58705
58706/*
58707** Return some kind of integer value which is the best we can do
58708** at representing the value that *pMem describes as an integer.
58709** If pMem is an integer, then the value is exact.  If pMem is
58710** a floating-point then the value returned is the integer part.
58711** If pMem is a string or blob, then we make an attempt to convert
58712** it into a integer and return that.  If pMem represents an
58713** an SQL-NULL value, return 0.
58714**
58715** If pMem represents a string value, its encoding might be changed.
58716*/
58717SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
58718  int flags;
58719  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58720  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58721  flags = pMem->flags;
58722  if( flags & MEM_Int ){
58723    return pMem->u.i;
58724  }else if( flags & MEM_Real ){
58725    return doubleToInt64(pMem->r);
58726  }else if( flags & (MEM_Str|MEM_Blob) ){
58727    i64 value = 0;
58728    assert( pMem->z || pMem->n==0 );
58729    testcase( pMem->z==0 );
58730    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
58731    return value;
58732  }else{
58733    return 0;
58734  }
58735}
58736
58737/*
58738** Return the best representation of pMem that we can get into a
58739** double.  If pMem is already a double or an integer, return its
58740** value.  If it is a string or blob, try to convert it to a double.
58741** If it is a NULL, return 0.0.
58742*/
58743SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
58744  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58745  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58746  if( pMem->flags & MEM_Real ){
58747    return pMem->r;
58748  }else if( pMem->flags & MEM_Int ){
58749    return (double)pMem->u.i;
58750  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
58751    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
58752    double val = (double)0;
58753    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
58754    return val;
58755  }else{
58756    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
58757    return (double)0;
58758  }
58759}
58760
58761/*
58762** The MEM structure is already a MEM_Real.  Try to also make it a
58763** MEM_Int if we can.
58764*/
58765SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
58766  assert( pMem->flags & MEM_Real );
58767  assert( (pMem->flags & MEM_RowSet)==0 );
58768  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58769  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58770
58771  pMem->u.i = doubleToInt64(pMem->r);
58772
58773  /* Only mark the value as an integer if
58774  **
58775  **    (1) the round-trip conversion real->int->real is a no-op, and
58776  **    (2) The integer is neither the largest nor the smallest
58777  **        possible integer (ticket #3922)
58778  **
58779  ** The second and third terms in the following conditional enforces
58780  ** the second condition under the assumption that addition overflow causes
58781  ** values to wrap around.  On x86 hardware, the third term is always
58782  ** true and could be omitted.  But we leave it in because other
58783  ** architectures might behave differently.
58784  */
58785  if( pMem->r==(double)pMem->u.i
58786   && pMem->u.i>SMALLEST_INT64
58787#if defined(__i486__) || defined(__x86_64__)
58788   && ALWAYS(pMem->u.i<LARGEST_INT64)
58789#else
58790   && pMem->u.i<LARGEST_INT64
58791#endif
58792  ){
58793    pMem->flags |= MEM_Int;
58794  }
58795}
58796
58797/*
58798** Convert pMem to type integer.  Invalidate any prior representations.
58799*/
58800SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
58801  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58802  assert( (pMem->flags & MEM_RowSet)==0 );
58803  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58804
58805  pMem->u.i = sqlite3VdbeIntValue(pMem);
58806  MemSetTypeFlag(pMem, MEM_Int);
58807  return SQLITE_OK;
58808}
58809
58810/*
58811** Convert pMem so that it is of type MEM_Real.
58812** Invalidate any prior representations.
58813*/
58814SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
58815  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58816  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58817
58818  pMem->r = sqlite3VdbeRealValue(pMem);
58819  MemSetTypeFlag(pMem, MEM_Real);
58820  return SQLITE_OK;
58821}
58822
58823/*
58824** Convert pMem so that it has types MEM_Real or MEM_Int or both.
58825** Invalidate any prior representations.
58826**
58827** Every effort is made to force the conversion, even if the input
58828** is a string that does not look completely like a number.  Convert
58829** as much of the string as we can and ignore the rest.
58830*/
58831SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
58832  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
58833    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
58834    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58835    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
58836      MemSetTypeFlag(pMem, MEM_Int);
58837    }else{
58838      pMem->r = sqlite3VdbeRealValue(pMem);
58839      MemSetTypeFlag(pMem, MEM_Real);
58840      sqlite3VdbeIntegerAffinity(pMem);
58841    }
58842  }
58843  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
58844  pMem->flags &= ~(MEM_Str|MEM_Blob);
58845  return SQLITE_OK;
58846}
58847
58848/*
58849** Delete any previous value and set the value stored in *pMem to NULL.
58850*/
58851SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
58852  if( pMem->flags & MEM_Frame ){
58853    VdbeFrame *pFrame = pMem->u.pFrame;
58854    pFrame->pParent = pFrame->v->pDelFrame;
58855    pFrame->v->pDelFrame = pFrame;
58856  }
58857  if( pMem->flags & MEM_RowSet ){
58858    sqlite3RowSetClear(pMem->u.pRowSet);
58859  }
58860  MemSetTypeFlag(pMem, MEM_Null);
58861  pMem->type = SQLITE_NULL;
58862}
58863
58864/*
58865** Delete any previous value and set the value to be a BLOB of length
58866** n containing all zeros.
58867*/
58868SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
58869  sqlite3VdbeMemRelease(pMem);
58870  pMem->flags = MEM_Blob|MEM_Zero;
58871  pMem->type = SQLITE_BLOB;
58872  pMem->n = 0;
58873  if( n<0 ) n = 0;
58874  pMem->u.nZero = n;
58875  pMem->enc = SQLITE_UTF8;
58876
58877#ifdef SQLITE_OMIT_INCRBLOB
58878  sqlite3VdbeMemGrow(pMem, n, 0);
58879  if( pMem->z ){
58880    pMem->n = n;
58881    memset(pMem->z, 0, n);
58882  }
58883#endif
58884}
58885
58886/*
58887** Delete any previous value and set the value stored in *pMem to val,
58888** manifest type INTEGER.
58889*/
58890SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
58891  sqlite3VdbeMemRelease(pMem);
58892  pMem->u.i = val;
58893  pMem->flags = MEM_Int;
58894  pMem->type = SQLITE_INTEGER;
58895}
58896
58897#ifndef SQLITE_OMIT_FLOATING_POINT
58898/*
58899** Delete any previous value and set the value stored in *pMem to val,
58900** manifest type REAL.
58901*/
58902SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
58903  if( sqlite3IsNaN(val) ){
58904    sqlite3VdbeMemSetNull(pMem);
58905  }else{
58906    sqlite3VdbeMemRelease(pMem);
58907    pMem->r = val;
58908    pMem->flags = MEM_Real;
58909    pMem->type = SQLITE_FLOAT;
58910  }
58911}
58912#endif
58913
58914/*
58915** Delete any previous value and set the value of pMem to be an
58916** empty boolean index.
58917*/
58918SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
58919  sqlite3 *db = pMem->db;
58920  assert( db!=0 );
58921  assert( (pMem->flags & MEM_RowSet)==0 );
58922  sqlite3VdbeMemRelease(pMem);
58923  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
58924  if( db->mallocFailed ){
58925    pMem->flags = MEM_Null;
58926  }else{
58927    assert( pMem->zMalloc );
58928    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
58929                                       sqlite3DbMallocSize(db, pMem->zMalloc));
58930    assert( pMem->u.pRowSet!=0 );
58931    pMem->flags = MEM_RowSet;
58932  }
58933}
58934
58935/*
58936** Return true if the Mem object contains a TEXT or BLOB that is
58937** too large - whose size exceeds SQLITE_MAX_LENGTH.
58938*/
58939SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
58940  assert( p->db!=0 );
58941  if( p->flags & (MEM_Str|MEM_Blob) ){
58942    int n = p->n;
58943    if( p->flags & MEM_Zero ){
58944      n += p->u.nZero;
58945    }
58946    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
58947  }
58948  return 0;
58949}
58950
58951#ifdef SQLITE_DEBUG
58952/*
58953** This routine prepares a memory cell for modication by breaking
58954** its link to a shallow copy and by marking any current shallow
58955** copies of this cell as invalid.
58956**
58957** This is used for testing and debugging only - to make sure shallow
58958** copies are not misused.
58959*/
58960SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
58961  int i;
58962  Mem *pX;
58963  for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
58964    if( pX->pScopyFrom==pMem ){
58965      pX->flags |= MEM_Invalid;
58966      pX->pScopyFrom = 0;
58967    }
58968  }
58969  pMem->pScopyFrom = 0;
58970}
58971#endif /* SQLITE_DEBUG */
58972
58973/*
58974** Size of struct Mem not including the Mem.zMalloc member.
58975*/
58976#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
58977
58978/*
58979** Make an shallow copy of pFrom into pTo.  Prior contents of
58980** pTo are freed.  The pFrom->z field is not duplicated.  If
58981** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
58982** and flags gets srcType (either MEM_Ephem or MEM_Static).
58983*/
58984SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
58985  assert( (pFrom->flags & MEM_RowSet)==0 );
58986  VdbeMemRelease(pTo);
58987  memcpy(pTo, pFrom, MEMCELLSIZE);
58988  pTo->xDel = 0;
58989  if( (pFrom->flags&MEM_Static)==0 ){
58990    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
58991    assert( srcType==MEM_Ephem || srcType==MEM_Static );
58992    pTo->flags |= srcType;
58993  }
58994}
58995
58996/*
58997** Make a full copy of pFrom into pTo.  Prior contents of pTo are
58998** freed before the copy is made.
58999*/
59000SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
59001  int rc = SQLITE_OK;
59002
59003  assert( (pFrom->flags & MEM_RowSet)==0 );
59004  VdbeMemRelease(pTo);
59005  memcpy(pTo, pFrom, MEMCELLSIZE);
59006  pTo->flags &= ~MEM_Dyn;
59007
59008  if( pTo->flags&(MEM_Str|MEM_Blob) ){
59009    if( 0==(pFrom->flags&MEM_Static) ){
59010      pTo->flags |= MEM_Ephem;
59011      rc = sqlite3VdbeMemMakeWriteable(pTo);
59012    }
59013  }
59014
59015  return rc;
59016}
59017
59018/*
59019** Transfer the contents of pFrom to pTo. Any existing value in pTo is
59020** freed. If pFrom contains ephemeral data, a copy is made.
59021**
59022** pFrom contains an SQL NULL when this routine returns.
59023*/
59024SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
59025  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
59026  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
59027  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
59028
59029  sqlite3VdbeMemRelease(pTo);
59030  memcpy(pTo, pFrom, sizeof(Mem));
59031  pFrom->flags = MEM_Null;
59032  pFrom->xDel = 0;
59033  pFrom->zMalloc = 0;
59034}
59035
59036/*
59037** Change the value of a Mem to be a string or a BLOB.
59038**
59039** The memory management strategy depends on the value of the xDel
59040** parameter. If the value passed is SQLITE_TRANSIENT, then the
59041** string is copied into a (possibly existing) buffer managed by the
59042** Mem structure. Otherwise, any existing buffer is freed and the
59043** pointer copied.
59044**
59045** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
59046** size limit) then no memory allocation occurs.  If the string can be
59047** stored without allocating memory, then it is.  If a memory allocation
59048** is required to store the string, then value of pMem is unchanged.  In
59049** either case, SQLITE_TOOBIG is returned.
59050*/
59051SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
59052  Mem *pMem,          /* Memory cell to set to string value */
59053  const char *z,      /* String pointer */
59054  int n,              /* Bytes in string, or negative */
59055  u8 enc,             /* Encoding of z.  0 for BLOBs */
59056  void (*xDel)(void*) /* Destructor function */
59057){
59058  int nByte = n;      /* New value for pMem->n */
59059  int iLimit;         /* Maximum allowed string or blob size */
59060  u16 flags = 0;      /* New value for pMem->flags */
59061
59062  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59063  assert( (pMem->flags & MEM_RowSet)==0 );
59064
59065  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
59066  if( !z ){
59067    sqlite3VdbeMemSetNull(pMem);
59068    return SQLITE_OK;
59069  }
59070
59071  if( pMem->db ){
59072    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
59073  }else{
59074    iLimit = SQLITE_MAX_LENGTH;
59075  }
59076  flags = (enc==0?MEM_Blob:MEM_Str);
59077  if( nByte<0 ){
59078    assert( enc!=0 );
59079    if( enc==SQLITE_UTF8 ){
59080      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
59081    }else{
59082      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
59083    }
59084    flags |= MEM_Term;
59085  }
59086
59087  /* The following block sets the new values of Mem.z and Mem.xDel. It
59088  ** also sets a flag in local variable "flags" to indicate the memory
59089  ** management (one of MEM_Dyn or MEM_Static).
59090  */
59091  if( xDel==SQLITE_TRANSIENT ){
59092    int nAlloc = nByte;
59093    if( flags&MEM_Term ){
59094      nAlloc += (enc==SQLITE_UTF8?1:2);
59095    }
59096    if( nByte>iLimit ){
59097      return SQLITE_TOOBIG;
59098    }
59099    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
59100      return SQLITE_NOMEM;
59101    }
59102    memcpy(pMem->z, z, nAlloc);
59103  }else if( xDel==SQLITE_DYNAMIC ){
59104    sqlite3VdbeMemRelease(pMem);
59105    pMem->zMalloc = pMem->z = (char *)z;
59106    pMem->xDel = 0;
59107  }else{
59108    sqlite3VdbeMemRelease(pMem);
59109    pMem->z = (char *)z;
59110    pMem->xDel = xDel;
59111    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
59112  }
59113
59114  pMem->n = nByte;
59115  pMem->flags = flags;
59116  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
59117  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
59118
59119#ifndef SQLITE_OMIT_UTF16
59120  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
59121    return SQLITE_NOMEM;
59122  }
59123#endif
59124
59125  if( nByte>iLimit ){
59126    return SQLITE_TOOBIG;
59127  }
59128
59129  return SQLITE_OK;
59130}
59131
59132/*
59133** Compare the values contained by the two memory cells, returning
59134** negative, zero or positive if pMem1 is less than, equal to, or greater
59135** than pMem2. Sorting order is NULL's first, followed by numbers (integers
59136** and reals) sorted numerically, followed by text ordered by the collating
59137** sequence pColl and finally blob's ordered by memcmp().
59138**
59139** Two NULL values are considered equal by this function.
59140*/
59141SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
59142  int rc;
59143  int f1, f2;
59144  int combined_flags;
59145
59146  f1 = pMem1->flags;
59147  f2 = pMem2->flags;
59148  combined_flags = f1|f2;
59149  assert( (combined_flags & MEM_RowSet)==0 );
59150
59151  /* If one value is NULL, it is less than the other. If both values
59152  ** are NULL, return 0.
59153  */
59154  if( combined_flags&MEM_Null ){
59155    return (f2&MEM_Null) - (f1&MEM_Null);
59156  }
59157
59158  /* If one value is a number and the other is not, the number is less.
59159  ** If both are numbers, compare as reals if one is a real, or as integers
59160  ** if both values are integers.
59161  */
59162  if( combined_flags&(MEM_Int|MEM_Real) ){
59163    if( !(f1&(MEM_Int|MEM_Real)) ){
59164      return 1;
59165    }
59166    if( !(f2&(MEM_Int|MEM_Real)) ){
59167      return -1;
59168    }
59169    if( (f1 & f2 & MEM_Int)==0 ){
59170      double r1, r2;
59171      if( (f1&MEM_Real)==0 ){
59172        r1 = (double)pMem1->u.i;
59173      }else{
59174        r1 = pMem1->r;
59175      }
59176      if( (f2&MEM_Real)==0 ){
59177        r2 = (double)pMem2->u.i;
59178      }else{
59179        r2 = pMem2->r;
59180      }
59181      if( r1<r2 ) return -1;
59182      if( r1>r2 ) return 1;
59183      return 0;
59184    }else{
59185      assert( f1&MEM_Int );
59186      assert( f2&MEM_Int );
59187      if( pMem1->u.i < pMem2->u.i ) return -1;
59188      if( pMem1->u.i > pMem2->u.i ) return 1;
59189      return 0;
59190    }
59191  }
59192
59193  /* If one value is a string and the other is a blob, the string is less.
59194  ** If both are strings, compare using the collating functions.
59195  */
59196  if( combined_flags&MEM_Str ){
59197    if( (f1 & MEM_Str)==0 ){
59198      return 1;
59199    }
59200    if( (f2 & MEM_Str)==0 ){
59201      return -1;
59202    }
59203
59204    assert( pMem1->enc==pMem2->enc );
59205    assert( pMem1->enc==SQLITE_UTF8 ||
59206            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
59207
59208    /* The collation sequence must be defined at this point, even if
59209    ** the user deletes the collation sequence after the vdbe program is
59210    ** compiled (this was not always the case).
59211    */
59212    assert( !pColl || pColl->xCmp );
59213
59214    if( pColl ){
59215      if( pMem1->enc==pColl->enc ){
59216        /* The strings are already in the correct encoding.  Call the
59217        ** comparison function directly */
59218        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
59219      }else{
59220        const void *v1, *v2;
59221        int n1, n2;
59222        Mem c1;
59223        Mem c2;
59224        memset(&c1, 0, sizeof(c1));
59225        memset(&c2, 0, sizeof(c2));
59226        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
59227        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
59228        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
59229        n1 = v1==0 ? 0 : c1.n;
59230        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
59231        n2 = v2==0 ? 0 : c2.n;
59232        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
59233        sqlite3VdbeMemRelease(&c1);
59234        sqlite3VdbeMemRelease(&c2);
59235        return rc;
59236      }
59237    }
59238    /* If a NULL pointer was passed as the collate function, fall through
59239    ** to the blob case and use memcmp().  */
59240  }
59241
59242  /* Both values must be blobs.  Compare using memcmp().  */
59243  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
59244  if( rc==0 ){
59245    rc = pMem1->n - pMem2->n;
59246  }
59247  return rc;
59248}
59249
59250/*
59251** Move data out of a btree key or data field and into a Mem structure.
59252** The data or key is taken from the entry that pCur is currently pointing
59253** to.  offset and amt determine what portion of the data or key to retrieve.
59254** key is true to get the key or false to get data.  The result is written
59255** into the pMem element.
59256**
59257** The pMem structure is assumed to be uninitialized.  Any prior content
59258** is overwritten without being freed.
59259**
59260** If this routine fails for any reason (malloc returns NULL or unable
59261** to read from the disk) then the pMem is left in an inconsistent state.
59262*/
59263SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
59264  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
59265  int offset,       /* Offset from the start of data to return bytes from. */
59266  int amt,          /* Number of bytes to return. */
59267  int key,          /* If true, retrieve from the btree key, not data. */
59268  Mem *pMem         /* OUT: Return data in this Mem structure. */
59269){
59270  char *zData;        /* Data from the btree layer */
59271  int available = 0;  /* Number of bytes available on the local btree page */
59272  int rc = SQLITE_OK; /* Return code */
59273
59274  assert( sqlite3BtreeCursorIsValid(pCur) );
59275
59276  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
59277  ** that both the BtShared and database handle mutexes are held. */
59278  assert( (pMem->flags & MEM_RowSet)==0 );
59279  if( key ){
59280    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
59281  }else{
59282    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
59283  }
59284  assert( zData!=0 );
59285
59286  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
59287    sqlite3VdbeMemRelease(pMem);
59288    pMem->z = &zData[offset];
59289    pMem->flags = MEM_Blob|MEM_Ephem;
59290  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
59291    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
59292    pMem->enc = 0;
59293    pMem->type = SQLITE_BLOB;
59294    if( key ){
59295      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
59296    }else{
59297      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
59298    }
59299    pMem->z[amt] = 0;
59300    pMem->z[amt+1] = 0;
59301    if( rc!=SQLITE_OK ){
59302      sqlite3VdbeMemRelease(pMem);
59303    }
59304  }
59305  pMem->n = amt;
59306
59307  return rc;
59308}
59309
59310/* This function is only available internally, it is not part of the
59311** external API. It works in a similar way to sqlite3_value_text(),
59312** except the data returned is in the encoding specified by the second
59313** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
59314** SQLITE_UTF8.
59315**
59316** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
59317** If that is the case, then the result must be aligned on an even byte
59318** boundary.
59319*/
59320SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
59321  if( !pVal ) return 0;
59322
59323  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
59324  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
59325  assert( (pVal->flags & MEM_RowSet)==0 );
59326
59327  if( pVal->flags&MEM_Null ){
59328    return 0;
59329  }
59330  assert( (MEM_Blob>>3) == MEM_Str );
59331  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
59332  ExpandBlob(pVal);
59333  if( pVal->flags&MEM_Str ){
59334    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
59335    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
59336      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
59337      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
59338        return 0;
59339      }
59340    }
59341    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
59342  }else{
59343    assert( (pVal->flags&MEM_Blob)==0 );
59344    sqlite3VdbeMemStringify(pVal, enc);
59345    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
59346  }
59347  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
59348              || pVal->db->mallocFailed );
59349  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
59350    return pVal->z;
59351  }else{
59352    return 0;
59353  }
59354}
59355
59356/*
59357** Create a new sqlite3_value object.
59358*/
59359SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
59360  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
59361  if( p ){
59362    p->flags = MEM_Null;
59363    p->type = SQLITE_NULL;
59364    p->db = db;
59365  }
59366  return p;
59367}
59368
59369/*
59370** Create a new sqlite3_value object, containing the value of pExpr.
59371**
59372** This only works for very simple expressions that consist of one constant
59373** token (i.e. "5", "5.1", "'a string'"). If the expression can
59374** be converted directly into a value, then the value is allocated and
59375** a pointer written to *ppVal. The caller is responsible for deallocating
59376** the value by passing it to sqlite3ValueFree() later on. If the expression
59377** cannot be converted to a value, then *ppVal is set to NULL.
59378*/
59379SQLITE_PRIVATE int sqlite3ValueFromExpr(
59380  sqlite3 *db,              /* The database connection */
59381  Expr *pExpr,              /* The expression to evaluate */
59382  u8 enc,                   /* Encoding to use */
59383  u8 affinity,              /* Affinity to use */
59384  sqlite3_value **ppVal     /* Write the new value here */
59385){
59386  int op;
59387  char *zVal = 0;
59388  sqlite3_value *pVal = 0;
59389  int negInt = 1;
59390  const char *zNeg = "";
59391
59392  if( !pExpr ){
59393    *ppVal = 0;
59394    return SQLITE_OK;
59395  }
59396  op = pExpr->op;
59397
59398  /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
59399  ** The ifdef here is to enable us to achieve 100% branch test coverage even
59400  ** when SQLITE_ENABLE_STAT3 is omitted.
59401  */
59402#ifdef SQLITE_ENABLE_STAT3
59403  if( op==TK_REGISTER ) op = pExpr->op2;
59404#else
59405  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
59406#endif
59407
59408  /* Handle negative integers in a single step.  This is needed in the
59409  ** case when the value is -9223372036854775808.
59410  */
59411  if( op==TK_UMINUS
59412   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
59413    pExpr = pExpr->pLeft;
59414    op = pExpr->op;
59415    negInt = -1;
59416    zNeg = "-";
59417  }
59418
59419  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
59420    pVal = sqlite3ValueNew(db);
59421    if( pVal==0 ) goto no_mem;
59422    if( ExprHasProperty(pExpr, EP_IntValue) ){
59423      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
59424    }else{
59425      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
59426      if( zVal==0 ) goto no_mem;
59427      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
59428      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
59429    }
59430    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
59431      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
59432    }else{
59433      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
59434    }
59435    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
59436    if( enc!=SQLITE_UTF8 ){
59437      sqlite3VdbeChangeEncoding(pVal, enc);
59438    }
59439  }else if( op==TK_UMINUS ) {
59440    /* This branch happens for multiple negative signs.  Ex: -(-5) */
59441    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
59442      sqlite3VdbeMemNumerify(pVal);
59443      if( pVal->u.i==SMALLEST_INT64 ){
59444        pVal->flags &= MEM_Int;
59445        pVal->flags |= MEM_Real;
59446        pVal->r = (double)LARGEST_INT64;
59447      }else{
59448        pVal->u.i = -pVal->u.i;
59449      }
59450      pVal->r = -pVal->r;
59451      sqlite3ValueApplyAffinity(pVal, affinity, enc);
59452    }
59453  }else if( op==TK_NULL ){
59454    pVal = sqlite3ValueNew(db);
59455    if( pVal==0 ) goto no_mem;
59456  }
59457#ifndef SQLITE_OMIT_BLOB_LITERAL
59458  else if( op==TK_BLOB ){
59459    int nVal;
59460    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
59461    assert( pExpr->u.zToken[1]=='\'' );
59462    pVal = sqlite3ValueNew(db);
59463    if( !pVal ) goto no_mem;
59464    zVal = &pExpr->u.zToken[2];
59465    nVal = sqlite3Strlen30(zVal)-1;
59466    assert( zVal[nVal]=='\'' );
59467    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
59468                         0, SQLITE_DYNAMIC);
59469  }
59470#endif
59471
59472  if( pVal ){
59473    sqlite3VdbeMemStoreType(pVal);
59474  }
59475  *ppVal = pVal;
59476  return SQLITE_OK;
59477
59478no_mem:
59479  db->mallocFailed = 1;
59480  sqlite3DbFree(db, zVal);
59481  sqlite3ValueFree(pVal);
59482  *ppVal = 0;
59483  return SQLITE_NOMEM;
59484}
59485
59486/*
59487** Change the string value of an sqlite3_value object
59488*/
59489SQLITE_PRIVATE void sqlite3ValueSetStr(
59490  sqlite3_value *v,     /* Value to be set */
59491  int n,                /* Length of string z */
59492  const void *z,        /* Text of the new string */
59493  u8 enc,               /* Encoding to use */
59494  void (*xDel)(void*)   /* Destructor for the string */
59495){
59496  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
59497}
59498
59499/*
59500** Free an sqlite3_value object
59501*/
59502SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
59503  if( !v ) return;
59504  sqlite3VdbeMemRelease((Mem *)v);
59505  sqlite3DbFree(((Mem*)v)->db, v);
59506}
59507
59508/*
59509** Return the number of bytes in the sqlite3_value object assuming
59510** that it uses the encoding "enc"
59511*/
59512SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
59513  Mem *p = (Mem*)pVal;
59514  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
59515    if( p->flags & MEM_Zero ){
59516      return p->n + p->u.nZero;
59517    }else{
59518      return p->n;
59519    }
59520  }
59521  return 0;
59522}
59523
59524/************** End of vdbemem.c *********************************************/
59525/************** Begin file vdbeaux.c *****************************************/
59526/*
59527** 2003 September 6
59528**
59529** The author disclaims copyright to this source code.  In place of
59530** a legal notice, here is a blessing:
59531**
59532**    May you do good and not evil.
59533**    May you find forgiveness for yourself and forgive others.
59534**    May you share freely, never taking more than you give.
59535**
59536*************************************************************************
59537** This file contains code used for creating, destroying, and populating
59538** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
59539** to version 2.8.7, all this code was combined into the vdbe.c source file.
59540** But that file was getting too big so this subroutines were split out.
59541*/
59542
59543
59544
59545/*
59546** When debugging the code generator in a symbolic debugger, one can
59547** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
59548** as they are added to the instruction stream.
59549*/
59550#ifdef SQLITE_DEBUG
59551SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
59552#endif
59553
59554
59555/*
59556** Create a new virtual database engine.
59557*/
59558SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
59559  Vdbe *p;
59560  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
59561  if( p==0 ) return 0;
59562  p->db = db;
59563  if( db->pVdbe ){
59564    db->pVdbe->pPrev = p;
59565  }
59566  p->pNext = db->pVdbe;
59567  p->pPrev = 0;
59568  db->pVdbe = p;
59569  p->magic = VDBE_MAGIC_INIT;
59570  return p;
59571}
59572
59573/*
59574** Remember the SQL string for a prepared statement.
59575*/
59576SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
59577  assert( isPrepareV2==1 || isPrepareV2==0 );
59578  if( p==0 ) return;
59579#ifdef SQLITE_OMIT_TRACE
59580  if( !isPrepareV2 ) return;
59581#endif
59582  assert( p->zSql==0 );
59583  p->zSql = sqlite3DbStrNDup(p->db, z, n);
59584  p->isPrepareV2 = (u8)isPrepareV2;
59585}
59586
59587/*
59588** Return the SQL associated with a prepared statement
59589*/
59590SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
59591  Vdbe *p = (Vdbe *)pStmt;
59592  return (p && p->isPrepareV2) ? p->zSql : 0;
59593}
59594
59595/*
59596** Swap all content between two VDBE structures.
59597*/
59598SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
59599  Vdbe tmp, *pTmp;
59600  char *zTmp;
59601  tmp = *pA;
59602  *pA = *pB;
59603  *pB = tmp;
59604  pTmp = pA->pNext;
59605  pA->pNext = pB->pNext;
59606  pB->pNext = pTmp;
59607  pTmp = pA->pPrev;
59608  pA->pPrev = pB->pPrev;
59609  pB->pPrev = pTmp;
59610  zTmp = pA->zSql;
59611  pA->zSql = pB->zSql;
59612  pB->zSql = zTmp;
59613  pB->isPrepareV2 = pA->isPrepareV2;
59614}
59615
59616#ifdef SQLITE_DEBUG
59617/*
59618** Turn tracing on or off
59619*/
59620SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
59621  p->trace = trace;
59622}
59623#endif
59624
59625/*
59626** Resize the Vdbe.aOp array so that it is at least one op larger than
59627** it was.
59628**
59629** If an out-of-memory error occurs while resizing the array, return
59630** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
59631** unchanged (this is so that any opcodes already allocated can be
59632** correctly deallocated along with the rest of the Vdbe).
59633*/
59634static int growOpArray(Vdbe *p){
59635  VdbeOp *pNew;
59636  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
59637  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
59638  if( pNew ){
59639    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
59640    p->aOp = pNew;
59641  }
59642  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
59643}
59644
59645/*
59646** Add a new instruction to the list of instructions current in the
59647** VDBE.  Return the address of the new instruction.
59648**
59649** Parameters:
59650**
59651**    p               Pointer to the VDBE
59652**
59653**    op              The opcode for this instruction
59654**
59655**    p1, p2, p3      Operands
59656**
59657** Use the sqlite3VdbeResolveLabel() function to fix an address and
59658** the sqlite3VdbeChangeP4() function to change the value of the P4
59659** operand.
59660*/
59661SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
59662  int i;
59663  VdbeOp *pOp;
59664
59665  i = p->nOp;
59666  assert( p->magic==VDBE_MAGIC_INIT );
59667  assert( op>0 && op<0xff );
59668  if( p->nOpAlloc<=i ){
59669    if( growOpArray(p) ){
59670      return 1;
59671    }
59672  }
59673  p->nOp++;
59674  pOp = &p->aOp[i];
59675  pOp->opcode = (u8)op;
59676  pOp->p5 = 0;
59677  pOp->p1 = p1;
59678  pOp->p2 = p2;
59679  pOp->p3 = p3;
59680  pOp->p4.p = 0;
59681  pOp->p4type = P4_NOTUSED;
59682#ifdef SQLITE_DEBUG
59683  pOp->zComment = 0;
59684  if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
59685#endif
59686#ifdef VDBE_PROFILE
59687  pOp->cycles = 0;
59688  pOp->cnt = 0;
59689#endif
59690  return i;
59691}
59692SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
59693  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
59694}
59695SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
59696  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
59697}
59698SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
59699  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
59700}
59701
59702
59703/*
59704** Add an opcode that includes the p4 value as a pointer.
59705*/
59706SQLITE_PRIVATE int sqlite3VdbeAddOp4(
59707  Vdbe *p,            /* Add the opcode to this VM */
59708  int op,             /* The new opcode */
59709  int p1,             /* The P1 operand */
59710  int p2,             /* The P2 operand */
59711  int p3,             /* The P3 operand */
59712  const char *zP4,    /* The P4 operand */
59713  int p4type          /* P4 operand type */
59714){
59715  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
59716  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
59717  return addr;
59718}
59719
59720/*
59721** Add an OP_ParseSchema opcode.  This routine is broken out from
59722** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
59723** as having been used.
59724**
59725** The zWhere string must have been obtained from sqlite3_malloc().
59726** This routine will take ownership of the allocated memory.
59727*/
59728SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
59729  int j;
59730  int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
59731  sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
59732  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
59733}
59734
59735/*
59736** Add an opcode that includes the p4 value as an integer.
59737*/
59738SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
59739  Vdbe *p,            /* Add the opcode to this VM */
59740  int op,             /* The new opcode */
59741  int p1,             /* The P1 operand */
59742  int p2,             /* The P2 operand */
59743  int p3,             /* The P3 operand */
59744  int p4              /* The P4 operand as an integer */
59745){
59746  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
59747  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
59748  return addr;
59749}
59750
59751/*
59752** Create a new symbolic label for an instruction that has yet to be
59753** coded.  The symbolic label is really just a negative number.  The
59754** label can be used as the P2 value of an operation.  Later, when
59755** the label is resolved to a specific address, the VDBE will scan
59756** through its operation list and change all values of P2 which match
59757** the label into the resolved address.
59758**
59759** The VDBE knows that a P2 value is a label because labels are
59760** always negative and P2 values are suppose to be non-negative.
59761** Hence, a negative P2 value is a label that has yet to be resolved.
59762**
59763** Zero is returned if a malloc() fails.
59764*/
59765SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
59766  int i = p->nLabel++;
59767  assert( p->magic==VDBE_MAGIC_INIT );
59768  if( (i & (i-1))==0 ){
59769    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
59770                                       (i*2+1)*sizeof(p->aLabel[0]));
59771  }
59772  if( p->aLabel ){
59773    p->aLabel[i] = -1;
59774  }
59775  return -1-i;
59776}
59777
59778/*
59779** Resolve label "x" to be the address of the next instruction to
59780** be inserted.  The parameter "x" must have been obtained from
59781** a prior call to sqlite3VdbeMakeLabel().
59782*/
59783SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
59784  int j = -1-x;
59785  assert( p->magic==VDBE_MAGIC_INIT );
59786  assert( j>=0 && j<p->nLabel );
59787  if( p->aLabel ){
59788    p->aLabel[j] = p->nOp;
59789  }
59790}
59791
59792/*
59793** Mark the VDBE as one that can only be run one time.
59794*/
59795SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
59796  p->runOnlyOnce = 1;
59797}
59798
59799#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
59800
59801/*
59802** The following type and function are used to iterate through all opcodes
59803** in a Vdbe main program and each of the sub-programs (triggers) it may
59804** invoke directly or indirectly. It should be used as follows:
59805**
59806**   Op *pOp;
59807**   VdbeOpIter sIter;
59808**
59809**   memset(&sIter, 0, sizeof(sIter));
59810**   sIter.v = v;                            // v is of type Vdbe*
59811**   while( (pOp = opIterNext(&sIter)) ){
59812**     // Do something with pOp
59813**   }
59814**   sqlite3DbFree(v->db, sIter.apSub);
59815**
59816*/
59817typedef struct VdbeOpIter VdbeOpIter;
59818struct VdbeOpIter {
59819  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
59820  SubProgram **apSub;        /* Array of subprograms */
59821  int nSub;                  /* Number of entries in apSub */
59822  int iAddr;                 /* Address of next instruction to return */
59823  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
59824};
59825static Op *opIterNext(VdbeOpIter *p){
59826  Vdbe *v = p->v;
59827  Op *pRet = 0;
59828  Op *aOp;
59829  int nOp;
59830
59831  if( p->iSub<=p->nSub ){
59832
59833    if( p->iSub==0 ){
59834      aOp = v->aOp;
59835      nOp = v->nOp;
59836    }else{
59837      aOp = p->apSub[p->iSub-1]->aOp;
59838      nOp = p->apSub[p->iSub-1]->nOp;
59839    }
59840    assert( p->iAddr<nOp );
59841
59842    pRet = &aOp[p->iAddr];
59843    p->iAddr++;
59844    if( p->iAddr==nOp ){
59845      p->iSub++;
59846      p->iAddr = 0;
59847    }
59848
59849    if( pRet->p4type==P4_SUBPROGRAM ){
59850      int nByte = (p->nSub+1)*sizeof(SubProgram*);
59851      int j;
59852      for(j=0; j<p->nSub; j++){
59853        if( p->apSub[j]==pRet->p4.pProgram ) break;
59854      }
59855      if( j==p->nSub ){
59856        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
59857        if( !p->apSub ){
59858          pRet = 0;
59859        }else{
59860          p->apSub[p->nSub++] = pRet->p4.pProgram;
59861        }
59862      }
59863    }
59864  }
59865
59866  return pRet;
59867}
59868
59869/*
59870** Check if the program stored in the VM associated with pParse may
59871** throw an ABORT exception (causing the statement, but not entire transaction
59872** to be rolled back). This condition is true if the main program or any
59873** sub-programs contains any of the following:
59874**
59875**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
59876**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
59877**   *  OP_Destroy
59878**   *  OP_VUpdate
59879**   *  OP_VRename
59880**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
59881**
59882** Then check that the value of Parse.mayAbort is true if an
59883** ABORT may be thrown, or false otherwise. Return true if it does
59884** match, or false otherwise. This function is intended to be used as
59885** part of an assert statement in the compiler. Similar to:
59886**
59887**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
59888*/
59889SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
59890  int hasAbort = 0;
59891  Op *pOp;
59892  VdbeOpIter sIter;
59893  memset(&sIter, 0, sizeof(sIter));
59894  sIter.v = v;
59895
59896  while( (pOp = opIterNext(&sIter))!=0 ){
59897    int opcode = pOp->opcode;
59898    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
59899#ifndef SQLITE_OMIT_FOREIGN_KEY
59900     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
59901#endif
59902     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
59903      && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
59904    ){
59905      hasAbort = 1;
59906      break;
59907    }
59908  }
59909  sqlite3DbFree(v->db, sIter.apSub);
59910
59911  /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
59912  ** If malloc failed, then the while() loop above may not have iterated
59913  ** through all opcodes and hasAbort may be set incorrectly. Return
59914  ** true for this case to prevent the assert() in the callers frame
59915  ** from failing.  */
59916  return ( v->db->mallocFailed || hasAbort==mayAbort );
59917}
59918#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
59919
59920/*
59921** Loop through the program looking for P2 values that are negative
59922** on jump instructions.  Each such value is a label.  Resolve the
59923** label by setting the P2 value to its correct non-zero value.
59924**
59925** This routine is called once after all opcodes have been inserted.
59926**
59927** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
59928** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
59929** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
59930**
59931** The Op.opflags field is set on all opcodes.
59932*/
59933static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
59934  int i;
59935  int nMaxArgs = *pMaxFuncArgs;
59936  Op *pOp;
59937  int *aLabel = p->aLabel;
59938  p->readOnly = 1;
59939  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
59940    u8 opcode = pOp->opcode;
59941
59942    pOp->opflags = sqlite3OpcodeProperty[opcode];
59943    if( opcode==OP_Function || opcode==OP_AggStep ){
59944      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
59945    }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
59946      p->readOnly = 0;
59947#ifndef SQLITE_OMIT_VIRTUALTABLE
59948    }else if( opcode==OP_VUpdate ){
59949      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
59950    }else if( opcode==OP_VFilter ){
59951      int n;
59952      assert( p->nOp - i >= 3 );
59953      assert( pOp[-1].opcode==OP_Integer );
59954      n = pOp[-1].p1;
59955      if( n>nMaxArgs ) nMaxArgs = n;
59956#endif
59957    }else if( opcode==OP_Next || opcode==OP_SorterNext ){
59958      pOp->p4.xAdvance = sqlite3BtreeNext;
59959      pOp->p4type = P4_ADVANCE;
59960    }else if( opcode==OP_Prev ){
59961      pOp->p4.xAdvance = sqlite3BtreePrevious;
59962      pOp->p4type = P4_ADVANCE;
59963    }
59964
59965    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
59966      assert( -1-pOp->p2<p->nLabel );
59967      pOp->p2 = aLabel[-1-pOp->p2];
59968    }
59969  }
59970  sqlite3DbFree(p->db, p->aLabel);
59971  p->aLabel = 0;
59972
59973  *pMaxFuncArgs = nMaxArgs;
59974}
59975
59976/*
59977** Return the address of the next instruction to be inserted.
59978*/
59979SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
59980  assert( p->magic==VDBE_MAGIC_INIT );
59981  return p->nOp;
59982}
59983
59984/*
59985** This function returns a pointer to the array of opcodes associated with
59986** the Vdbe passed as the first argument. It is the callers responsibility
59987** to arrange for the returned array to be eventually freed using the
59988** vdbeFreeOpArray() function.
59989**
59990** Before returning, *pnOp is set to the number of entries in the returned
59991** array. Also, *pnMaxArg is set to the larger of its current value and
59992** the number of entries in the Vdbe.apArg[] array required to execute the
59993** returned program.
59994*/
59995SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
59996  VdbeOp *aOp = p->aOp;
59997  assert( aOp && !p->db->mallocFailed );
59998
59999  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
60000  assert( p->btreeMask==0 );
60001
60002  resolveP2Values(p, pnMaxArg);
60003  *pnOp = p->nOp;
60004  p->aOp = 0;
60005  return aOp;
60006}
60007
60008/*
60009** Add a whole list of operations to the operation stack.  Return the
60010** address of the first operation added.
60011*/
60012SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
60013  int addr;
60014  assert( p->magic==VDBE_MAGIC_INIT );
60015  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
60016    return 0;
60017  }
60018  addr = p->nOp;
60019  if( ALWAYS(nOp>0) ){
60020    int i;
60021    VdbeOpList const *pIn = aOp;
60022    for(i=0; i<nOp; i++, pIn++){
60023      int p2 = pIn->p2;
60024      VdbeOp *pOut = &p->aOp[i+addr];
60025      pOut->opcode = pIn->opcode;
60026      pOut->p1 = pIn->p1;
60027      if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
60028        pOut->p2 = addr + ADDR(p2);
60029      }else{
60030        pOut->p2 = p2;
60031      }
60032      pOut->p3 = pIn->p3;
60033      pOut->p4type = P4_NOTUSED;
60034      pOut->p4.p = 0;
60035      pOut->p5 = 0;
60036#ifdef SQLITE_DEBUG
60037      pOut->zComment = 0;
60038      if( sqlite3VdbeAddopTrace ){
60039        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
60040      }
60041#endif
60042    }
60043    p->nOp += nOp;
60044  }
60045  return addr;
60046}
60047
60048/*
60049** Change the value of the P1 operand for a specific instruction.
60050** This routine is useful when a large program is loaded from a
60051** static array using sqlite3VdbeAddOpList but we want to make a
60052** few minor changes to the program.
60053*/
60054SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
60055  assert( p!=0 );
60056  if( ((u32)p->nOp)>addr ){
60057    p->aOp[addr].p1 = val;
60058  }
60059}
60060
60061/*
60062** Change the value of the P2 operand for a specific instruction.
60063** This routine is useful for setting a jump destination.
60064*/
60065SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
60066  assert( p!=0 );
60067  if( ((u32)p->nOp)>addr ){
60068    p->aOp[addr].p2 = val;
60069  }
60070}
60071
60072/*
60073** Change the value of the P3 operand for a specific instruction.
60074*/
60075SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
60076  assert( p!=0 );
60077  if( ((u32)p->nOp)>addr ){
60078    p->aOp[addr].p3 = val;
60079  }
60080}
60081
60082/*
60083** Change the value of the P5 operand for the most recently
60084** added operation.
60085*/
60086SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
60087  assert( p!=0 );
60088  if( p->aOp ){
60089    assert( p->nOp>0 );
60090    p->aOp[p->nOp-1].p5 = val;
60091  }
60092}
60093
60094/*
60095** Change the P2 operand of instruction addr so that it points to
60096** the address of the next instruction to be coded.
60097*/
60098SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
60099  assert( addr>=0 || p->db->mallocFailed );
60100  if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
60101}
60102
60103
60104/*
60105** If the input FuncDef structure is ephemeral, then free it.  If
60106** the FuncDef is not ephermal, then do nothing.
60107*/
60108static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
60109  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
60110    sqlite3DbFree(db, pDef);
60111  }
60112}
60113
60114static void vdbeFreeOpArray(sqlite3 *, Op *, int);
60115
60116/*
60117** Delete a P4 value if necessary.
60118*/
60119static void freeP4(sqlite3 *db, int p4type, void *p4){
60120  if( p4 ){
60121    assert( db );
60122    switch( p4type ){
60123      case P4_REAL:
60124      case P4_INT64:
60125      case P4_DYNAMIC:
60126      case P4_KEYINFO:
60127      case P4_INTARRAY:
60128      case P4_KEYINFO_HANDOFF: {
60129        sqlite3DbFree(db, p4);
60130        break;
60131      }
60132      case P4_MPRINTF: {
60133        if( db->pnBytesFreed==0 ) sqlite3_free(p4);
60134        break;
60135      }
60136      case P4_VDBEFUNC: {
60137        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
60138        freeEphemeralFunction(db, pVdbeFunc->pFunc);
60139        if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
60140        sqlite3DbFree(db, pVdbeFunc);
60141        break;
60142      }
60143      case P4_FUNCDEF: {
60144        freeEphemeralFunction(db, (FuncDef*)p4);
60145        break;
60146      }
60147      case P4_MEM: {
60148        if( db->pnBytesFreed==0 ){
60149          sqlite3ValueFree((sqlite3_value*)p4);
60150        }else{
60151          Mem *p = (Mem*)p4;
60152          sqlite3DbFree(db, p->zMalloc);
60153          sqlite3DbFree(db, p);
60154        }
60155        break;
60156      }
60157      case P4_VTAB : {
60158        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
60159        break;
60160      }
60161    }
60162  }
60163}
60164
60165/*
60166** Free the space allocated for aOp and any p4 values allocated for the
60167** opcodes contained within. If aOp is not NULL it is assumed to contain
60168** nOp entries.
60169*/
60170static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
60171  if( aOp ){
60172    Op *pOp;
60173    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
60174      freeP4(db, pOp->p4type, pOp->p4.p);
60175#ifdef SQLITE_DEBUG
60176      sqlite3DbFree(db, pOp->zComment);
60177#endif
60178    }
60179  }
60180  sqlite3DbFree(db, aOp);
60181}
60182
60183/*
60184** Link the SubProgram object passed as the second argument into the linked
60185** list at Vdbe.pSubProgram. This list is used to delete all sub-program
60186** objects when the VM is no longer required.
60187*/
60188SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
60189  p->pNext = pVdbe->pProgram;
60190  pVdbe->pProgram = p;
60191}
60192
60193/*
60194** Change the opcode at addr into OP_Noop
60195*/
60196SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
60197  if( p->aOp ){
60198    VdbeOp *pOp = &p->aOp[addr];
60199    sqlite3 *db = p->db;
60200    freeP4(db, pOp->p4type, pOp->p4.p);
60201    memset(pOp, 0, sizeof(pOp[0]));
60202    pOp->opcode = OP_Noop;
60203  }
60204}
60205
60206/*
60207** Change the value of the P4 operand for a specific instruction.
60208** This routine is useful when a large program is loaded from a
60209** static array using sqlite3VdbeAddOpList but we want to make a
60210** few minor changes to the program.
60211**
60212** If n>=0 then the P4 operand is dynamic, meaning that a copy of
60213** the string is made into memory obtained from sqlite3_malloc().
60214** A value of n==0 means copy bytes of zP4 up to and including the
60215** first null byte.  If n>0 then copy n+1 bytes of zP4.
60216**
60217** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
60218** A copy is made of the KeyInfo structure into memory obtained from
60219** sqlite3_malloc, to be freed when the Vdbe is finalized.
60220** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
60221** stored in memory that the caller has obtained from sqlite3_malloc. The
60222** caller should not free the allocation, it will be freed when the Vdbe is
60223** finalized.
60224**
60225** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
60226** to a string or structure that is guaranteed to exist for the lifetime of
60227** the Vdbe. In these cases we can just copy the pointer.
60228**
60229** If addr<0 then change P4 on the most recently inserted instruction.
60230*/
60231SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
60232  Op *pOp;
60233  sqlite3 *db;
60234  assert( p!=0 );
60235  db = p->db;
60236  assert( p->magic==VDBE_MAGIC_INIT );
60237  if( p->aOp==0 || db->mallocFailed ){
60238    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
60239      freeP4(db, n, (void*)*(char**)&zP4);
60240    }
60241    return;
60242  }
60243  assert( p->nOp>0 );
60244  assert( addr<p->nOp );
60245  if( addr<0 ){
60246    addr = p->nOp - 1;
60247  }
60248  pOp = &p->aOp[addr];
60249  freeP4(db, pOp->p4type, pOp->p4.p);
60250  pOp->p4.p = 0;
60251  if( n==P4_INT32 ){
60252    /* Note: this cast is safe, because the origin data point was an int
60253    ** that was cast to a (const char *). */
60254    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
60255    pOp->p4type = P4_INT32;
60256  }else if( zP4==0 ){
60257    pOp->p4.p = 0;
60258    pOp->p4type = P4_NOTUSED;
60259  }else if( n==P4_KEYINFO ){
60260    KeyInfo *pKeyInfo;
60261    int nField, nByte;
60262
60263    nField = ((KeyInfo*)zP4)->nField;
60264    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
60265    pKeyInfo = sqlite3DbMallocRaw(0, nByte);
60266    pOp->p4.pKeyInfo = pKeyInfo;
60267    if( pKeyInfo ){
60268      u8 *aSortOrder;
60269      memcpy((char*)pKeyInfo, zP4, nByte - nField);
60270      aSortOrder = pKeyInfo->aSortOrder;
60271      if( aSortOrder ){
60272        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
60273        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
60274      }
60275      pOp->p4type = P4_KEYINFO;
60276    }else{
60277      p->db->mallocFailed = 1;
60278      pOp->p4type = P4_NOTUSED;
60279    }
60280  }else if( n==P4_KEYINFO_HANDOFF ){
60281    pOp->p4.p = (void*)zP4;
60282    pOp->p4type = P4_KEYINFO;
60283  }else if( n==P4_VTAB ){
60284    pOp->p4.p = (void*)zP4;
60285    pOp->p4type = P4_VTAB;
60286    sqlite3VtabLock((VTable *)zP4);
60287    assert( ((VTable *)zP4)->db==p->db );
60288  }else if( n<0 ){
60289    pOp->p4.p = (void*)zP4;
60290    pOp->p4type = (signed char)n;
60291  }else{
60292    if( n==0 ) n = sqlite3Strlen30(zP4);
60293    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
60294    pOp->p4type = P4_DYNAMIC;
60295  }
60296}
60297
60298#ifndef NDEBUG
60299/*
60300** Change the comment on the the most recently coded instruction.  Or
60301** insert a No-op and add the comment to that new instruction.  This
60302** makes the code easier to read during debugging.  None of this happens
60303** in a production build.
60304*/
60305static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
60306  assert( p->nOp>0 || p->aOp==0 );
60307  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
60308  if( p->nOp ){
60309    assert( p->aOp );
60310    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
60311    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
60312  }
60313}
60314SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
60315  va_list ap;
60316  if( p ){
60317    va_start(ap, zFormat);
60318    vdbeVComment(p, zFormat, ap);
60319    va_end(ap);
60320  }
60321}
60322SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
60323  va_list ap;
60324  if( p ){
60325    sqlite3VdbeAddOp0(p, OP_Noop);
60326    va_start(ap, zFormat);
60327    vdbeVComment(p, zFormat, ap);
60328    va_end(ap);
60329  }
60330}
60331#endif  /* NDEBUG */
60332
60333/*
60334** Return the opcode for a given address.  If the address is -1, then
60335** return the most recently inserted opcode.
60336**
60337** If a memory allocation error has occurred prior to the calling of this
60338** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
60339** is readable but not writable, though it is cast to a writable value.
60340** The return of a dummy opcode allows the call to continue functioning
60341** after a OOM fault without having to check to see if the return from
60342** this routine is a valid pointer.  But because the dummy.opcode is 0,
60343** dummy will never be written to.  This is verified by code inspection and
60344** by running with Valgrind.
60345**
60346** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
60347** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
60348** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
60349** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
60350** having to double-check to make sure that the result is non-negative. But
60351** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
60352** check the value of p->nOp-1 before continuing.
60353*/
60354SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
60355  /* C89 specifies that the constant "dummy" will be initialized to all
60356  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
60357  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
60358  assert( p->magic==VDBE_MAGIC_INIT );
60359  if( addr<0 ){
60360#ifdef SQLITE_OMIT_TRACE
60361    if( p->nOp==0 ) return (VdbeOp*)&dummy;
60362#endif
60363    addr = p->nOp - 1;
60364  }
60365  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
60366  if( p->db->mallocFailed ){
60367    return (VdbeOp*)&dummy;
60368  }else{
60369    return &p->aOp[addr];
60370  }
60371}
60372
60373#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
60374     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
60375/*
60376** Compute a string that describes the P4 parameter for an opcode.
60377** Use zTemp for any required temporary buffer space.
60378*/
60379static char *displayP4(Op *pOp, char *zTemp, int nTemp){
60380  char *zP4 = zTemp;
60381  assert( nTemp>=20 );
60382  switch( pOp->p4type ){
60383    case P4_KEYINFO_STATIC:
60384    case P4_KEYINFO: {
60385      int i, j;
60386      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
60387      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
60388      i = sqlite3Strlen30(zTemp);
60389      for(j=0; j<pKeyInfo->nField; j++){
60390        CollSeq *pColl = pKeyInfo->aColl[j];
60391        if( pColl ){
60392          int n = sqlite3Strlen30(pColl->zName);
60393          if( i+n>nTemp-6 ){
60394            memcpy(&zTemp[i],",...",4);
60395            break;
60396          }
60397          zTemp[i++] = ',';
60398          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
60399            zTemp[i++] = '-';
60400          }
60401          memcpy(&zTemp[i], pColl->zName,n+1);
60402          i += n;
60403        }else if( i+4<nTemp-6 ){
60404          memcpy(&zTemp[i],",nil",4);
60405          i += 4;
60406        }
60407      }
60408      zTemp[i++] = ')';
60409      zTemp[i] = 0;
60410      assert( i<nTemp );
60411      break;
60412    }
60413    case P4_COLLSEQ: {
60414      CollSeq *pColl = pOp->p4.pColl;
60415      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
60416      break;
60417    }
60418    case P4_FUNCDEF: {
60419      FuncDef *pDef = pOp->p4.pFunc;
60420      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
60421      break;
60422    }
60423    case P4_INT64: {
60424      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
60425      break;
60426    }
60427    case P4_INT32: {
60428      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
60429      break;
60430    }
60431    case P4_REAL: {
60432      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
60433      break;
60434    }
60435    case P4_MEM: {
60436      Mem *pMem = pOp->p4.pMem;
60437      if( pMem->flags & MEM_Str ){
60438        zP4 = pMem->z;
60439      }else if( pMem->flags & MEM_Int ){
60440        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
60441      }else if( pMem->flags & MEM_Real ){
60442        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
60443      }else if( pMem->flags & MEM_Null ){
60444        sqlite3_snprintf(nTemp, zTemp, "NULL");
60445      }else{
60446        assert( pMem->flags & MEM_Blob );
60447        zP4 = "(blob)";
60448      }
60449      break;
60450    }
60451#ifndef SQLITE_OMIT_VIRTUALTABLE
60452    case P4_VTAB: {
60453      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
60454      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
60455      break;
60456    }
60457#endif
60458    case P4_INTARRAY: {
60459      sqlite3_snprintf(nTemp, zTemp, "intarray");
60460      break;
60461    }
60462    case P4_SUBPROGRAM: {
60463      sqlite3_snprintf(nTemp, zTemp, "program");
60464      break;
60465    }
60466    case P4_ADVANCE: {
60467      zTemp[0] = 0;
60468      break;
60469    }
60470    default: {
60471      zP4 = pOp->p4.z;
60472      if( zP4==0 ){
60473        zP4 = zTemp;
60474        zTemp[0] = 0;
60475      }
60476    }
60477  }
60478  assert( zP4!=0 );
60479  return zP4;
60480}
60481#endif
60482
60483/*
60484** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
60485**
60486** The prepared statements need to know in advance the complete set of
60487** attached databases that will be use.  A mask of these databases
60488** is maintained in p->btreeMask.  The p->lockMask value is the subset of
60489** p->btreeMask of databases that will require a lock.
60490*/
60491SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
60492  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
60493  assert( i<(int)sizeof(p->btreeMask)*8 );
60494  p->btreeMask |= ((yDbMask)1)<<i;
60495  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
60496    p->lockMask |= ((yDbMask)1)<<i;
60497  }
60498}
60499
60500#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
60501/*
60502** If SQLite is compiled to support shared-cache mode and to be threadsafe,
60503** this routine obtains the mutex associated with each BtShared structure
60504** that may be accessed by the VM passed as an argument. In doing so it also
60505** sets the BtShared.db member of each of the BtShared structures, ensuring
60506** that the correct busy-handler callback is invoked if required.
60507**
60508** If SQLite is not threadsafe but does support shared-cache mode, then
60509** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
60510** of all of BtShared structures accessible via the database handle
60511** associated with the VM.
60512**
60513** If SQLite is not threadsafe and does not support shared-cache mode, this
60514** function is a no-op.
60515**
60516** The p->btreeMask field is a bitmask of all btrees that the prepared
60517** statement p will ever use.  Let N be the number of bits in p->btreeMask
60518** corresponding to btrees that use shared cache.  Then the runtime of
60519** this routine is N*N.  But as N is rarely more than 1, this should not
60520** be a problem.
60521*/
60522SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
60523  int i;
60524  yDbMask mask;
60525  sqlite3 *db;
60526  Db *aDb;
60527  int nDb;
60528  if( p->lockMask==0 ) return;  /* The common case */
60529  db = p->db;
60530  aDb = db->aDb;
60531  nDb = db->nDb;
60532  for(i=0, mask=1; i<nDb; i++, mask += mask){
60533    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60534      sqlite3BtreeEnter(aDb[i].pBt);
60535    }
60536  }
60537}
60538#endif
60539
60540#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
60541/*
60542** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
60543*/
60544SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
60545  int i;
60546  yDbMask mask;
60547  sqlite3 *db;
60548  Db *aDb;
60549  int nDb;
60550  if( p->lockMask==0 ) return;  /* The common case */
60551  db = p->db;
60552  aDb = db->aDb;
60553  nDb = db->nDb;
60554  for(i=0, mask=1; i<nDb; i++, mask += mask){
60555    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60556      sqlite3BtreeLeave(aDb[i].pBt);
60557    }
60558  }
60559}
60560#endif
60561
60562#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
60563/*
60564** Print a single opcode.  This routine is used for debugging only.
60565*/
60566SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
60567  char *zP4;
60568  char zPtr[50];
60569  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
60570  if( pOut==0 ) pOut = stdout;
60571  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
60572  fprintf(pOut, zFormat1, pc,
60573      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
60574#ifdef SQLITE_DEBUG
60575      pOp->zComment ? pOp->zComment : ""
60576#else
60577      ""
60578#endif
60579  );
60580  fflush(pOut);
60581}
60582#endif
60583
60584/*
60585** Release an array of N Mem elements
60586*/
60587static void releaseMemArray(Mem *p, int N){
60588  if( p && N ){
60589    Mem *pEnd;
60590    sqlite3 *db = p->db;
60591    u8 malloc_failed = db->mallocFailed;
60592    if( db->pnBytesFreed ){
60593      for(pEnd=&p[N]; p<pEnd; p++){
60594        sqlite3DbFree(db, p->zMalloc);
60595      }
60596      return;
60597    }
60598    for(pEnd=&p[N]; p<pEnd; p++){
60599      assert( (&p[1])==pEnd || p[0].db==p[1].db );
60600
60601      /* This block is really an inlined version of sqlite3VdbeMemRelease()
60602      ** that takes advantage of the fact that the memory cell value is
60603      ** being set to NULL after releasing any dynamic resources.
60604      **
60605      ** The justification for duplicating code is that according to
60606      ** callgrind, this causes a certain test case to hit the CPU 4.7
60607      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
60608      ** sqlite3MemRelease() were called from here. With -O2, this jumps
60609      ** to 6.6 percent. The test case is inserting 1000 rows into a table
60610      ** with no indexes using a single prepared INSERT statement, bind()
60611      ** and reset(). Inserts are grouped into a transaction.
60612      */
60613      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
60614        sqlite3VdbeMemRelease(p);
60615      }else if( p->zMalloc ){
60616        sqlite3DbFree(db, p->zMalloc);
60617        p->zMalloc = 0;
60618      }
60619
60620      p->flags = MEM_Invalid;
60621    }
60622    db->mallocFailed = malloc_failed;
60623  }
60624}
60625
60626/*
60627** Delete a VdbeFrame object and its contents. VdbeFrame objects are
60628** allocated by the OP_Program opcode in sqlite3VdbeExec().
60629*/
60630SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
60631  int i;
60632  Mem *aMem = VdbeFrameMem(p);
60633  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
60634  for(i=0; i<p->nChildCsr; i++){
60635    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
60636  }
60637  releaseMemArray(aMem, p->nChildMem);
60638  sqlite3DbFree(p->v->db, p);
60639}
60640
60641#ifndef SQLITE_OMIT_EXPLAIN
60642/*
60643** Give a listing of the program in the virtual machine.
60644**
60645** The interface is the same as sqlite3VdbeExec().  But instead of
60646** running the code, it invokes the callback once for each instruction.
60647** This feature is used to implement "EXPLAIN".
60648**
60649** When p->explain==1, each instruction is listed.  When
60650** p->explain==2, only OP_Explain instructions are listed and these
60651** are shown in a different format.  p->explain==2 is used to implement
60652** EXPLAIN QUERY PLAN.
60653**
60654** When p->explain==1, first the main program is listed, then each of
60655** the trigger subprograms are listed one by one.
60656*/
60657SQLITE_PRIVATE int sqlite3VdbeList(
60658  Vdbe *p                   /* The VDBE */
60659){
60660  int nRow;                            /* Stop when row count reaches this */
60661  int nSub = 0;                        /* Number of sub-vdbes seen so far */
60662  SubProgram **apSub = 0;              /* Array of sub-vdbes */
60663  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
60664  sqlite3 *db = p->db;                 /* The database connection */
60665  int i;                               /* Loop counter */
60666  int rc = SQLITE_OK;                  /* Return code */
60667  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
60668
60669  assert( p->explain );
60670  assert( p->magic==VDBE_MAGIC_RUN );
60671  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
60672
60673  /* Even though this opcode does not use dynamic strings for
60674  ** the result, result columns may become dynamic if the user calls
60675  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
60676  */
60677  releaseMemArray(pMem, 8);
60678  p->pResultSet = 0;
60679
60680  if( p->rc==SQLITE_NOMEM ){
60681    /* This happens if a malloc() inside a call to sqlite3_column_text() or
60682    ** sqlite3_column_text16() failed.  */
60683    db->mallocFailed = 1;
60684    return SQLITE_ERROR;
60685  }
60686
60687  /* When the number of output rows reaches nRow, that means the
60688  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
60689  ** nRow is the sum of the number of rows in the main program, plus
60690  ** the sum of the number of rows in all trigger subprograms encountered
60691  ** so far.  The nRow value will increase as new trigger subprograms are
60692  ** encountered, but p->pc will eventually catch up to nRow.
60693  */
60694  nRow = p->nOp;
60695  if( p->explain==1 ){
60696    /* The first 8 memory cells are used for the result set.  So we will
60697    ** commandeer the 9th cell to use as storage for an array of pointers
60698    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
60699    ** cells.  */
60700    assert( p->nMem>9 );
60701    pSub = &p->aMem[9];
60702    if( pSub->flags&MEM_Blob ){
60703      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
60704      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
60705      nSub = pSub->n/sizeof(Vdbe*);
60706      apSub = (SubProgram **)pSub->z;
60707    }
60708    for(i=0; i<nSub; i++){
60709      nRow += apSub[i]->nOp;
60710    }
60711  }
60712
60713  do{
60714    i = p->pc++;
60715  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
60716  if( i>=nRow ){
60717    p->rc = SQLITE_OK;
60718    rc = SQLITE_DONE;
60719  }else if( db->u1.isInterrupted ){
60720    p->rc = SQLITE_INTERRUPT;
60721    rc = SQLITE_ERROR;
60722    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
60723  }else{
60724    char *z;
60725    Op *pOp;
60726    if( i<p->nOp ){
60727      /* The output line number is small enough that we are still in the
60728      ** main program. */
60729      pOp = &p->aOp[i];
60730    }else{
60731      /* We are currently listing subprograms.  Figure out which one and
60732      ** pick up the appropriate opcode. */
60733      int j;
60734      i -= p->nOp;
60735      for(j=0; i>=apSub[j]->nOp; j++){
60736        i -= apSub[j]->nOp;
60737      }
60738      pOp = &apSub[j]->aOp[i];
60739    }
60740    if( p->explain==1 ){
60741      pMem->flags = MEM_Int;
60742      pMem->type = SQLITE_INTEGER;
60743      pMem->u.i = i;                                /* Program counter */
60744      pMem++;
60745
60746      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
60747      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
60748      assert( pMem->z!=0 );
60749      pMem->n = sqlite3Strlen30(pMem->z);
60750      pMem->type = SQLITE_TEXT;
60751      pMem->enc = SQLITE_UTF8;
60752      pMem++;
60753
60754      /* When an OP_Program opcode is encounter (the only opcode that has
60755      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
60756      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
60757      ** has not already been seen.
60758      */
60759      if( pOp->p4type==P4_SUBPROGRAM ){
60760        int nByte = (nSub+1)*sizeof(SubProgram*);
60761        int j;
60762        for(j=0; j<nSub; j++){
60763          if( apSub[j]==pOp->p4.pProgram ) break;
60764        }
60765        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
60766          apSub = (SubProgram **)pSub->z;
60767          apSub[nSub++] = pOp->p4.pProgram;
60768          pSub->flags |= MEM_Blob;
60769          pSub->n = nSub*sizeof(SubProgram*);
60770        }
60771      }
60772    }
60773
60774    pMem->flags = MEM_Int;
60775    pMem->u.i = pOp->p1;                          /* P1 */
60776    pMem->type = SQLITE_INTEGER;
60777    pMem++;
60778
60779    pMem->flags = MEM_Int;
60780    pMem->u.i = pOp->p2;                          /* P2 */
60781    pMem->type = SQLITE_INTEGER;
60782    pMem++;
60783
60784    pMem->flags = MEM_Int;
60785    pMem->u.i = pOp->p3;                          /* P3 */
60786    pMem->type = SQLITE_INTEGER;
60787    pMem++;
60788
60789    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
60790      assert( p->db->mallocFailed );
60791      return SQLITE_ERROR;
60792    }
60793    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
60794    z = displayP4(pOp, pMem->z, 32);
60795    if( z!=pMem->z ){
60796      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
60797    }else{
60798      assert( pMem->z!=0 );
60799      pMem->n = sqlite3Strlen30(pMem->z);
60800      pMem->enc = SQLITE_UTF8;
60801    }
60802    pMem->type = SQLITE_TEXT;
60803    pMem++;
60804
60805    if( p->explain==1 ){
60806      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
60807        assert( p->db->mallocFailed );
60808        return SQLITE_ERROR;
60809      }
60810      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
60811      pMem->n = 2;
60812      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
60813      pMem->type = SQLITE_TEXT;
60814      pMem->enc = SQLITE_UTF8;
60815      pMem++;
60816
60817#ifdef SQLITE_DEBUG
60818      if( pOp->zComment ){
60819        pMem->flags = MEM_Str|MEM_Term;
60820        pMem->z = pOp->zComment;
60821        pMem->n = sqlite3Strlen30(pMem->z);
60822        pMem->enc = SQLITE_UTF8;
60823        pMem->type = SQLITE_TEXT;
60824      }else
60825#endif
60826      {
60827        pMem->flags = MEM_Null;                       /* Comment */
60828        pMem->type = SQLITE_NULL;
60829      }
60830    }
60831
60832    p->nResColumn = 8 - 4*(p->explain-1);
60833    p->pResultSet = &p->aMem[1];
60834    p->rc = SQLITE_OK;
60835    rc = SQLITE_ROW;
60836  }
60837  return rc;
60838}
60839#endif /* SQLITE_OMIT_EXPLAIN */
60840
60841#ifdef SQLITE_DEBUG
60842/*
60843** Print the SQL that was used to generate a VDBE program.
60844*/
60845SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
60846  int nOp = p->nOp;
60847  VdbeOp *pOp;
60848  if( nOp<1 ) return;
60849  pOp = &p->aOp[0];
60850  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60851    const char *z = pOp->p4.z;
60852    while( sqlite3Isspace(*z) ) z++;
60853    printf("SQL: [%s]\n", z);
60854  }
60855}
60856#endif
60857
60858#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
60859/*
60860** Print an IOTRACE message showing SQL content.
60861*/
60862SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
60863  int nOp = p->nOp;
60864  VdbeOp *pOp;
60865  if( sqlite3IoTrace==0 ) return;
60866  if( nOp<1 ) return;
60867  pOp = &p->aOp[0];
60868  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60869    int i, j;
60870    char z[1000];
60871    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
60872    for(i=0; sqlite3Isspace(z[i]); i++){}
60873    for(j=0; z[i]; i++){
60874      if( sqlite3Isspace(z[i]) ){
60875        if( z[i-1]!=' ' ){
60876          z[j++] = ' ';
60877        }
60878      }else{
60879        z[j++] = z[i];
60880      }
60881    }
60882    z[j] = 0;
60883    sqlite3IoTrace("SQL %s\n", z);
60884  }
60885}
60886#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
60887
60888/*
60889** Allocate space from a fixed size buffer and return a pointer to
60890** that space.  If insufficient space is available, return NULL.
60891**
60892** The pBuf parameter is the initial value of a pointer which will
60893** receive the new memory.  pBuf is normally NULL.  If pBuf is not
60894** NULL, it means that memory space has already been allocated and that
60895** this routine should not allocate any new memory.  When pBuf is not
60896** NULL simply return pBuf.  Only allocate new memory space when pBuf
60897** is NULL.
60898**
60899** nByte is the number of bytes of space needed.
60900**
60901** *ppFrom points to available space and pEnd points to the end of the
60902** available space.  When space is allocated, *ppFrom is advanced past
60903** the end of the allocated space.
60904**
60905** *pnByte is a counter of the number of bytes of space that have failed
60906** to allocate.  If there is insufficient space in *ppFrom to satisfy the
60907** request, then increment *pnByte by the amount of the request.
60908*/
60909static void *allocSpace(
60910  void *pBuf,          /* Where return pointer will be stored */
60911  int nByte,           /* Number of bytes to allocate */
60912  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
60913  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
60914  int *pnByte          /* If allocation cannot be made, increment *pnByte */
60915){
60916  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
60917  if( pBuf ) return pBuf;
60918  nByte = ROUND8(nByte);
60919  if( &(*ppFrom)[nByte] <= pEnd ){
60920    pBuf = (void*)*ppFrom;
60921    *ppFrom += nByte;
60922  }else{
60923    *pnByte += nByte;
60924  }
60925  return pBuf;
60926}
60927
60928/*
60929** Rewind the VDBE back to the beginning in preparation for
60930** running it.
60931*/
60932SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
60933#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
60934  int i;
60935#endif
60936  assert( p!=0 );
60937  assert( p->magic==VDBE_MAGIC_INIT );
60938
60939  /* There should be at least one opcode.
60940  */
60941  assert( p->nOp>0 );
60942
60943  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
60944  p->magic = VDBE_MAGIC_RUN;
60945
60946#ifdef SQLITE_DEBUG
60947  for(i=1; i<p->nMem; i++){
60948    assert( p->aMem[i].db==p->db );
60949  }
60950#endif
60951  p->pc = -1;
60952  p->rc = SQLITE_OK;
60953  p->errorAction = OE_Abort;
60954  p->magic = VDBE_MAGIC_RUN;
60955  p->nChange = 0;
60956  p->cacheCtr = 1;
60957  p->minWriteFileFormat = 255;
60958  p->iStatement = 0;
60959  p->nFkConstraint = 0;
60960#ifdef VDBE_PROFILE
60961  for(i=0; i<p->nOp; i++){
60962    p->aOp[i].cnt = 0;
60963    p->aOp[i].cycles = 0;
60964  }
60965#endif
60966}
60967
60968/*
60969** Prepare a virtual machine for execution for the first time after
60970** creating the virtual machine.  This involves things such
60971** as allocating stack space and initializing the program counter.
60972** After the VDBE has be prepped, it can be executed by one or more
60973** calls to sqlite3VdbeExec().
60974**
60975** This function may be called exact once on a each virtual machine.
60976** After this routine is called the VM has been "packaged" and is ready
60977** to run.  After this routine is called, futher calls to
60978** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
60979** the Vdbe from the Parse object that helped generate it so that the
60980** the Vdbe becomes an independent entity and the Parse object can be
60981** destroyed.
60982**
60983** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
60984** to its initial state after it has been run.
60985*/
60986SQLITE_PRIVATE void sqlite3VdbeMakeReady(
60987  Vdbe *p,                       /* The VDBE */
60988  Parse *pParse                  /* Parsing context */
60989){
60990  sqlite3 *db;                   /* The database connection */
60991  int nVar;                      /* Number of parameters */
60992  int nMem;                      /* Number of VM memory registers */
60993  int nCursor;                   /* Number of cursors required */
60994  int nArg;                      /* Number of arguments in subprograms */
60995  int nOnce;                     /* Number of OP_Once instructions */
60996  int n;                         /* Loop counter */
60997  u8 *zCsr;                      /* Memory available for allocation */
60998  u8 *zEnd;                      /* First byte past allocated memory */
60999  int nByte;                     /* How much extra memory is needed */
61000
61001  assert( p!=0 );
61002  assert( p->nOp>0 );
61003  assert( pParse!=0 );
61004  assert( p->magic==VDBE_MAGIC_INIT );
61005  db = p->db;
61006  assert( db->mallocFailed==0 );
61007  nVar = pParse->nVar;
61008  nMem = pParse->nMem;
61009  nCursor = pParse->nTab;
61010  nArg = pParse->nMaxArg;
61011  nOnce = pParse->nOnce;
61012  if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
61013
61014  /* For each cursor required, also allocate a memory cell. Memory
61015  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
61016  ** the vdbe program. Instead they are used to allocate space for
61017  ** VdbeCursor/BtCursor structures. The blob of memory associated with
61018  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
61019  ** stores the blob of memory associated with cursor 1, etc.
61020  **
61021  ** See also: allocateCursor().
61022  */
61023  nMem += nCursor;
61024
61025  /* Allocate space for memory registers, SQL variables, VDBE cursors and
61026  ** an array to marshal SQL function arguments in.
61027  */
61028  zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
61029  zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
61030
61031  resolveP2Values(p, &nArg);
61032  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
61033  if( pParse->explain && nMem<10 ){
61034    nMem = 10;
61035  }
61036  memset(zCsr, 0, zEnd-zCsr);
61037  zCsr += (zCsr - (u8*)0)&7;
61038  assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
61039  p->expired = 0;
61040
61041  /* Memory for registers, parameters, cursor, etc, is allocated in two
61042  ** passes.  On the first pass, we try to reuse unused space at the
61043  ** end of the opcode array.  If we are unable to satisfy all memory
61044  ** requirements by reusing the opcode array tail, then the second
61045  ** pass will fill in the rest using a fresh allocation.
61046  **
61047  ** This two-pass approach that reuses as much memory as possible from
61048  ** the leftover space at the end of the opcode array can significantly
61049  ** reduce the amount of memory held by a prepared statement.
61050  */
61051  do {
61052    nByte = 0;
61053    p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
61054    p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
61055    p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
61056    p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
61057    p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
61058                          &zCsr, zEnd, &nByte);
61059    p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
61060    if( nByte ){
61061      p->pFree = sqlite3DbMallocZero(db, nByte);
61062    }
61063    zCsr = p->pFree;
61064    zEnd = &zCsr[nByte];
61065  }while( nByte && !db->mallocFailed );
61066
61067  p->nCursor = (u16)nCursor;
61068  p->nOnceFlag = nOnce;
61069  if( p->aVar ){
61070    p->nVar = (ynVar)nVar;
61071    for(n=0; n<nVar; n++){
61072      p->aVar[n].flags = MEM_Null;
61073      p->aVar[n].db = db;
61074    }
61075  }
61076  if( p->azVar ){
61077    p->nzVar = pParse->nzVar;
61078    memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
61079    memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
61080  }
61081  if( p->aMem ){
61082    p->aMem--;                      /* aMem[] goes from 1..nMem */
61083    p->nMem = nMem;                 /*       not from 0..nMem-1 */
61084    for(n=1; n<=nMem; n++){
61085      p->aMem[n].flags = MEM_Invalid;
61086      p->aMem[n].db = db;
61087    }
61088  }
61089  p->explain = pParse->explain;
61090  sqlite3VdbeRewind(p);
61091}
61092
61093/*
61094** Close a VDBE cursor and release all the resources that cursor
61095** happens to hold.
61096*/
61097SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
61098  if( pCx==0 ){
61099    return;
61100  }
61101  sqlite3VdbeSorterClose(p->db, pCx);
61102  if( pCx->pBt ){
61103    sqlite3BtreeClose(pCx->pBt);
61104    /* The pCx->pCursor will be close automatically, if it exists, by
61105    ** the call above. */
61106  }else if( pCx->pCursor ){
61107    sqlite3BtreeCloseCursor(pCx->pCursor);
61108  }
61109#ifndef SQLITE_OMIT_VIRTUALTABLE
61110  if( pCx->pVtabCursor ){
61111    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
61112    const sqlite3_module *pModule = pCx->pModule;
61113    p->inVtabMethod = 1;
61114    pModule->xClose(pVtabCursor);
61115    p->inVtabMethod = 0;
61116  }
61117#endif
61118}
61119
61120/*
61121** Copy the values stored in the VdbeFrame structure to its Vdbe. This
61122** is used, for example, when a trigger sub-program is halted to restore
61123** control to the main program.
61124*/
61125SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
61126  Vdbe *v = pFrame->v;
61127  v->aOnceFlag = pFrame->aOnceFlag;
61128  v->nOnceFlag = pFrame->nOnceFlag;
61129  v->aOp = pFrame->aOp;
61130  v->nOp = pFrame->nOp;
61131  v->aMem = pFrame->aMem;
61132  v->nMem = pFrame->nMem;
61133  v->apCsr = pFrame->apCsr;
61134  v->nCursor = pFrame->nCursor;
61135  v->db->lastRowid = pFrame->lastRowid;
61136  v->nChange = pFrame->nChange;
61137  return pFrame->pc;
61138}
61139
61140/*
61141** Close all cursors.
61142**
61143** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
61144** cell array. This is necessary as the memory cell array may contain
61145** pointers to VdbeFrame objects, which may in turn contain pointers to
61146** open cursors.
61147*/
61148static void closeAllCursors(Vdbe *p){
61149  if( p->pFrame ){
61150    VdbeFrame *pFrame;
61151    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
61152    sqlite3VdbeFrameRestore(pFrame);
61153  }
61154  p->pFrame = 0;
61155  p->nFrame = 0;
61156
61157  if( p->apCsr ){
61158    int i;
61159    for(i=0; i<p->nCursor; i++){
61160      VdbeCursor *pC = p->apCsr[i];
61161      if( pC ){
61162        sqlite3VdbeFreeCursor(p, pC);
61163        p->apCsr[i] = 0;
61164      }
61165    }
61166  }
61167  if( p->aMem ){
61168    releaseMemArray(&p->aMem[1], p->nMem);
61169  }
61170  while( p->pDelFrame ){
61171    VdbeFrame *pDel = p->pDelFrame;
61172    p->pDelFrame = pDel->pParent;
61173    sqlite3VdbeFrameDelete(pDel);
61174  }
61175}
61176
61177/*
61178** Clean up the VM after execution.
61179**
61180** This routine will automatically close any cursors, lists, and/or
61181** sorters that were left open.  It also deletes the values of
61182** variables in the aVar[] array.
61183*/
61184static void Cleanup(Vdbe *p){
61185  sqlite3 *db = p->db;
61186
61187#ifdef SQLITE_DEBUG
61188  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
61189  ** Vdbe.aMem[] arrays have already been cleaned up.  */
61190  int i;
61191  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
61192  if( p->aMem ){
61193    for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
61194  }
61195#endif
61196
61197  sqlite3DbFree(db, p->zErrMsg);
61198  p->zErrMsg = 0;
61199  p->pResultSet = 0;
61200}
61201
61202/*
61203** Set the number of result columns that will be returned by this SQL
61204** statement. This is now set at compile time, rather than during
61205** execution of the vdbe program so that sqlite3_column_count() can
61206** be called on an SQL statement before sqlite3_step().
61207*/
61208SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
61209  Mem *pColName;
61210  int n;
61211  sqlite3 *db = p->db;
61212
61213  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61214  sqlite3DbFree(db, p->aColName);
61215  n = nResColumn*COLNAME_N;
61216  p->nResColumn = (u16)nResColumn;
61217  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
61218  if( p->aColName==0 ) return;
61219  while( n-- > 0 ){
61220    pColName->flags = MEM_Null;
61221    pColName->db = p->db;
61222    pColName++;
61223  }
61224}
61225
61226/*
61227** Set the name of the idx'th column to be returned by the SQL statement.
61228** zName must be a pointer to a nul terminated string.
61229**
61230** This call must be made after a call to sqlite3VdbeSetNumCols().
61231**
61232** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
61233** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
61234** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
61235*/
61236SQLITE_PRIVATE int sqlite3VdbeSetColName(
61237  Vdbe *p,                         /* Vdbe being configured */
61238  int idx,                         /* Index of column zName applies to */
61239  int var,                         /* One of the COLNAME_* constants */
61240  const char *zName,               /* Pointer to buffer containing name */
61241  void (*xDel)(void*)              /* Memory management strategy for zName */
61242){
61243  int rc;
61244  Mem *pColName;
61245  assert( idx<p->nResColumn );
61246  assert( var<COLNAME_N );
61247  if( p->db->mallocFailed ){
61248    assert( !zName || xDel!=SQLITE_DYNAMIC );
61249    return SQLITE_NOMEM;
61250  }
61251  assert( p->aColName!=0 );
61252  pColName = &(p->aColName[idx+var*p->nResColumn]);
61253  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
61254  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
61255  return rc;
61256}
61257
61258/*
61259** A read or write transaction may or may not be active on database handle
61260** db. If a transaction is active, commit it. If there is a
61261** write-transaction spanning more than one database file, this routine
61262** takes care of the master journal trickery.
61263*/
61264static int vdbeCommit(sqlite3 *db, Vdbe *p){
61265  int i;
61266  int nTrans = 0;  /* Number of databases with an active write-transaction */
61267  int rc = SQLITE_OK;
61268  int needXcommit = 0;
61269
61270#ifdef SQLITE_OMIT_VIRTUALTABLE
61271  /* With this option, sqlite3VtabSync() is defined to be simply
61272  ** SQLITE_OK so p is not used.
61273  */
61274  UNUSED_PARAMETER(p);
61275#endif
61276
61277  /* Before doing anything else, call the xSync() callback for any
61278  ** virtual module tables written in this transaction. This has to
61279  ** be done before determining whether a master journal file is
61280  ** required, as an xSync() callback may add an attached database
61281  ** to the transaction.
61282  */
61283  rc = sqlite3VtabSync(db, &p->zErrMsg);
61284
61285  /* This loop determines (a) if the commit hook should be invoked and
61286  ** (b) how many database files have open write transactions, not
61287  ** including the temp database. (b) is important because if more than
61288  ** one database file has an open write transaction, a master journal
61289  ** file is required for an atomic commit.
61290  */
61291  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61292    Btree *pBt = db->aDb[i].pBt;
61293    if( sqlite3BtreeIsInTrans(pBt) ){
61294      needXcommit = 1;
61295      if( i!=1 ) nTrans++;
61296      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
61297    }
61298  }
61299  if( rc!=SQLITE_OK ){
61300    return rc;
61301  }
61302
61303  /* If there are any write-transactions at all, invoke the commit hook */
61304  if( needXcommit && db->xCommitCallback ){
61305    rc = db->xCommitCallback(db->pCommitArg);
61306    if( rc ){
61307      return SQLITE_CONSTRAINT;
61308    }
61309  }
61310
61311  /* The simple case - no more than one database file (not counting the
61312  ** TEMP database) has a transaction active.   There is no need for the
61313  ** master-journal.
61314  **
61315  ** If the return value of sqlite3BtreeGetFilename() is a zero length
61316  ** string, it means the main database is :memory: or a temp file.  In
61317  ** that case we do not support atomic multi-file commits, so use the
61318  ** simple case then too.
61319  */
61320  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
61321   || nTrans<=1
61322  ){
61323    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61324      Btree *pBt = db->aDb[i].pBt;
61325      if( pBt ){
61326        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
61327      }
61328    }
61329
61330    /* Do the commit only if all databases successfully complete phase 1.
61331    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
61332    ** IO error while deleting or truncating a journal file. It is unlikely,
61333    ** but could happen. In this case abandon processing and return the error.
61334    */
61335    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61336      Btree *pBt = db->aDb[i].pBt;
61337      if( pBt ){
61338        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
61339      }
61340    }
61341    if( rc==SQLITE_OK ){
61342      sqlite3VtabCommit(db);
61343    }
61344  }
61345
61346  /* The complex case - There is a multi-file write-transaction active.
61347  ** This requires a master journal file to ensure the transaction is
61348  ** committed atomicly.
61349  */
61350#ifndef SQLITE_OMIT_DISKIO
61351  else{
61352    sqlite3_vfs *pVfs = db->pVfs;
61353    int needSync = 0;
61354    char *zMaster = 0;   /* File-name for the master journal */
61355    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
61356    sqlite3_file *pMaster = 0;
61357    i64 offset = 0;
61358    int res;
61359    int retryCount = 0;
61360    int nMainFile;
61361
61362    /* Select a master journal file name */
61363    nMainFile = sqlite3Strlen30(zMainFile);
61364    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
61365    if( zMaster==0 ) return SQLITE_NOMEM;
61366    do {
61367      u32 iRandom;
61368      if( retryCount ){
61369        if( retryCount>100 ){
61370          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
61371          sqlite3OsDelete(pVfs, zMaster, 0);
61372          break;
61373        }else if( retryCount==1 ){
61374          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
61375        }
61376      }
61377      retryCount++;
61378      sqlite3_randomness(sizeof(iRandom), &iRandom);
61379      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
61380                               (iRandom>>8)&0xffffff, iRandom&0xff);
61381      /* The antipenultimate character of the master journal name must
61382      ** be "9" to avoid name collisions when using 8+3 filenames. */
61383      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
61384      sqlite3FileSuffix3(zMainFile, zMaster);
61385      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
61386    }while( rc==SQLITE_OK && res );
61387    if( rc==SQLITE_OK ){
61388      /* Open the master journal. */
61389      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
61390          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
61391          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
61392      );
61393    }
61394    if( rc!=SQLITE_OK ){
61395      sqlite3DbFree(db, zMaster);
61396      return rc;
61397    }
61398
61399    /* Write the name of each database file in the transaction into the new
61400    ** master journal file. If an error occurs at this point close
61401    ** and delete the master journal file. All the individual journal files
61402    ** still have 'null' as the master journal pointer, so they will roll
61403    ** back independently if a failure occurs.
61404    */
61405    for(i=0; i<db->nDb; i++){
61406      Btree *pBt = db->aDb[i].pBt;
61407      if( sqlite3BtreeIsInTrans(pBt) ){
61408        char const *zFile = sqlite3BtreeGetJournalname(pBt);
61409        if( zFile==0 ){
61410          continue;  /* Ignore TEMP and :memory: databases */
61411        }
61412        assert( zFile[0]!=0 );
61413        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
61414          needSync = 1;
61415        }
61416        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
61417        offset += sqlite3Strlen30(zFile)+1;
61418        if( rc!=SQLITE_OK ){
61419          sqlite3OsCloseFree(pMaster);
61420          sqlite3OsDelete(pVfs, zMaster, 0);
61421          sqlite3DbFree(db, zMaster);
61422          return rc;
61423        }
61424      }
61425    }
61426
61427    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
61428    ** flag is set this is not required.
61429    */
61430    if( needSync
61431     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
61432     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
61433    ){
61434      sqlite3OsCloseFree(pMaster);
61435      sqlite3OsDelete(pVfs, zMaster, 0);
61436      sqlite3DbFree(db, zMaster);
61437      return rc;
61438    }
61439
61440    /* Sync all the db files involved in the transaction. The same call
61441    ** sets the master journal pointer in each individual journal. If
61442    ** an error occurs here, do not delete the master journal file.
61443    **
61444    ** If the error occurs during the first call to
61445    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
61446    ** master journal file will be orphaned. But we cannot delete it,
61447    ** in case the master journal file name was written into the journal
61448    ** file before the failure occurred.
61449    */
61450    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61451      Btree *pBt = db->aDb[i].pBt;
61452      if( pBt ){
61453        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
61454      }
61455    }
61456    sqlite3OsCloseFree(pMaster);
61457    assert( rc!=SQLITE_BUSY );
61458    if( rc!=SQLITE_OK ){
61459      sqlite3DbFree(db, zMaster);
61460      return rc;
61461    }
61462
61463    /* Delete the master journal file. This commits the transaction. After
61464    ** doing this the directory is synced again before any individual
61465    ** transaction files are deleted.
61466    */
61467    rc = sqlite3OsDelete(pVfs, zMaster, 1);
61468    sqlite3DbFree(db, zMaster);
61469    zMaster = 0;
61470    if( rc ){
61471      return rc;
61472    }
61473
61474    /* All files and directories have already been synced, so the following
61475    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
61476    ** deleting or truncating journals. If something goes wrong while
61477    ** this is happening we don't really care. The integrity of the
61478    ** transaction is already guaranteed, but some stray 'cold' journals
61479    ** may be lying around. Returning an error code won't help matters.
61480    */
61481    disable_simulated_io_errors();
61482    sqlite3BeginBenignMalloc();
61483    for(i=0; i<db->nDb; i++){
61484      Btree *pBt = db->aDb[i].pBt;
61485      if( pBt ){
61486        sqlite3BtreeCommitPhaseTwo(pBt, 1);
61487      }
61488    }
61489    sqlite3EndBenignMalloc();
61490    enable_simulated_io_errors();
61491
61492    sqlite3VtabCommit(db);
61493  }
61494#endif
61495
61496  return rc;
61497}
61498
61499/*
61500** This routine checks that the sqlite3.activeVdbeCnt count variable
61501** matches the number of vdbe's in the list sqlite3.pVdbe that are
61502** currently active. An assertion fails if the two counts do not match.
61503** This is an internal self-check only - it is not an essential processing
61504** step.
61505**
61506** This is a no-op if NDEBUG is defined.
61507*/
61508#ifndef NDEBUG
61509static void checkActiveVdbeCnt(sqlite3 *db){
61510  Vdbe *p;
61511  int cnt = 0;
61512  int nWrite = 0;
61513  p = db->pVdbe;
61514  while( p ){
61515    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
61516      cnt++;
61517      if( p->readOnly==0 ) nWrite++;
61518    }
61519    p = p->pNext;
61520  }
61521  assert( cnt==db->activeVdbeCnt );
61522  assert( nWrite==db->writeVdbeCnt );
61523}
61524#else
61525#define checkActiveVdbeCnt(x)
61526#endif
61527
61528/*
61529** If the Vdbe passed as the first argument opened a statement-transaction,
61530** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
61531** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
61532** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
61533** statement transaction is commtted.
61534**
61535** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
61536** Otherwise SQLITE_OK.
61537*/
61538SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
61539  sqlite3 *const db = p->db;
61540  int rc = SQLITE_OK;
61541
61542  /* If p->iStatement is greater than zero, then this Vdbe opened a
61543  ** statement transaction that should be closed here. The only exception
61544  ** is that an IO error may have occured, causing an emergency rollback.
61545  ** In this case (db->nStatement==0), and there is nothing to do.
61546  */
61547  if( db->nStatement && p->iStatement ){
61548    int i;
61549    const int iSavepoint = p->iStatement-1;
61550
61551    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
61552    assert( db->nStatement>0 );
61553    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
61554
61555    for(i=0; i<db->nDb; i++){
61556      int rc2 = SQLITE_OK;
61557      Btree *pBt = db->aDb[i].pBt;
61558      if( pBt ){
61559        if( eOp==SAVEPOINT_ROLLBACK ){
61560          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
61561        }
61562        if( rc2==SQLITE_OK ){
61563          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
61564        }
61565        if( rc==SQLITE_OK ){
61566          rc = rc2;
61567        }
61568      }
61569    }
61570    db->nStatement--;
61571    p->iStatement = 0;
61572
61573    if( rc==SQLITE_OK ){
61574      if( eOp==SAVEPOINT_ROLLBACK ){
61575        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
61576      }
61577      if( rc==SQLITE_OK ){
61578        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
61579      }
61580    }
61581
61582    /* If the statement transaction is being rolled back, also restore the
61583    ** database handles deferred constraint counter to the value it had when
61584    ** the statement transaction was opened.  */
61585    if( eOp==SAVEPOINT_ROLLBACK ){
61586      db->nDeferredCons = p->nStmtDefCons;
61587    }
61588  }
61589  return rc;
61590}
61591
61592/*
61593** This function is called when a transaction opened by the database
61594** handle associated with the VM passed as an argument is about to be
61595** committed. If there are outstanding deferred foreign key constraint
61596** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
61597**
61598** If there are outstanding FK violations and this function returns
61599** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
61600** an error message to it. Then return SQLITE_ERROR.
61601*/
61602#ifndef SQLITE_OMIT_FOREIGN_KEY
61603SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
61604  sqlite3 *db = p->db;
61605  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
61606    p->rc = SQLITE_CONSTRAINT;
61607    p->errorAction = OE_Abort;
61608    sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
61609    return SQLITE_ERROR;
61610  }
61611  return SQLITE_OK;
61612}
61613#endif
61614
61615/*
61616** This routine is called the when a VDBE tries to halt.  If the VDBE
61617** has made changes and is in autocommit mode, then commit those
61618** changes.  If a rollback is needed, then do the rollback.
61619**
61620** This routine is the only way to move the state of a VM from
61621** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
61622** call this on a VM that is in the SQLITE_MAGIC_HALT state.
61623**
61624** Return an error code.  If the commit could not complete because of
61625** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
61626** means the close did not happen and needs to be repeated.
61627*/
61628SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
61629  int rc;                         /* Used to store transient return codes */
61630  sqlite3 *db = p->db;
61631
61632  /* This function contains the logic that determines if a statement or
61633  ** transaction will be committed or rolled back as a result of the
61634  ** execution of this virtual machine.
61635  **
61636  ** If any of the following errors occur:
61637  **
61638  **     SQLITE_NOMEM
61639  **     SQLITE_IOERR
61640  **     SQLITE_FULL
61641  **     SQLITE_INTERRUPT
61642  **
61643  ** Then the internal cache might have been left in an inconsistent
61644  ** state.  We need to rollback the statement transaction, if there is
61645  ** one, or the complete transaction if there is no statement transaction.
61646  */
61647
61648  if( p->db->mallocFailed ){
61649    p->rc = SQLITE_NOMEM;
61650  }
61651  if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
61652  closeAllCursors(p);
61653  if( p->magic!=VDBE_MAGIC_RUN ){
61654    return SQLITE_OK;
61655  }
61656  checkActiveVdbeCnt(db);
61657
61658  /* No commit or rollback needed if the program never started */
61659  if( p->pc>=0 ){
61660    int mrc;   /* Primary error code from p->rc */
61661    int eStatementOp = 0;
61662    int isSpecialError;            /* Set to true if a 'special' error */
61663
61664    /* Lock all btrees used by the statement */
61665    sqlite3VdbeEnter(p);
61666
61667    /* Check for one of the special errors */
61668    mrc = p->rc & 0xff;
61669    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
61670    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
61671                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
61672    if( isSpecialError ){
61673      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
61674      ** no rollback is necessary. Otherwise, at least a savepoint
61675      ** transaction must be rolled back to restore the database to a
61676      ** consistent state.
61677      **
61678      ** Even if the statement is read-only, it is important to perform
61679      ** a statement or transaction rollback operation. If the error
61680      ** occured while writing to the journal, sub-journal or database
61681      ** file as part of an effort to free up cache space (see function
61682      ** pagerStress() in pager.c), the rollback is required to restore
61683      ** the pager to a consistent state.
61684      */
61685      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
61686        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
61687          eStatementOp = SAVEPOINT_ROLLBACK;
61688        }else{
61689          /* We are forced to roll back the active transaction. Before doing
61690          ** so, abort any other statements this handle currently has active.
61691          */
61692          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
61693          sqlite3CloseSavepoints(db);
61694          db->autoCommit = 1;
61695        }
61696      }
61697    }
61698
61699    /* Check for immediate foreign key violations. */
61700    if( p->rc==SQLITE_OK ){
61701      sqlite3VdbeCheckFk(p, 0);
61702    }
61703
61704    /* If the auto-commit flag is set and this is the only active writer
61705    ** VM, then we do either a commit or rollback of the current transaction.
61706    **
61707    ** Note: This block also runs if one of the special errors handled
61708    ** above has occurred.
61709    */
61710    if( !sqlite3VtabInSync(db)
61711     && db->autoCommit
61712     && db->writeVdbeCnt==(p->readOnly==0)
61713    ){
61714      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
61715        rc = sqlite3VdbeCheckFk(p, 1);
61716        if( rc!=SQLITE_OK ){
61717          if( NEVER(p->readOnly) ){
61718            sqlite3VdbeLeave(p);
61719            return SQLITE_ERROR;
61720          }
61721          rc = SQLITE_CONSTRAINT;
61722        }else{
61723          /* The auto-commit flag is true, the vdbe program was successful
61724          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
61725          ** key constraints to hold up the transaction. This means a commit
61726          ** is required. */
61727          rc = vdbeCommit(db, p);
61728        }
61729        if( rc==SQLITE_BUSY && p->readOnly ){
61730          sqlite3VdbeLeave(p);
61731          return SQLITE_BUSY;
61732        }else if( rc!=SQLITE_OK ){
61733          p->rc = rc;
61734          sqlite3RollbackAll(db, SQLITE_OK);
61735        }else{
61736          db->nDeferredCons = 0;
61737          sqlite3CommitInternalChanges(db);
61738        }
61739      }else{
61740        sqlite3RollbackAll(db, SQLITE_OK);
61741      }
61742      db->nStatement = 0;
61743    }else if( eStatementOp==0 ){
61744      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
61745        eStatementOp = SAVEPOINT_RELEASE;
61746      }else if( p->errorAction==OE_Abort ){
61747        eStatementOp = SAVEPOINT_ROLLBACK;
61748      }else{
61749        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
61750        sqlite3CloseSavepoints(db);
61751        db->autoCommit = 1;
61752      }
61753    }
61754
61755    /* If eStatementOp is non-zero, then a statement transaction needs to
61756    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
61757    ** do so. If this operation returns an error, and the current statement
61758    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
61759    ** current statement error code.
61760    */
61761    if( eStatementOp ){
61762      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
61763      if( rc ){
61764        if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
61765          p->rc = rc;
61766          sqlite3DbFree(db, p->zErrMsg);
61767          p->zErrMsg = 0;
61768        }
61769        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
61770        sqlite3CloseSavepoints(db);
61771        db->autoCommit = 1;
61772      }
61773    }
61774
61775    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
61776    ** has been rolled back, update the database connection change-counter.
61777    */
61778    if( p->changeCntOn ){
61779      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
61780        sqlite3VdbeSetChanges(db, p->nChange);
61781      }else{
61782        sqlite3VdbeSetChanges(db, 0);
61783      }
61784      p->nChange = 0;
61785    }
61786
61787    /* Release the locks */
61788    sqlite3VdbeLeave(p);
61789  }
61790
61791  /* We have successfully halted and closed the VM.  Record this fact. */
61792  if( p->pc>=0 ){
61793    db->activeVdbeCnt--;
61794    if( !p->readOnly ){
61795      db->writeVdbeCnt--;
61796    }
61797    assert( db->activeVdbeCnt>=db->writeVdbeCnt );
61798  }
61799  p->magic = VDBE_MAGIC_HALT;
61800  checkActiveVdbeCnt(db);
61801  if( p->db->mallocFailed ){
61802    p->rc = SQLITE_NOMEM;
61803  }
61804
61805  /* If the auto-commit flag is set to true, then any locks that were held
61806  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
61807  ** to invoke any required unlock-notify callbacks.
61808  */
61809  if( db->autoCommit ){
61810    sqlite3ConnectionUnlocked(db);
61811  }
61812
61813  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
61814  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
61815}
61816
61817
61818/*
61819** Each VDBE holds the result of the most recent sqlite3_step() call
61820** in p->rc.  This routine sets that result back to SQLITE_OK.
61821*/
61822SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
61823  p->rc = SQLITE_OK;
61824}
61825
61826/*
61827** Copy the error code and error message belonging to the VDBE passed
61828** as the first argument to its database handle (so that they will be
61829** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
61830**
61831** This function does not clear the VDBE error code or message, just
61832** copies them to the database handle.
61833*/
61834SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
61835  sqlite3 *db = p->db;
61836  int rc = p->rc;
61837  if( p->zErrMsg ){
61838    u8 mallocFailed = db->mallocFailed;
61839    sqlite3BeginBenignMalloc();
61840    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
61841    sqlite3EndBenignMalloc();
61842    db->mallocFailed = mallocFailed;
61843    db->errCode = rc;
61844  }else{
61845    sqlite3Error(db, rc, 0);
61846  }
61847  return rc;
61848}
61849
61850/*
61851** Clean up a VDBE after execution but do not delete the VDBE just yet.
61852** Write any error messages into *pzErrMsg.  Return the result code.
61853**
61854** After this routine is run, the VDBE should be ready to be executed
61855** again.
61856**
61857** To look at it another way, this routine resets the state of the
61858** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
61859** VDBE_MAGIC_INIT.
61860*/
61861SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
61862  sqlite3 *db;
61863  db = p->db;
61864
61865  /* If the VM did not run to completion or if it encountered an
61866  ** error, then it might not have been halted properly.  So halt
61867  ** it now.
61868  */
61869  sqlite3VdbeHalt(p);
61870
61871  /* If the VDBE has be run even partially, then transfer the error code
61872  ** and error message from the VDBE into the main database structure.  But
61873  ** if the VDBE has just been set to run but has not actually executed any
61874  ** instructions yet, leave the main database error information unchanged.
61875  */
61876  if( p->pc>=0 ){
61877    sqlite3VdbeTransferError(p);
61878    sqlite3DbFree(db, p->zErrMsg);
61879    p->zErrMsg = 0;
61880    if( p->runOnlyOnce ) p->expired = 1;
61881  }else if( p->rc && p->expired ){
61882    /* The expired flag was set on the VDBE before the first call
61883    ** to sqlite3_step(). For consistency (since sqlite3_step() was
61884    ** called), set the database error in this case as well.
61885    */
61886    sqlite3Error(db, p->rc, 0);
61887    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
61888    sqlite3DbFree(db, p->zErrMsg);
61889    p->zErrMsg = 0;
61890  }
61891
61892  /* Reclaim all memory used by the VDBE
61893  */
61894  Cleanup(p);
61895
61896  /* Save profiling information from this VDBE run.
61897  */
61898#ifdef VDBE_PROFILE
61899  {
61900    FILE *out = fopen("vdbe_profile.out", "a");
61901    if( out ){
61902      int i;
61903      fprintf(out, "---- ");
61904      for(i=0; i<p->nOp; i++){
61905        fprintf(out, "%02x", p->aOp[i].opcode);
61906      }
61907      fprintf(out, "\n");
61908      for(i=0; i<p->nOp; i++){
61909        fprintf(out, "%6d %10lld %8lld ",
61910           p->aOp[i].cnt,
61911           p->aOp[i].cycles,
61912           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
61913        );
61914        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
61915      }
61916      fclose(out);
61917    }
61918  }
61919#endif
61920  p->magic = VDBE_MAGIC_INIT;
61921  return p->rc & db->errMask;
61922}
61923
61924/*
61925** Clean up and delete a VDBE after execution.  Return an integer which is
61926** the result code.  Write any error message text into *pzErrMsg.
61927*/
61928SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
61929  int rc = SQLITE_OK;
61930  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
61931    rc = sqlite3VdbeReset(p);
61932    assert( (rc & p->db->errMask)==rc );
61933  }
61934  sqlite3VdbeDelete(p);
61935  return rc;
61936}
61937
61938/*
61939** Call the destructor for each auxdata entry in pVdbeFunc for which
61940** the corresponding bit in mask is clear.  Auxdata entries beyond 31
61941** are always destroyed.  To destroy all auxdata entries, call this
61942** routine with mask==0.
61943*/
61944SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
61945  int i;
61946  for(i=0; i<pVdbeFunc->nAux; i++){
61947    struct AuxData *pAux = &pVdbeFunc->apAux[i];
61948    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
61949      if( pAux->xDelete ){
61950        pAux->xDelete(pAux->pAux);
61951      }
61952      pAux->pAux = 0;
61953    }
61954  }
61955}
61956
61957/*
61958** Free all memory associated with the Vdbe passed as the second argument.
61959** The difference between this function and sqlite3VdbeDelete() is that
61960** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
61961** the database connection.
61962*/
61963SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
61964  SubProgram *pSub, *pNext;
61965  int i;
61966  assert( p->db==0 || p->db==db );
61967  releaseMemArray(p->aVar, p->nVar);
61968  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61969  for(pSub=p->pProgram; pSub; pSub=pNext){
61970    pNext = pSub->pNext;
61971    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
61972    sqlite3DbFree(db, pSub);
61973  }
61974  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
61975  vdbeFreeOpArray(db, p->aOp, p->nOp);
61976  sqlite3DbFree(db, p->aLabel);
61977  sqlite3DbFree(db, p->aColName);
61978  sqlite3DbFree(db, p->zSql);
61979  sqlite3DbFree(db, p->pFree);
61980#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
61981  sqlite3DbFree(db, p->zExplain);
61982  sqlite3DbFree(db, p->pExplain);
61983#endif
61984  sqlite3DbFree(db, p);
61985}
61986
61987/*
61988** Delete an entire VDBE.
61989*/
61990SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
61991  sqlite3 *db;
61992
61993  if( NEVER(p==0) ) return;
61994  db = p->db;
61995  if( p->pPrev ){
61996    p->pPrev->pNext = p->pNext;
61997  }else{
61998    assert( db->pVdbe==p );
61999    db->pVdbe = p->pNext;
62000  }
62001  if( p->pNext ){
62002    p->pNext->pPrev = p->pPrev;
62003  }
62004  p->magic = VDBE_MAGIC_DEAD;
62005  p->db = 0;
62006  sqlite3VdbeDeleteObject(db, p);
62007}
62008
62009/*
62010** Make sure the cursor p is ready to read or write the row to which it
62011** was last positioned.  Return an error code if an OOM fault or I/O error
62012** prevents us from positioning the cursor to its correct position.
62013**
62014** If a MoveTo operation is pending on the given cursor, then do that
62015** MoveTo now.  If no move is pending, check to see if the row has been
62016** deleted out from under the cursor and if it has, mark the row as
62017** a NULL row.
62018**
62019** If the cursor is already pointing to the correct row and that row has
62020** not been deleted out from under the cursor, then this routine is a no-op.
62021*/
62022SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
62023  if( p->deferredMoveto ){
62024    int res, rc;
62025#ifdef SQLITE_TEST
62026    extern int sqlite3_search_count;
62027#endif
62028    assert( p->isTable );
62029    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
62030    if( rc ) return rc;
62031    p->lastRowid = p->movetoTarget;
62032    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
62033    p->rowidIsValid = 1;
62034#ifdef SQLITE_TEST
62035    sqlite3_search_count++;
62036#endif
62037    p->deferredMoveto = 0;
62038    p->cacheStatus = CACHE_STALE;
62039  }else if( ALWAYS(p->pCursor) ){
62040    int hasMoved;
62041    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
62042    if( rc ) return rc;
62043    if( hasMoved ){
62044      p->cacheStatus = CACHE_STALE;
62045      p->nullRow = 1;
62046    }
62047  }
62048  return SQLITE_OK;
62049}
62050
62051/*
62052** The following functions:
62053**
62054** sqlite3VdbeSerialType()
62055** sqlite3VdbeSerialTypeLen()
62056** sqlite3VdbeSerialLen()
62057** sqlite3VdbeSerialPut()
62058** sqlite3VdbeSerialGet()
62059**
62060** encapsulate the code that serializes values for storage in SQLite
62061** data and index records. Each serialized value consists of a
62062** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
62063** integer, stored as a varint.
62064**
62065** In an SQLite index record, the serial type is stored directly before
62066** the blob of data that it corresponds to. In a table record, all serial
62067** types are stored at the start of the record, and the blobs of data at
62068** the end. Hence these functions allow the caller to handle the
62069** serial-type and data blob seperately.
62070**
62071** The following table describes the various storage classes for data:
62072**
62073**   serial type        bytes of data      type
62074**   --------------     ---------------    ---------------
62075**      0                     0            NULL
62076**      1                     1            signed integer
62077**      2                     2            signed integer
62078**      3                     3            signed integer
62079**      4                     4            signed integer
62080**      5                     6            signed integer
62081**      6                     8            signed integer
62082**      7                     8            IEEE float
62083**      8                     0            Integer constant 0
62084**      9                     0            Integer constant 1
62085**     10,11                               reserved for expansion
62086**    N>=12 and even       (N-12)/2        BLOB
62087**    N>=13 and odd        (N-13)/2        text
62088**
62089** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
62090** of SQLite will not understand those serial types.
62091*/
62092
62093/*
62094** Return the serial-type for the value stored in pMem.
62095*/
62096SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
62097  int flags = pMem->flags;
62098  int n;
62099
62100  if( flags&MEM_Null ){
62101    return 0;
62102  }
62103  if( flags&MEM_Int ){
62104    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
62105#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
62106    i64 i = pMem->u.i;
62107    u64 u;
62108    if( file_format>=4 && (i&1)==i ){
62109      return 8+(u32)i;
62110    }
62111    if( i<0 ){
62112      if( i<(-MAX_6BYTE) ) return 6;
62113      /* Previous test prevents:  u = -(-9223372036854775808) */
62114      u = -i;
62115    }else{
62116      u = i;
62117    }
62118    if( u<=127 ) return 1;
62119    if( u<=32767 ) return 2;
62120    if( u<=8388607 ) return 3;
62121    if( u<=2147483647 ) return 4;
62122    if( u<=MAX_6BYTE ) return 5;
62123    return 6;
62124  }
62125  if( flags&MEM_Real ){
62126    return 7;
62127  }
62128  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
62129  n = pMem->n;
62130  if( flags & MEM_Zero ){
62131    n += pMem->u.nZero;
62132  }
62133  assert( n>=0 );
62134  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
62135}
62136
62137/*
62138** Return the length of the data corresponding to the supplied serial-type.
62139*/
62140SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
62141  if( serial_type>=12 ){
62142    return (serial_type-12)/2;
62143  }else{
62144    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
62145    return aSize[serial_type];
62146  }
62147}
62148
62149/*
62150** If we are on an architecture with mixed-endian floating
62151** points (ex: ARM7) then swap the lower 4 bytes with the
62152** upper 4 bytes.  Return the result.
62153**
62154** For most architectures, this is a no-op.
62155**
62156** (later):  It is reported to me that the mixed-endian problem
62157** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
62158** that early versions of GCC stored the two words of a 64-bit
62159** float in the wrong order.  And that error has been propagated
62160** ever since.  The blame is not necessarily with GCC, though.
62161** GCC might have just copying the problem from a prior compiler.
62162** I am also told that newer versions of GCC that follow a different
62163** ABI get the byte order right.
62164**
62165** Developers using SQLite on an ARM7 should compile and run their
62166** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
62167** enabled, some asserts below will ensure that the byte order of
62168** floating point values is correct.
62169**
62170** (2007-08-30)  Frank van Vugt has studied this problem closely
62171** and has send his findings to the SQLite developers.  Frank
62172** writes that some Linux kernels offer floating point hardware
62173** emulation that uses only 32-bit mantissas instead of a full
62174** 48-bits as required by the IEEE standard.  (This is the
62175** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
62176** byte swapping becomes very complicated.  To avoid problems,
62177** the necessary byte swapping is carried out using a 64-bit integer
62178** rather than a 64-bit float.  Frank assures us that the code here
62179** works for him.  We, the developers, have no way to independently
62180** verify this, but Frank seems to know what he is talking about
62181** so we trust him.
62182*/
62183#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
62184static u64 floatSwap(u64 in){
62185  union {
62186    u64 r;
62187    u32 i[2];
62188  } u;
62189  u32 t;
62190
62191  u.r = in;
62192  t = u.i[0];
62193  u.i[0] = u.i[1];
62194  u.i[1] = t;
62195  return u.r;
62196}
62197# define swapMixedEndianFloat(X)  X = floatSwap(X)
62198#else
62199# define swapMixedEndianFloat(X)
62200#endif
62201
62202/*
62203** Write the serialized data blob for the value stored in pMem into
62204** buf. It is assumed that the caller has allocated sufficient space.
62205** Return the number of bytes written.
62206**
62207** nBuf is the amount of space left in buf[].  nBuf must always be
62208** large enough to hold the entire field.  Except, if the field is
62209** a blob with a zero-filled tail, then buf[] might be just the right
62210** size to hold everything except for the zero-filled tail.  If buf[]
62211** is only big enough to hold the non-zero prefix, then only write that
62212** prefix into buf[].  But if buf[] is large enough to hold both the
62213** prefix and the tail then write the prefix and set the tail to all
62214** zeros.
62215**
62216** Return the number of bytes actually written into buf[].  The number
62217** of bytes in the zero-filled tail is included in the return value only
62218** if those bytes were zeroed in buf[].
62219*/
62220SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
62221  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
62222  u32 len;
62223
62224  /* Integer and Real */
62225  if( serial_type<=7 && serial_type>0 ){
62226    u64 v;
62227    u32 i;
62228    if( serial_type==7 ){
62229      assert( sizeof(v)==sizeof(pMem->r) );
62230      memcpy(&v, &pMem->r, sizeof(v));
62231      swapMixedEndianFloat(v);
62232    }else{
62233      v = pMem->u.i;
62234    }
62235    len = i = sqlite3VdbeSerialTypeLen(serial_type);
62236    assert( len<=(u32)nBuf );
62237    while( i-- ){
62238      buf[i] = (u8)(v&0xFF);
62239      v >>= 8;
62240    }
62241    return len;
62242  }
62243
62244  /* String or blob */
62245  if( serial_type>=12 ){
62246    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
62247             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
62248    assert( pMem->n<=nBuf );
62249    len = pMem->n;
62250    memcpy(buf, pMem->z, len);
62251    if( pMem->flags & MEM_Zero ){
62252      len += pMem->u.nZero;
62253      assert( nBuf>=0 );
62254      if( len > (u32)nBuf ){
62255        len = (u32)nBuf;
62256      }
62257      memset(&buf[pMem->n], 0, len-pMem->n);
62258    }
62259    return len;
62260  }
62261
62262  /* NULL or constants 0 or 1 */
62263  return 0;
62264}
62265
62266/*
62267** Deserialize the data blob pointed to by buf as serial type serial_type
62268** and store the result in pMem.  Return the number of bytes read.
62269*/
62270SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
62271  const unsigned char *buf,     /* Buffer to deserialize from */
62272  u32 serial_type,              /* Serial type to deserialize */
62273  Mem *pMem                     /* Memory cell to write value into */
62274){
62275  switch( serial_type ){
62276    case 10:   /* Reserved for future use */
62277    case 11:   /* Reserved for future use */
62278    case 0: {  /* NULL */
62279      pMem->flags = MEM_Null;
62280      break;
62281    }
62282    case 1: { /* 1-byte signed integer */
62283      pMem->u.i = (signed char)buf[0];
62284      pMem->flags = MEM_Int;
62285      return 1;
62286    }
62287    case 2: { /* 2-byte signed integer */
62288      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
62289      pMem->flags = MEM_Int;
62290      return 2;
62291    }
62292    case 3: { /* 3-byte signed integer */
62293      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
62294      pMem->flags = MEM_Int;
62295      return 3;
62296    }
62297    case 4: { /* 4-byte signed integer */
62298      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62299      pMem->flags = MEM_Int;
62300      return 4;
62301    }
62302    case 5: { /* 6-byte signed integer */
62303      u64 x = (((signed char)buf[0])<<8) | buf[1];
62304      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
62305      x = (x<<32) | y;
62306      pMem->u.i = *(i64*)&x;
62307      pMem->flags = MEM_Int;
62308      return 6;
62309    }
62310    case 6:   /* 8-byte signed integer */
62311    case 7: { /* IEEE floating point */
62312      u64 x;
62313      u32 y;
62314#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
62315      /* Verify that integers and floating point values use the same
62316      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
62317      ** defined that 64-bit floating point values really are mixed
62318      ** endian.
62319      */
62320      static const u64 t1 = ((u64)0x3ff00000)<<32;
62321      static const double r1 = 1.0;
62322      u64 t2 = t1;
62323      swapMixedEndianFloat(t2);
62324      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
62325#endif
62326
62327      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62328      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
62329      x = (x<<32) | y;
62330      if( serial_type==6 ){
62331        pMem->u.i = *(i64*)&x;
62332        pMem->flags = MEM_Int;
62333      }else{
62334        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
62335        swapMixedEndianFloat(x);
62336        memcpy(&pMem->r, &x, sizeof(x));
62337        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
62338      }
62339      return 8;
62340    }
62341    case 8:    /* Integer 0 */
62342    case 9: {  /* Integer 1 */
62343      pMem->u.i = serial_type-8;
62344      pMem->flags = MEM_Int;
62345      return 0;
62346    }
62347    default: {
62348      u32 len = (serial_type-12)/2;
62349      pMem->z = (char *)buf;
62350      pMem->n = len;
62351      pMem->xDel = 0;
62352      if( serial_type&0x01 ){
62353        pMem->flags = MEM_Str | MEM_Ephem;
62354      }else{
62355        pMem->flags = MEM_Blob | MEM_Ephem;
62356      }
62357      return len;
62358    }
62359  }
62360  return 0;
62361}
62362
62363/*
62364** This routine is used to allocate sufficient space for an UnpackedRecord
62365** structure large enough to be used with sqlite3VdbeRecordUnpack() if
62366** the first argument is a pointer to KeyInfo structure pKeyInfo.
62367**
62368** The space is either allocated using sqlite3DbMallocRaw() or from within
62369** the unaligned buffer passed via the second and third arguments (presumably
62370** stack space). If the former, then *ppFree is set to a pointer that should
62371** be eventually freed by the caller using sqlite3DbFree(). Or, if the
62372** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
62373** before returning.
62374**
62375** If an OOM error occurs, NULL is returned.
62376*/
62377SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
62378  KeyInfo *pKeyInfo,              /* Description of the record */
62379  char *pSpace,                   /* Unaligned space available */
62380  int szSpace,                    /* Size of pSpace[] in bytes */
62381  char **ppFree                   /* OUT: Caller should free this pointer */
62382){
62383  UnpackedRecord *p;              /* Unpacked record to return */
62384  int nOff;                       /* Increment pSpace by nOff to align it */
62385  int nByte;                      /* Number of bytes required for *p */
62386
62387  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
62388  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
62389  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
62390  */
62391  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
62392  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
62393  if( nByte>szSpace+nOff ){
62394    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
62395    *ppFree = (char *)p;
62396    if( !p ) return 0;
62397  }else{
62398    p = (UnpackedRecord*)&pSpace[nOff];
62399    *ppFree = 0;
62400  }
62401
62402  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
62403  p->pKeyInfo = pKeyInfo;
62404  p->nField = pKeyInfo->nField + 1;
62405  return p;
62406}
62407
62408/*
62409** Given the nKey-byte encoding of a record in pKey[], populate the
62410** UnpackedRecord structure indicated by the fourth argument with the
62411** contents of the decoded record.
62412*/
62413SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
62414  KeyInfo *pKeyInfo,     /* Information about the record format */
62415  int nKey,              /* Size of the binary record */
62416  const void *pKey,      /* The binary record */
62417  UnpackedRecord *p      /* Populate this structure before returning. */
62418){
62419  const unsigned char *aKey = (const unsigned char *)pKey;
62420  int d;
62421  u32 idx;                        /* Offset in aKey[] to read from */
62422  u16 u;                          /* Unsigned loop counter */
62423  u32 szHdr;
62424  Mem *pMem = p->aMem;
62425
62426  p->flags = 0;
62427  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62428  idx = getVarint32(aKey, szHdr);
62429  d = szHdr;
62430  u = 0;
62431  while( idx<szHdr && u<p->nField && d<=nKey ){
62432    u32 serial_type;
62433
62434    idx += getVarint32(&aKey[idx], serial_type);
62435    pMem->enc = pKeyInfo->enc;
62436    pMem->db = pKeyInfo->db;
62437    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
62438    pMem->zMalloc = 0;
62439    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
62440    pMem++;
62441    u++;
62442  }
62443  assert( u<=pKeyInfo->nField + 1 );
62444  p->nField = u;
62445}
62446
62447/*
62448** This function compares the two table rows or index records
62449** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
62450** or positive integer if key1 is less than, equal to or
62451** greater than key2.  The {nKey1, pKey1} key must be a blob
62452** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
62453** key must be a parsed key such as obtained from
62454** sqlite3VdbeParseRecord.
62455**
62456** Key1 and Key2 do not have to contain the same number of fields.
62457** The key with fewer fields is usually compares less than the
62458** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
62459** and the common prefixes are equal, then key1 is less than key2.
62460** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
62461** equal, then the keys are considered to be equal and
62462** the parts beyond the common prefix are ignored.
62463*/
62464SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
62465  int nKey1, const void *pKey1, /* Left key */
62466  UnpackedRecord *pPKey2        /* Right key */
62467){
62468  int d1;            /* Offset into aKey[] of next data element */
62469  u32 idx1;          /* Offset into aKey[] of next header element */
62470  u32 szHdr1;        /* Number of bytes in header */
62471  int i = 0;
62472  int nField;
62473  int rc = 0;
62474  const unsigned char *aKey1 = (const unsigned char *)pKey1;
62475  KeyInfo *pKeyInfo;
62476  Mem mem1;
62477
62478  pKeyInfo = pPKey2->pKeyInfo;
62479  mem1.enc = pKeyInfo->enc;
62480  mem1.db = pKeyInfo->db;
62481  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
62482  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
62483
62484  /* Compilers may complain that mem1.u.i is potentially uninitialized.
62485  ** We could initialize it, as shown here, to silence those complaints.
62486  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
62487  ** the unnecessary initialization has a measurable negative performance
62488  ** impact, since this routine is a very high runner.  And so, we choose
62489  ** to ignore the compiler warnings and leave this variable uninitialized.
62490  */
62491  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
62492
62493  idx1 = getVarint32(aKey1, szHdr1);
62494  d1 = szHdr1;
62495  nField = pKeyInfo->nField;
62496  while( idx1<szHdr1 && i<pPKey2->nField ){
62497    u32 serial_type1;
62498
62499    /* Read the serial types for the next element in each key. */
62500    idx1 += getVarint32( aKey1+idx1, serial_type1 );
62501    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
62502
62503    /* Extract the values to be compared.
62504    */
62505    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
62506
62507    /* Do the comparison
62508    */
62509    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
62510                           i<nField ? pKeyInfo->aColl[i] : 0);
62511    if( rc!=0 ){
62512      assert( mem1.zMalloc==0 );  /* See comment below */
62513
62514      /* Invert the result if we are using DESC sort order. */
62515      if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
62516        rc = -rc;
62517      }
62518
62519      /* If the PREFIX_SEARCH flag is set and all fields except the final
62520      ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
62521      ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
62522      ** This is used by the OP_IsUnique opcode.
62523      */
62524      if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
62525        assert( idx1==szHdr1 && rc );
62526        assert( mem1.flags & MEM_Int );
62527        pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
62528        pPKey2->rowid = mem1.u.i;
62529      }
62530
62531      return rc;
62532    }
62533    i++;
62534  }
62535
62536  /* No memory allocation is ever used on mem1.  Prove this using
62537  ** the following assert().  If the assert() fails, it indicates a
62538  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
62539  */
62540  assert( mem1.zMalloc==0 );
62541
62542  /* rc==0 here means that one of the keys ran out of fields and
62543  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
62544  ** flag is set, then break the tie by treating key2 as larger.
62545  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
62546  ** are considered to be equal.  Otherwise, the longer key is the
62547  ** larger.  As it happens, the pPKey2 will always be the longer
62548  ** if there is a difference.
62549  */
62550  assert( rc==0 );
62551  if( pPKey2->flags & UNPACKED_INCRKEY ){
62552    rc = -1;
62553  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
62554    /* Leave rc==0 */
62555  }else if( idx1<szHdr1 ){
62556    rc = 1;
62557  }
62558  return rc;
62559}
62560
62561
62562/*
62563** pCur points at an index entry created using the OP_MakeRecord opcode.
62564** Read the rowid (the last field in the record) and store it in *rowid.
62565** Return SQLITE_OK if everything works, or an error code otherwise.
62566**
62567** pCur might be pointing to text obtained from a corrupt database file.
62568** So the content cannot be trusted.  Do appropriate checks on the content.
62569*/
62570SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
62571  i64 nCellKey = 0;
62572  int rc;
62573  u32 szHdr;        /* Size of the header */
62574  u32 typeRowid;    /* Serial type of the rowid */
62575  u32 lenRowid;     /* Size of the rowid */
62576  Mem m, v;
62577
62578  UNUSED_PARAMETER(db);
62579
62580  /* Get the size of the index entry.  Only indices entries of less
62581  ** than 2GiB are support - anything large must be database corruption.
62582  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
62583  ** this code can safely assume that nCellKey is 32-bits
62584  */
62585  assert( sqlite3BtreeCursorIsValid(pCur) );
62586  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
62587  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
62588  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
62589
62590  /* Read in the complete content of the index entry */
62591  memset(&m, 0, sizeof(m));
62592  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
62593  if( rc ){
62594    return rc;
62595  }
62596
62597  /* The index entry must begin with a header size */
62598  (void)getVarint32((u8*)m.z, szHdr);
62599  testcase( szHdr==3 );
62600  testcase( szHdr==m.n );
62601  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
62602    goto idx_rowid_corruption;
62603  }
62604
62605  /* The last field of the index should be an integer - the ROWID.
62606  ** Verify that the last entry really is an integer. */
62607  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
62608  testcase( typeRowid==1 );
62609  testcase( typeRowid==2 );
62610  testcase( typeRowid==3 );
62611  testcase( typeRowid==4 );
62612  testcase( typeRowid==5 );
62613  testcase( typeRowid==6 );
62614  testcase( typeRowid==8 );
62615  testcase( typeRowid==9 );
62616  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
62617    goto idx_rowid_corruption;
62618  }
62619  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
62620  testcase( (u32)m.n==szHdr+lenRowid );
62621  if( unlikely((u32)m.n<szHdr+lenRowid) ){
62622    goto idx_rowid_corruption;
62623  }
62624
62625  /* Fetch the integer off the end of the index record */
62626  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
62627  *rowid = v.u.i;
62628  sqlite3VdbeMemRelease(&m);
62629  return SQLITE_OK;
62630
62631  /* Jump here if database corruption is detected after m has been
62632  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
62633idx_rowid_corruption:
62634  testcase( m.zMalloc!=0 );
62635  sqlite3VdbeMemRelease(&m);
62636  return SQLITE_CORRUPT_BKPT;
62637}
62638
62639/*
62640** Compare the key of the index entry that cursor pC is pointing to against
62641** the key string in pUnpacked.  Write into *pRes a number
62642** that is negative, zero, or positive if pC is less than, equal to,
62643** or greater than pUnpacked.  Return SQLITE_OK on success.
62644**
62645** pUnpacked is either created without a rowid or is truncated so that it
62646** omits the rowid at the end.  The rowid at the end of the index entry
62647** is ignored as well.  Hence, this routine only compares the prefixes
62648** of the keys prior to the final rowid, not the entire key.
62649*/
62650SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
62651  VdbeCursor *pC,             /* The cursor to compare against */
62652  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
62653  int *res                    /* Write the comparison result here */
62654){
62655  i64 nCellKey = 0;
62656  int rc;
62657  BtCursor *pCur = pC->pCursor;
62658  Mem m;
62659
62660  assert( sqlite3BtreeCursorIsValid(pCur) );
62661  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
62662  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
62663  /* nCellKey will always be between 0 and 0xffffffff because of the say
62664  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
62665  if( nCellKey<=0 || nCellKey>0x7fffffff ){
62666    *res = 0;
62667    return SQLITE_CORRUPT_BKPT;
62668  }
62669  memset(&m, 0, sizeof(m));
62670  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
62671  if( rc ){
62672    return rc;
62673  }
62674  assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
62675  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
62676  sqlite3VdbeMemRelease(&m);
62677  return SQLITE_OK;
62678}
62679
62680/*
62681** This routine sets the value to be returned by subsequent calls to
62682** sqlite3_changes() on the database handle 'db'.
62683*/
62684SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
62685  assert( sqlite3_mutex_held(db->mutex) );
62686  db->nChange = nChange;
62687  db->nTotalChange += nChange;
62688}
62689
62690/*
62691** Set a flag in the vdbe to update the change counter when it is finalised
62692** or reset.
62693*/
62694SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
62695  v->changeCntOn = 1;
62696}
62697
62698/*
62699** Mark every prepared statement associated with a database connection
62700** as expired.
62701**
62702** An expired statement means that recompilation of the statement is
62703** recommend.  Statements expire when things happen that make their
62704** programs obsolete.  Removing user-defined functions or collating
62705** sequences, or changing an authorization function are the types of
62706** things that make prepared statements obsolete.
62707*/
62708SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
62709  Vdbe *p;
62710  for(p = db->pVdbe; p; p=p->pNext){
62711    p->expired = 1;
62712  }
62713}
62714
62715/*
62716** Return the database associated with the Vdbe.
62717*/
62718SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
62719  return v->db;
62720}
62721
62722/*
62723** Return a pointer to an sqlite3_value structure containing the value bound
62724** parameter iVar of VM v. Except, if the value is an SQL NULL, return
62725** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
62726** constants) to the value before returning it.
62727**
62728** The returned value must be freed by the caller using sqlite3ValueFree().
62729*/
62730SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
62731  assert( iVar>0 );
62732  if( v ){
62733    Mem *pMem = &v->aVar[iVar-1];
62734    if( 0==(pMem->flags & MEM_Null) ){
62735      sqlite3_value *pRet = sqlite3ValueNew(v->db);
62736      if( pRet ){
62737        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
62738        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
62739        sqlite3VdbeMemStoreType((Mem *)pRet);
62740      }
62741      return pRet;
62742    }
62743  }
62744  return 0;
62745}
62746
62747/*
62748** Configure SQL variable iVar so that binding a new value to it signals
62749** to sqlite3_reoptimize() that re-preparing the statement may result
62750** in a better query plan.
62751*/
62752SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
62753  assert( iVar>0 );
62754  if( iVar>32 ){
62755    v->expmask = 0xffffffff;
62756  }else{
62757    v->expmask |= ((u32)1 << (iVar-1));
62758  }
62759}
62760
62761/************** End of vdbeaux.c *********************************************/
62762/************** Begin file vdbeapi.c *****************************************/
62763/*
62764** 2004 May 26
62765**
62766** The author disclaims copyright to this source code.  In place of
62767** a legal notice, here is a blessing:
62768**
62769**    May you do good and not evil.
62770**    May you find forgiveness for yourself and forgive others.
62771**    May you share freely, never taking more than you give.
62772**
62773*************************************************************************
62774**
62775** This file contains code use to implement APIs that are part of the
62776** VDBE.
62777*/
62778
62779#ifndef SQLITE_OMIT_DEPRECATED
62780/*
62781** Return TRUE (non-zero) of the statement supplied as an argument needs
62782** to be recompiled.  A statement needs to be recompiled whenever the
62783** execution environment changes in a way that would alter the program
62784** that sqlite3_prepare() generates.  For example, if new functions or
62785** collating sequences are registered or if an authorizer function is
62786** added or changed.
62787*/
62788SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
62789  Vdbe *p = (Vdbe*)pStmt;
62790  return p==0 || p->expired;
62791}
62792#endif
62793
62794/*
62795** Check on a Vdbe to make sure it has not been finalized.  Log
62796** an error and return true if it has been finalized (or is otherwise
62797** invalid).  Return false if it is ok.
62798*/
62799static int vdbeSafety(Vdbe *p){
62800  if( p->db==0 ){
62801    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
62802    return 1;
62803  }else{
62804    return 0;
62805  }
62806}
62807static int vdbeSafetyNotNull(Vdbe *p){
62808  if( p==0 ){
62809    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
62810    return 1;
62811  }else{
62812    return vdbeSafety(p);
62813  }
62814}
62815
62816/*
62817** The following routine destroys a virtual machine that is created by
62818** the sqlite3_compile() routine. The integer returned is an SQLITE_
62819** success/failure code that describes the result of executing the virtual
62820** machine.
62821**
62822** This routine sets the error code and string returned by
62823** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
62824*/
62825SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
62826  int rc;
62827  if( pStmt==0 ){
62828    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
62829    ** pointer is a harmless no-op. */
62830    rc = SQLITE_OK;
62831  }else{
62832    Vdbe *v = (Vdbe*)pStmt;
62833    sqlite3 *db = v->db;
62834#if SQLITE_THREADSAFE
62835    sqlite3_mutex *mutex;
62836#endif
62837    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
62838#if SQLITE_THREADSAFE
62839    mutex = v->db->mutex;
62840#endif
62841    sqlite3_mutex_enter(mutex);
62842    rc = sqlite3VdbeFinalize(v);
62843    rc = sqlite3ApiExit(db, rc);
62844    sqlite3_mutex_leave(mutex);
62845  }
62846  return rc;
62847}
62848
62849/*
62850** Terminate the current execution of an SQL statement and reset it
62851** back to its starting state so that it can be reused. A success code from
62852** the prior execution is returned.
62853**
62854** This routine sets the error code and string returned by
62855** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
62856*/
62857SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
62858  int rc;
62859  if( pStmt==0 ){
62860    rc = SQLITE_OK;
62861  }else{
62862    Vdbe *v = (Vdbe*)pStmt;
62863    sqlite3_mutex_enter(v->db->mutex);
62864    rc = sqlite3VdbeReset(v);
62865    sqlite3VdbeRewind(v);
62866    assert( (rc & (v->db->errMask))==rc );
62867    rc = sqlite3ApiExit(v->db, rc);
62868    sqlite3_mutex_leave(v->db->mutex);
62869  }
62870  return rc;
62871}
62872
62873/*
62874** Set all the parameters in the compiled SQL statement to NULL.
62875*/
62876SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
62877  int i;
62878  int rc = SQLITE_OK;
62879  Vdbe *p = (Vdbe*)pStmt;
62880#if SQLITE_THREADSAFE
62881  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
62882#endif
62883  sqlite3_mutex_enter(mutex);
62884  for(i=0; i<p->nVar; i++){
62885    sqlite3VdbeMemRelease(&p->aVar[i]);
62886    p->aVar[i].flags = MEM_Null;
62887  }
62888  if( p->isPrepareV2 && p->expmask ){
62889    p->expired = 1;
62890  }
62891  sqlite3_mutex_leave(mutex);
62892  return rc;
62893}
62894
62895
62896/**************************** sqlite3_value_  *******************************
62897** The following routines extract information from a Mem or sqlite3_value
62898** structure.
62899*/
62900SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
62901  Mem *p = (Mem*)pVal;
62902  if( p->flags & (MEM_Blob|MEM_Str) ){
62903    sqlite3VdbeMemExpandBlob(p);
62904    p->flags &= ~MEM_Str;
62905    p->flags |= MEM_Blob;
62906    return p->n ? p->z : 0;
62907  }else{
62908    return sqlite3_value_text(pVal);
62909  }
62910}
62911SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
62912  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
62913}
62914SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
62915  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
62916}
62917SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
62918  return sqlite3VdbeRealValue((Mem*)pVal);
62919}
62920SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
62921  return (int)sqlite3VdbeIntValue((Mem*)pVal);
62922}
62923SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
62924  return sqlite3VdbeIntValue((Mem*)pVal);
62925}
62926SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
62927  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
62928}
62929#ifndef SQLITE_OMIT_UTF16
62930SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
62931  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
62932}
62933SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
62934  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
62935}
62936SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
62937  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
62938}
62939#endif /* SQLITE_OMIT_UTF16 */
62940SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
62941  return pVal->type;
62942}
62943
62944/**************************** sqlite3_result_  *******************************
62945** The following routines are used by user-defined functions to specify
62946** the function result.
62947**
62948** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
62949** result as a string or blob but if the string or blob is too large, it
62950** then sets the error code to SQLITE_TOOBIG
62951*/
62952static void setResultStrOrError(
62953  sqlite3_context *pCtx,  /* Function context */
62954  const char *z,          /* String pointer */
62955  int n,                  /* Bytes in string, or negative */
62956  u8 enc,                 /* Encoding of z.  0 for BLOBs */
62957  void (*xDel)(void*)     /* Destructor function */
62958){
62959  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
62960    sqlite3_result_error_toobig(pCtx);
62961  }
62962}
62963SQLITE_API void sqlite3_result_blob(
62964  sqlite3_context *pCtx,
62965  const void *z,
62966  int n,
62967  void (*xDel)(void *)
62968){
62969  assert( n>=0 );
62970  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62971  setResultStrOrError(pCtx, z, n, 0, xDel);
62972}
62973SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
62974  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62975  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
62976}
62977SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
62978  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62979  pCtx->isError = SQLITE_ERROR;
62980  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
62981}
62982#ifndef SQLITE_OMIT_UTF16
62983SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
62984  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62985  pCtx->isError = SQLITE_ERROR;
62986  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
62987}
62988#endif
62989SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
62990  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62991  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
62992}
62993SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
62994  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62995  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
62996}
62997SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
62998  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62999  sqlite3VdbeMemSetNull(&pCtx->s);
63000}
63001SQLITE_API void sqlite3_result_text(
63002  sqlite3_context *pCtx,
63003  const char *z,
63004  int n,
63005  void (*xDel)(void *)
63006){
63007  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63008  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
63009}
63010#ifndef SQLITE_OMIT_UTF16
63011SQLITE_API void sqlite3_result_text16(
63012  sqlite3_context *pCtx,
63013  const void *z,
63014  int n,
63015  void (*xDel)(void *)
63016){
63017  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63018  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
63019}
63020SQLITE_API void sqlite3_result_text16be(
63021  sqlite3_context *pCtx,
63022  const void *z,
63023  int n,
63024  void (*xDel)(void *)
63025){
63026  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63027  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
63028}
63029SQLITE_API void sqlite3_result_text16le(
63030  sqlite3_context *pCtx,
63031  const void *z,
63032  int n,
63033  void (*xDel)(void *)
63034){
63035  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63036  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
63037}
63038#endif /* SQLITE_OMIT_UTF16 */
63039SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
63040  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63041  sqlite3VdbeMemCopy(&pCtx->s, pValue);
63042}
63043SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
63044  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63045  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
63046}
63047SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
63048  pCtx->isError = errCode;
63049  if( pCtx->s.flags & MEM_Null ){
63050    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
63051                         SQLITE_UTF8, SQLITE_STATIC);
63052  }
63053}
63054
63055/* Force an SQLITE_TOOBIG error. */
63056SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
63057  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63058  pCtx->isError = SQLITE_TOOBIG;
63059  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
63060                       SQLITE_UTF8, SQLITE_STATIC);
63061}
63062
63063/* An SQLITE_NOMEM error. */
63064SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
63065  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63066  sqlite3VdbeMemSetNull(&pCtx->s);
63067  pCtx->isError = SQLITE_NOMEM;
63068  pCtx->s.db->mallocFailed = 1;
63069}
63070
63071/*
63072** This function is called after a transaction has been committed. It
63073** invokes callbacks registered with sqlite3_wal_hook() as required.
63074*/
63075static int doWalCallbacks(sqlite3 *db){
63076  int rc = SQLITE_OK;
63077#ifndef SQLITE_OMIT_WAL
63078  int i;
63079  for(i=0; i<db->nDb; i++){
63080    Btree *pBt = db->aDb[i].pBt;
63081    if( pBt ){
63082      int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
63083      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
63084        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
63085      }
63086    }
63087  }
63088#endif
63089  return rc;
63090}
63091
63092/*
63093** Execute the statement pStmt, either until a row of data is ready, the
63094** statement is completely executed or an error occurs.
63095**
63096** This routine implements the bulk of the logic behind the sqlite_step()
63097** API.  The only thing omitted is the automatic recompile if a
63098** schema change has occurred.  That detail is handled by the
63099** outer sqlite3_step() wrapper procedure.
63100*/
63101static int sqlite3Step(Vdbe *p){
63102  sqlite3 *db;
63103  int rc;
63104
63105  assert(p);
63106  if( p->magic!=VDBE_MAGIC_RUN ){
63107    /* We used to require that sqlite3_reset() be called before retrying
63108    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
63109    ** with version 3.7.0, we changed this so that sqlite3_reset() would
63110    ** be called automatically instead of throwing the SQLITE_MISUSE error.
63111    ** This "automatic-reset" change is not technically an incompatibility,
63112    ** since any application that receives an SQLITE_MISUSE is broken by
63113    ** definition.
63114    **
63115    ** Nevertheless, some published applications that were originally written
63116    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
63117    ** returns, and those were broken by the automatic-reset change.  As a
63118    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
63119    ** legacy behavior of returning SQLITE_MISUSE for cases where the
63120    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
63121    ** or SQLITE_BUSY error.
63122    */
63123#ifdef SQLITE_OMIT_AUTORESET
63124    if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
63125      sqlite3_reset((sqlite3_stmt*)p);
63126    }else{
63127      return SQLITE_MISUSE_BKPT;
63128    }
63129#else
63130    sqlite3_reset((sqlite3_stmt*)p);
63131#endif
63132  }
63133
63134  /* Check that malloc() has not failed. If it has, return early. */
63135  db = p->db;
63136  if( db->mallocFailed ){
63137    p->rc = SQLITE_NOMEM;
63138    return SQLITE_NOMEM;
63139  }
63140
63141  if( p->pc<=0 && p->expired ){
63142    p->rc = SQLITE_SCHEMA;
63143    rc = SQLITE_ERROR;
63144    goto end_of_step;
63145  }
63146  if( p->pc<0 ){
63147    /* If there are no other statements currently running, then
63148    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
63149    ** from interrupting a statement that has not yet started.
63150    */
63151    if( db->activeVdbeCnt==0 ){
63152      db->u1.isInterrupted = 0;
63153    }
63154
63155    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
63156
63157#ifndef SQLITE_OMIT_TRACE
63158    if( db->xProfile && !db->init.busy ){
63159      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
63160    }
63161#endif
63162
63163    db->activeVdbeCnt++;
63164    if( p->readOnly==0 ) db->writeVdbeCnt++;
63165    p->pc = 0;
63166  }
63167#ifndef SQLITE_OMIT_EXPLAIN
63168  if( p->explain ){
63169    rc = sqlite3VdbeList(p);
63170  }else
63171#endif /* SQLITE_OMIT_EXPLAIN */
63172  {
63173    db->vdbeExecCnt++;
63174    rc = sqlite3VdbeExec(p);
63175    db->vdbeExecCnt--;
63176  }
63177
63178#ifndef SQLITE_OMIT_TRACE
63179  /* Invoke the profile callback if there is one
63180  */
63181  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
63182    sqlite3_int64 iNow;
63183    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
63184    db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
63185  }
63186#endif
63187
63188  if( rc==SQLITE_DONE ){
63189    assert( p->rc==SQLITE_OK );
63190    p->rc = doWalCallbacks(db);
63191    if( p->rc!=SQLITE_OK ){
63192      rc = SQLITE_ERROR;
63193    }
63194  }
63195
63196  db->errCode = rc;
63197  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
63198    p->rc = SQLITE_NOMEM;
63199  }
63200end_of_step:
63201  /* At this point local variable rc holds the value that should be
63202  ** returned if this statement was compiled using the legacy
63203  ** sqlite3_prepare() interface. According to the docs, this can only
63204  ** be one of the values in the first assert() below. Variable p->rc
63205  ** contains the value that would be returned if sqlite3_finalize()
63206  ** were called on statement p.
63207  */
63208  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
63209       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
63210  );
63211  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
63212  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
63213    /* If this statement was prepared using sqlite3_prepare_v2(), and an
63214    ** error has occured, then return the error code in p->rc to the
63215    ** caller. Set the error code in the database handle to the same value.
63216    */
63217    rc = sqlite3VdbeTransferError(p);
63218  }
63219  return (rc&db->errMask);
63220}
63221
63222/*
63223** The maximum number of times that a statement will try to reparse
63224** itself before giving up and returning SQLITE_SCHEMA.
63225*/
63226#ifndef SQLITE_MAX_SCHEMA_RETRY
63227# define SQLITE_MAX_SCHEMA_RETRY 5
63228#endif
63229
63230/*
63231** This is the top-level implementation of sqlite3_step().  Call
63232** sqlite3Step() to do most of the work.  If a schema error occurs,
63233** call sqlite3Reprepare() and try again.
63234*/
63235SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
63236  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
63237  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
63238  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
63239  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
63240  sqlite3 *db;             /* The database connection */
63241
63242  if( vdbeSafetyNotNull(v) ){
63243    return SQLITE_MISUSE_BKPT;
63244  }
63245  db = v->db;
63246  sqlite3_mutex_enter(db->mutex);
63247  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
63248         && cnt++ < SQLITE_MAX_SCHEMA_RETRY
63249         && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
63250    sqlite3_reset(pStmt);
63251    assert( v->expired==0 );
63252  }
63253  if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
63254    /* This case occurs after failing to recompile an sql statement.
63255    ** The error message from the SQL compiler has already been loaded
63256    ** into the database handle. This block copies the error message
63257    ** from the database handle into the statement and sets the statement
63258    ** program counter to 0 to ensure that when the statement is
63259    ** finalized or reset the parser error message is available via
63260    ** sqlite3_errmsg() and sqlite3_errcode().
63261    */
63262    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
63263    sqlite3DbFree(db, v->zErrMsg);
63264    if( !db->mallocFailed ){
63265      v->zErrMsg = sqlite3DbStrDup(db, zErr);
63266      v->rc = rc2;
63267    } else {
63268      v->zErrMsg = 0;
63269      v->rc = rc = SQLITE_NOMEM;
63270    }
63271  }
63272  rc = sqlite3ApiExit(db, rc);
63273  sqlite3_mutex_leave(db->mutex);
63274  return rc;
63275}
63276
63277/*
63278** Extract the user data from a sqlite3_context structure and return a
63279** pointer to it.
63280*/
63281SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
63282  assert( p && p->pFunc );
63283  return p->pFunc->pUserData;
63284}
63285
63286/*
63287** Extract the user data from a sqlite3_context structure and return a
63288** pointer to it.
63289**
63290** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
63291** returns a copy of the pointer to the database connection (the 1st
63292** parameter) of the sqlite3_create_function() and
63293** sqlite3_create_function16() routines that originally registered the
63294** application defined function.
63295*/
63296SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
63297  assert( p && p->pFunc );
63298  return p->s.db;
63299}
63300
63301/*
63302** The following is the implementation of an SQL function that always
63303** fails with an error message stating that the function is used in the
63304** wrong context.  The sqlite3_overload_function() API might construct
63305** SQL function that use this routine so that the functions will exist
63306** for name resolution but are actually overloaded by the xFindFunction
63307** method of virtual tables.
63308*/
63309SQLITE_PRIVATE void sqlite3InvalidFunction(
63310  sqlite3_context *context,  /* The function calling context */
63311  int NotUsed,               /* Number of arguments to the function */
63312  sqlite3_value **NotUsed2   /* Value of each argument */
63313){
63314  const char *zName = context->pFunc->zName;
63315  char *zErr;
63316  UNUSED_PARAMETER2(NotUsed, NotUsed2);
63317  zErr = sqlite3_mprintf(
63318      "unable to use function %s in the requested context", zName);
63319  sqlite3_result_error(context, zErr, -1);
63320  sqlite3_free(zErr);
63321}
63322
63323/*
63324** Allocate or return the aggregate context for a user function.  A new
63325** context is allocated on the first call.  Subsequent calls return the
63326** same context that was returned on prior calls.
63327*/
63328SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
63329  Mem *pMem;
63330  assert( p && p->pFunc && p->pFunc->xStep );
63331  assert( sqlite3_mutex_held(p->s.db->mutex) );
63332  pMem = p->pMem;
63333  testcase( nByte<0 );
63334  if( (pMem->flags & MEM_Agg)==0 ){
63335    if( nByte<=0 ){
63336      sqlite3VdbeMemReleaseExternal(pMem);
63337      pMem->flags = MEM_Null;
63338      pMem->z = 0;
63339    }else{
63340      sqlite3VdbeMemGrow(pMem, nByte, 0);
63341      pMem->flags = MEM_Agg;
63342      pMem->u.pDef = p->pFunc;
63343      if( pMem->z ){
63344        memset(pMem->z, 0, nByte);
63345      }
63346    }
63347  }
63348  return (void*)pMem->z;
63349}
63350
63351/*
63352** Return the auxilary data pointer, if any, for the iArg'th argument to
63353** the user-function defined by pCtx.
63354*/
63355SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
63356  VdbeFunc *pVdbeFunc;
63357
63358  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63359  pVdbeFunc = pCtx->pVdbeFunc;
63360  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
63361    return 0;
63362  }
63363  return pVdbeFunc->apAux[iArg].pAux;
63364}
63365
63366/*
63367** Set the auxilary data pointer and delete function, for the iArg'th
63368** argument to the user-function defined by pCtx. Any previous value is
63369** deleted by calling the delete function specified when it was set.
63370*/
63371SQLITE_API void sqlite3_set_auxdata(
63372  sqlite3_context *pCtx,
63373  int iArg,
63374  void *pAux,
63375  void (*xDelete)(void*)
63376){
63377  struct AuxData *pAuxData;
63378  VdbeFunc *pVdbeFunc;
63379  if( iArg<0 ) goto failed;
63380
63381  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63382  pVdbeFunc = pCtx->pVdbeFunc;
63383  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
63384    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
63385    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
63386    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
63387    if( !pVdbeFunc ){
63388      goto failed;
63389    }
63390    pCtx->pVdbeFunc = pVdbeFunc;
63391    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
63392    pVdbeFunc->nAux = iArg+1;
63393    pVdbeFunc->pFunc = pCtx->pFunc;
63394  }
63395
63396  pAuxData = &pVdbeFunc->apAux[iArg];
63397  if( pAuxData->pAux && pAuxData->xDelete ){
63398    pAuxData->xDelete(pAuxData->pAux);
63399  }
63400  pAuxData->pAux = pAux;
63401  pAuxData->xDelete = xDelete;
63402  return;
63403
63404failed:
63405  if( xDelete ){
63406    xDelete(pAux);
63407  }
63408}
63409
63410#ifndef SQLITE_OMIT_DEPRECATED
63411/*
63412** Return the number of times the Step function of a aggregate has been
63413** called.
63414**
63415** This function is deprecated.  Do not use it for new code.  It is
63416** provide only to avoid breaking legacy code.  New aggregate function
63417** implementations should keep their own counts within their aggregate
63418** context.
63419*/
63420SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
63421  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
63422  return p->pMem->n;
63423}
63424#endif
63425
63426/*
63427** Return the number of columns in the result set for the statement pStmt.
63428*/
63429SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
63430  Vdbe *pVm = (Vdbe *)pStmt;
63431  return pVm ? pVm->nResColumn : 0;
63432}
63433
63434/*
63435** Return the number of values available from the current row of the
63436** currently executing statement pStmt.
63437*/
63438SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
63439  Vdbe *pVm = (Vdbe *)pStmt;
63440  if( pVm==0 || pVm->pResultSet==0 ) return 0;
63441  return pVm->nResColumn;
63442}
63443
63444
63445/*
63446** Check to see if column iCol of the given statement is valid.  If
63447** it is, return a pointer to the Mem for the value of that column.
63448** If iCol is not valid, return a pointer to a Mem which has a value
63449** of NULL.
63450*/
63451static Mem *columnMem(sqlite3_stmt *pStmt, int i){
63452  Vdbe *pVm;
63453  Mem *pOut;
63454
63455  pVm = (Vdbe *)pStmt;
63456  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
63457    sqlite3_mutex_enter(pVm->db->mutex);
63458    pOut = &pVm->pResultSet[i];
63459  }else{
63460    /* If the value passed as the second argument is out of range, return
63461    ** a pointer to the following static Mem object which contains the
63462    ** value SQL NULL. Even though the Mem structure contains an element
63463    ** of type i64, on certain architectures (x86) with certain compiler
63464    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
63465    ** instead of an 8-byte one. This all works fine, except that when
63466    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
63467    ** that a Mem structure is located on an 8-byte boundary. To prevent
63468    ** these assert()s from failing, when building with SQLITE_DEBUG defined
63469    ** using gcc, we force nullMem to be 8-byte aligned using the magical
63470    ** __attribute__((aligned(8))) macro.  */
63471    static const Mem nullMem
63472#if defined(SQLITE_DEBUG) && defined(__GNUC__)
63473      __attribute__((aligned(8)))
63474#endif
63475      = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
63476#ifdef SQLITE_DEBUG
63477         0, 0,  /* pScopyFrom, pFiller */
63478#endif
63479         0, 0 };
63480
63481    if( pVm && ALWAYS(pVm->db) ){
63482      sqlite3_mutex_enter(pVm->db->mutex);
63483      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
63484    }
63485    pOut = (Mem*)&nullMem;
63486  }
63487  return pOut;
63488}
63489
63490/*
63491** This function is called after invoking an sqlite3_value_XXX function on a
63492** column value (i.e. a value returned by evaluating an SQL expression in the
63493** select list of a SELECT statement) that may cause a malloc() failure. If
63494** malloc() has failed, the threads mallocFailed flag is cleared and the result
63495** code of statement pStmt set to SQLITE_NOMEM.
63496**
63497** Specifically, this is called from within:
63498**
63499**     sqlite3_column_int()
63500**     sqlite3_column_int64()
63501**     sqlite3_column_text()
63502**     sqlite3_column_text16()
63503**     sqlite3_column_real()
63504**     sqlite3_column_bytes()
63505**     sqlite3_column_bytes16()
63506**     sqiite3_column_blob()
63507*/
63508static void columnMallocFailure(sqlite3_stmt *pStmt)
63509{
63510  /* If malloc() failed during an encoding conversion within an
63511  ** sqlite3_column_XXX API, then set the return code of the statement to
63512  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
63513  ** and _finalize() will return NOMEM.
63514  */
63515  Vdbe *p = (Vdbe *)pStmt;
63516  if( p ){
63517    p->rc = sqlite3ApiExit(p->db, p->rc);
63518    sqlite3_mutex_leave(p->db->mutex);
63519  }
63520}
63521
63522/**************************** sqlite3_column_  *******************************
63523** The following routines are used to access elements of the current row
63524** in the result set.
63525*/
63526SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
63527  const void *val;
63528  val = sqlite3_value_blob( columnMem(pStmt,i) );
63529  /* Even though there is no encoding conversion, value_blob() might
63530  ** need to call malloc() to expand the result of a zeroblob()
63531  ** expression.
63532  */
63533  columnMallocFailure(pStmt);
63534  return val;
63535}
63536SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
63537  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
63538  columnMallocFailure(pStmt);
63539  return val;
63540}
63541SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
63542  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
63543  columnMallocFailure(pStmt);
63544  return val;
63545}
63546SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
63547  double val = sqlite3_value_double( columnMem(pStmt,i) );
63548  columnMallocFailure(pStmt);
63549  return val;
63550}
63551SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
63552  int val = sqlite3_value_int( columnMem(pStmt,i) );
63553  columnMallocFailure(pStmt);
63554  return val;
63555}
63556SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
63557  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
63558  columnMallocFailure(pStmt);
63559  return val;
63560}
63561SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
63562  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
63563  columnMallocFailure(pStmt);
63564  return val;
63565}
63566SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
63567  Mem *pOut = columnMem(pStmt, i);
63568  if( pOut->flags&MEM_Static ){
63569    pOut->flags &= ~MEM_Static;
63570    pOut->flags |= MEM_Ephem;
63571  }
63572  columnMallocFailure(pStmt);
63573  return (sqlite3_value *)pOut;
63574}
63575#ifndef SQLITE_OMIT_UTF16
63576SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
63577  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
63578  columnMallocFailure(pStmt);
63579  return val;
63580}
63581#endif /* SQLITE_OMIT_UTF16 */
63582SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
63583  int iType = sqlite3_value_type( columnMem(pStmt,i) );
63584  columnMallocFailure(pStmt);
63585  return iType;
63586}
63587
63588/* The following function is experimental and subject to change or
63589** removal */
63590/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
63591**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
63592**}
63593*/
63594
63595/*
63596** Convert the N-th element of pStmt->pColName[] into a string using
63597** xFunc() then return that string.  If N is out of range, return 0.
63598**
63599** There are up to 5 names for each column.  useType determines which
63600** name is returned.  Here are the names:
63601**
63602**    0      The column name as it should be displayed for output
63603**    1      The datatype name for the column
63604**    2      The name of the database that the column derives from
63605**    3      The name of the table that the column derives from
63606**    4      The name of the table column that the result column derives from
63607**
63608** If the result is not a simple column reference (if it is an expression
63609** or a constant) then useTypes 2, 3, and 4 return NULL.
63610*/
63611static const void *columnName(
63612  sqlite3_stmt *pStmt,
63613  int N,
63614  const void *(*xFunc)(Mem*),
63615  int useType
63616){
63617  const void *ret = 0;
63618  Vdbe *p = (Vdbe *)pStmt;
63619  int n;
63620  sqlite3 *db = p->db;
63621
63622  assert( db!=0 );
63623  n = sqlite3_column_count(pStmt);
63624  if( N<n && N>=0 ){
63625    N += useType*n;
63626    sqlite3_mutex_enter(db->mutex);
63627    assert( db->mallocFailed==0 );
63628    ret = xFunc(&p->aColName[N]);
63629     /* A malloc may have failed inside of the xFunc() call. If this
63630    ** is the case, clear the mallocFailed flag and return NULL.
63631    */
63632    if( db->mallocFailed ){
63633      db->mallocFailed = 0;
63634      ret = 0;
63635    }
63636    sqlite3_mutex_leave(db->mutex);
63637  }
63638  return ret;
63639}
63640
63641/*
63642** Return the name of the Nth column of the result set returned by SQL
63643** statement pStmt.
63644*/
63645SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
63646  return columnName(
63647      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
63648}
63649#ifndef SQLITE_OMIT_UTF16
63650SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
63651  return columnName(
63652      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
63653}
63654#endif
63655
63656/*
63657** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
63658** not define OMIT_DECLTYPE.
63659*/
63660#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
63661# error "Must not define both SQLITE_OMIT_DECLTYPE \
63662         and SQLITE_ENABLE_COLUMN_METADATA"
63663#endif
63664
63665#ifndef SQLITE_OMIT_DECLTYPE
63666/*
63667** Return the column declaration type (if applicable) of the 'i'th column
63668** of the result set of SQL statement pStmt.
63669*/
63670SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
63671  return columnName(
63672      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
63673}
63674#ifndef SQLITE_OMIT_UTF16
63675SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
63676  return columnName(
63677      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
63678}
63679#endif /* SQLITE_OMIT_UTF16 */
63680#endif /* SQLITE_OMIT_DECLTYPE */
63681
63682#ifdef SQLITE_ENABLE_COLUMN_METADATA
63683/*
63684** Return the name of the database from which a result column derives.
63685** NULL is returned if the result column is an expression or constant or
63686** anything else which is not an unabiguous reference to a database column.
63687*/
63688SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
63689  return columnName(
63690      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
63691}
63692#ifndef SQLITE_OMIT_UTF16
63693SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
63694  return columnName(
63695      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
63696}
63697#endif /* SQLITE_OMIT_UTF16 */
63698
63699/*
63700** Return the name of the table from which a result column derives.
63701** NULL is returned if the result column is an expression or constant or
63702** anything else which is not an unabiguous reference to a database column.
63703*/
63704SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
63705  return columnName(
63706      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
63707}
63708#ifndef SQLITE_OMIT_UTF16
63709SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
63710  return columnName(
63711      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
63712}
63713#endif /* SQLITE_OMIT_UTF16 */
63714
63715/*
63716** Return the name of the table column from which a result column derives.
63717** NULL is returned if the result column is an expression or constant or
63718** anything else which is not an unabiguous reference to a database column.
63719*/
63720SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
63721  return columnName(
63722      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
63723}
63724#ifndef SQLITE_OMIT_UTF16
63725SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
63726  return columnName(
63727      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
63728}
63729#endif /* SQLITE_OMIT_UTF16 */
63730#endif /* SQLITE_ENABLE_COLUMN_METADATA */
63731
63732
63733/******************************* sqlite3_bind_  ***************************
63734**
63735** Routines used to attach values to wildcards in a compiled SQL statement.
63736*/
63737/*
63738** Unbind the value bound to variable i in virtual machine p. This is the
63739** the same as binding a NULL value to the column. If the "i" parameter is
63740** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
63741**
63742** A successful evaluation of this routine acquires the mutex on p.
63743** the mutex is released if any kind of error occurs.
63744**
63745** The error code stored in database p->db is overwritten with the return
63746** value in any case.
63747*/
63748static int vdbeUnbind(Vdbe *p, int i){
63749  Mem *pVar;
63750  if( vdbeSafetyNotNull(p) ){
63751    return SQLITE_MISUSE_BKPT;
63752  }
63753  sqlite3_mutex_enter(p->db->mutex);
63754  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
63755    sqlite3Error(p->db, SQLITE_MISUSE, 0);
63756    sqlite3_mutex_leave(p->db->mutex);
63757    sqlite3_log(SQLITE_MISUSE,
63758        "bind on a busy prepared statement: [%s]", p->zSql);
63759    return SQLITE_MISUSE_BKPT;
63760  }
63761  if( i<1 || i>p->nVar ){
63762    sqlite3Error(p->db, SQLITE_RANGE, 0);
63763    sqlite3_mutex_leave(p->db->mutex);
63764    return SQLITE_RANGE;
63765  }
63766  i--;
63767  pVar = &p->aVar[i];
63768  sqlite3VdbeMemRelease(pVar);
63769  pVar->flags = MEM_Null;
63770  sqlite3Error(p->db, SQLITE_OK, 0);
63771
63772  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
63773  ** binding a new value to this variable invalidates the current query plan.
63774  **
63775  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
63776  ** parameter in the WHERE clause might influence the choice of query plan
63777  ** for a statement, then the statement will be automatically recompiled,
63778  ** as if there had been a schema change, on the first sqlite3_step() call
63779  ** following any change to the bindings of that parameter.
63780  */
63781  if( p->isPrepareV2 &&
63782     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
63783  ){
63784    p->expired = 1;
63785  }
63786  return SQLITE_OK;
63787}
63788
63789/*
63790** Bind a text or BLOB value.
63791*/
63792static int bindText(
63793  sqlite3_stmt *pStmt,   /* The statement to bind against */
63794  int i,                 /* Index of the parameter to bind */
63795  const void *zData,     /* Pointer to the data to be bound */
63796  int nData,             /* Number of bytes of data to be bound */
63797  void (*xDel)(void*),   /* Destructor for the data */
63798  u8 encoding            /* Encoding for the data */
63799){
63800  Vdbe *p = (Vdbe *)pStmt;
63801  Mem *pVar;
63802  int rc;
63803
63804  rc = vdbeUnbind(p, i);
63805  if( rc==SQLITE_OK ){
63806    if( zData!=0 ){
63807      pVar = &p->aVar[i-1];
63808      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
63809      if( rc==SQLITE_OK && encoding!=0 ){
63810        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
63811      }
63812      sqlite3Error(p->db, rc, 0);
63813      rc = sqlite3ApiExit(p->db, rc);
63814    }
63815    sqlite3_mutex_leave(p->db->mutex);
63816  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
63817    xDel((void*)zData);
63818  }
63819  return rc;
63820}
63821
63822
63823/*
63824** Bind a blob value to an SQL statement variable.
63825*/
63826SQLITE_API int sqlite3_bind_blob(
63827  sqlite3_stmt *pStmt,
63828  int i,
63829  const void *zData,
63830  int nData,
63831  void (*xDel)(void*)
63832){
63833  return bindText(pStmt, i, zData, nData, xDel, 0);
63834}
63835SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
63836  int rc;
63837  Vdbe *p = (Vdbe *)pStmt;
63838  rc = vdbeUnbind(p, i);
63839  if( rc==SQLITE_OK ){
63840    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
63841    sqlite3_mutex_leave(p->db->mutex);
63842  }
63843  return rc;
63844}
63845SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
63846  return sqlite3_bind_int64(p, i, (i64)iValue);
63847}
63848SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
63849  int rc;
63850  Vdbe *p = (Vdbe *)pStmt;
63851  rc = vdbeUnbind(p, i);
63852  if( rc==SQLITE_OK ){
63853    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
63854    sqlite3_mutex_leave(p->db->mutex);
63855  }
63856  return rc;
63857}
63858SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
63859  int rc;
63860  Vdbe *p = (Vdbe*)pStmt;
63861  rc = vdbeUnbind(p, i);
63862  if( rc==SQLITE_OK ){
63863    sqlite3_mutex_leave(p->db->mutex);
63864  }
63865  return rc;
63866}
63867SQLITE_API int sqlite3_bind_text(
63868  sqlite3_stmt *pStmt,
63869  int i,
63870  const char *zData,
63871  int nData,
63872  void (*xDel)(void*)
63873){
63874  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
63875}
63876#ifndef SQLITE_OMIT_UTF16
63877SQLITE_API int sqlite3_bind_text16(
63878  sqlite3_stmt *pStmt,
63879  int i,
63880  const void *zData,
63881  int nData,
63882  void (*xDel)(void*)
63883){
63884  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
63885}
63886#endif /* SQLITE_OMIT_UTF16 */
63887SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
63888  int rc;
63889  switch( pValue->type ){
63890    case SQLITE_INTEGER: {
63891      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
63892      break;
63893    }
63894    case SQLITE_FLOAT: {
63895      rc = sqlite3_bind_double(pStmt, i, pValue->r);
63896      break;
63897    }
63898    case SQLITE_BLOB: {
63899      if( pValue->flags & MEM_Zero ){
63900        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
63901      }else{
63902        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
63903      }
63904      break;
63905    }
63906    case SQLITE_TEXT: {
63907      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
63908                              pValue->enc);
63909      break;
63910    }
63911    default: {
63912      rc = sqlite3_bind_null(pStmt, i);
63913      break;
63914    }
63915  }
63916  return rc;
63917}
63918SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
63919  int rc;
63920  Vdbe *p = (Vdbe *)pStmt;
63921  rc = vdbeUnbind(p, i);
63922  if( rc==SQLITE_OK ){
63923    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
63924    sqlite3_mutex_leave(p->db->mutex);
63925  }
63926  return rc;
63927}
63928
63929/*
63930** Return the number of wildcards that can be potentially bound to.
63931** This routine is added to support DBD::SQLite.
63932*/
63933SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
63934  Vdbe *p = (Vdbe*)pStmt;
63935  return p ? p->nVar : 0;
63936}
63937
63938/*
63939** Return the name of a wildcard parameter.  Return NULL if the index
63940** is out of range or if the wildcard is unnamed.
63941**
63942** The result is always UTF-8.
63943*/
63944SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
63945  Vdbe *p = (Vdbe*)pStmt;
63946  if( p==0 || i<1 || i>p->nzVar ){
63947    return 0;
63948  }
63949  return p->azVar[i-1];
63950}
63951
63952/*
63953** Given a wildcard parameter name, return the index of the variable
63954** with that name.  If there is no variable with the given name,
63955** return 0.
63956*/
63957SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
63958  int i;
63959  if( p==0 ){
63960    return 0;
63961  }
63962  if( zName ){
63963    for(i=0; i<p->nzVar; i++){
63964      const char *z = p->azVar[i];
63965      if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
63966        return i+1;
63967      }
63968    }
63969  }
63970  return 0;
63971}
63972SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
63973  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
63974}
63975
63976/*
63977** Transfer all bindings from the first statement over to the second.
63978*/
63979SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
63980  Vdbe *pFrom = (Vdbe*)pFromStmt;
63981  Vdbe *pTo = (Vdbe*)pToStmt;
63982  int i;
63983  assert( pTo->db==pFrom->db );
63984  assert( pTo->nVar==pFrom->nVar );
63985  sqlite3_mutex_enter(pTo->db->mutex);
63986  for(i=0; i<pFrom->nVar; i++){
63987    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
63988  }
63989  sqlite3_mutex_leave(pTo->db->mutex);
63990  return SQLITE_OK;
63991}
63992
63993#ifndef SQLITE_OMIT_DEPRECATED
63994/*
63995** Deprecated external interface.  Internal/core SQLite code
63996** should call sqlite3TransferBindings.
63997**
63998** Is is misuse to call this routine with statements from different
63999** database connections.  But as this is a deprecated interface, we
64000** will not bother to check for that condition.
64001**
64002** If the two statements contain a different number of bindings, then
64003** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
64004** SQLITE_OK is returned.
64005*/
64006SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
64007  Vdbe *pFrom = (Vdbe*)pFromStmt;
64008  Vdbe *pTo = (Vdbe*)pToStmt;
64009  if( pFrom->nVar!=pTo->nVar ){
64010    return SQLITE_ERROR;
64011  }
64012  if( pTo->isPrepareV2 && pTo->expmask ){
64013    pTo->expired = 1;
64014  }
64015  if( pFrom->isPrepareV2 && pFrom->expmask ){
64016    pFrom->expired = 1;
64017  }
64018  return sqlite3TransferBindings(pFromStmt, pToStmt);
64019}
64020#endif
64021
64022/*
64023** Return the sqlite3* database handle to which the prepared statement given
64024** in the argument belongs.  This is the same database handle that was
64025** the first argument to the sqlite3_prepare() that was used to create
64026** the statement in the first place.
64027*/
64028SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
64029  return pStmt ? ((Vdbe*)pStmt)->db : 0;
64030}
64031
64032/*
64033** Return true if the prepared statement is guaranteed to not modify the
64034** database.
64035*/
64036SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
64037  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
64038}
64039
64040/*
64041** Return true if the prepared statement is in need of being reset.
64042*/
64043SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
64044  Vdbe *v = (Vdbe*)pStmt;
64045  return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
64046}
64047
64048/*
64049** Return a pointer to the next prepared statement after pStmt associated
64050** with database connection pDb.  If pStmt is NULL, return the first
64051** prepared statement for the database connection.  Return NULL if there
64052** are no more.
64053*/
64054SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
64055  sqlite3_stmt *pNext;
64056  sqlite3_mutex_enter(pDb->mutex);
64057  if( pStmt==0 ){
64058    pNext = (sqlite3_stmt*)pDb->pVdbe;
64059  }else{
64060    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
64061  }
64062  sqlite3_mutex_leave(pDb->mutex);
64063  return pNext;
64064}
64065
64066/*
64067** Return the value of a status counter for a prepared statement
64068*/
64069SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
64070  Vdbe *pVdbe = (Vdbe*)pStmt;
64071  int v = pVdbe->aCounter[op-1];
64072  if( resetFlag ) pVdbe->aCounter[op-1] = 0;
64073  return v;
64074}
64075
64076/************** End of vdbeapi.c *********************************************/
64077/************** Begin file vdbetrace.c ***************************************/
64078/*
64079** 2009 November 25
64080**
64081** The author disclaims copyright to this source code.  In place of
64082** a legal notice, here is a blessing:
64083**
64084**    May you do good and not evil.
64085**    May you find forgiveness for yourself and forgive others.
64086**    May you share freely, never taking more than you give.
64087**
64088*************************************************************************
64089**
64090** This file contains code used to insert the values of host parameters
64091** (aka "wildcards") into the SQL text output by sqlite3_trace().
64092**
64093** The Vdbe parse-tree explainer is also found here.
64094*/
64095
64096#ifndef SQLITE_OMIT_TRACE
64097
64098/*
64099** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
64100** bytes in this text up to but excluding the first character in
64101** a host parameter.  If the text contains no host parameters, return
64102** the total number of bytes in the text.
64103*/
64104static int findNextHostParameter(const char *zSql, int *pnToken){
64105  int tokenType;
64106  int nTotal = 0;
64107  int n;
64108
64109  *pnToken = 0;
64110  while( zSql[0] ){
64111    n = sqlite3GetToken((u8*)zSql, &tokenType);
64112    assert( n>0 && tokenType!=TK_ILLEGAL );
64113    if( tokenType==TK_VARIABLE ){
64114      *pnToken = n;
64115      break;
64116    }
64117    nTotal += n;
64118    zSql += n;
64119  }
64120  return nTotal;
64121}
64122
64123/*
64124** This function returns a pointer to a nul-terminated string in memory
64125** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
64126** string contains a copy of zRawSql but with host parameters expanded to
64127** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
64128** then the returned string holds a copy of zRawSql with "-- " prepended
64129** to each line of text.
64130**
64131** The calling function is responsible for making sure the memory returned
64132** is eventually freed.
64133**
64134** ALGORITHM:  Scan the input string looking for host parameters in any of
64135** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
64136** string literals, quoted identifier names, and comments.  For text forms,
64137** the host parameter index is found by scanning the perpared
64138** statement for the corresponding OP_Variable opcode.  Once the host
64139** parameter index is known, locate the value in p->aVar[].  Then render
64140** the value as a literal in place of the host parameter name.
64141*/
64142SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
64143  Vdbe *p,                 /* The prepared statement being evaluated */
64144  const char *zRawSql      /* Raw text of the SQL statement */
64145){
64146  sqlite3 *db;             /* The database connection */
64147  int idx = 0;             /* Index of a host parameter */
64148  int nextIndex = 1;       /* Index of next ? host parameter */
64149  int n;                   /* Length of a token prefix */
64150  int nToken;              /* Length of the parameter token */
64151  int i;                   /* Loop counter */
64152  Mem *pVar;               /* Value of a host parameter */
64153  StrAccum out;            /* Accumulate the output here */
64154  char zBase[100];         /* Initial working space */
64155
64156  db = p->db;
64157  sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
64158                      db->aLimit[SQLITE_LIMIT_LENGTH]);
64159  out.db = db;
64160  if( db->vdbeExecCnt>1 ){
64161    while( *zRawSql ){
64162      const char *zStart = zRawSql;
64163      while( *(zRawSql++)!='\n' && *zRawSql );
64164      sqlite3StrAccumAppend(&out, "-- ", 3);
64165      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
64166    }
64167  }else{
64168    while( zRawSql[0] ){
64169      n = findNextHostParameter(zRawSql, &nToken);
64170      assert( n>0 );
64171      sqlite3StrAccumAppend(&out, zRawSql, n);
64172      zRawSql += n;
64173      assert( zRawSql[0] || nToken==0 );
64174      if( nToken==0 ) break;
64175      if( zRawSql[0]=='?' ){
64176        if( nToken>1 ){
64177          assert( sqlite3Isdigit(zRawSql[1]) );
64178          sqlite3GetInt32(&zRawSql[1], &idx);
64179        }else{
64180          idx = nextIndex;
64181        }
64182      }else{
64183        assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
64184        testcase( zRawSql[0]==':' );
64185        testcase( zRawSql[0]=='$' );
64186        testcase( zRawSql[0]=='@' );
64187        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
64188        assert( idx>0 );
64189      }
64190      zRawSql += nToken;
64191      nextIndex = idx + 1;
64192      assert( idx>0 && idx<=p->nVar );
64193      pVar = &p->aVar[idx-1];
64194      if( pVar->flags & MEM_Null ){
64195        sqlite3StrAccumAppend(&out, "NULL", 4);
64196      }else if( pVar->flags & MEM_Int ){
64197        sqlite3XPrintf(&out, "%lld", pVar->u.i);
64198      }else if( pVar->flags & MEM_Real ){
64199        sqlite3XPrintf(&out, "%!.15g", pVar->r);
64200      }else if( pVar->flags & MEM_Str ){
64201#ifndef SQLITE_OMIT_UTF16
64202        u8 enc = ENC(db);
64203        if( enc!=SQLITE_UTF8 ){
64204          Mem utf8;
64205          memset(&utf8, 0, sizeof(utf8));
64206          utf8.db = db;
64207          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
64208          sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
64209          sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
64210          sqlite3VdbeMemRelease(&utf8);
64211        }else
64212#endif
64213        {
64214          sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
64215        }
64216      }else if( pVar->flags & MEM_Zero ){
64217        sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
64218      }else{
64219        assert( pVar->flags & MEM_Blob );
64220        sqlite3StrAccumAppend(&out, "x'", 2);
64221        for(i=0; i<pVar->n; i++){
64222          sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
64223        }
64224        sqlite3StrAccumAppend(&out, "'", 1);
64225      }
64226    }
64227  }
64228  return sqlite3StrAccumFinish(&out);
64229}
64230
64231#endif /* #ifndef SQLITE_OMIT_TRACE */
64232
64233/*****************************************************************************
64234** The following code implements the data-structure explaining logic
64235** for the Vdbe.
64236*/
64237
64238#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
64239
64240/*
64241** Allocate a new Explain object
64242*/
64243SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
64244  if( pVdbe ){
64245    sqlite3BeginBenignMalloc();
64246    Explain *p = sqlite3_malloc( sizeof(Explain) );
64247    if( p ){
64248      memset(p, 0, sizeof(*p));
64249      p->pVdbe = pVdbe;
64250      sqlite3_free(pVdbe->pExplain);
64251      pVdbe->pExplain = p;
64252      sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
64253                          SQLITE_MAX_LENGTH);
64254      p->str.useMalloc = 2;
64255    }else{
64256      sqlite3EndBenignMalloc();
64257    }
64258  }
64259}
64260
64261/*
64262** Return true if the Explain ends with a new-line.
64263*/
64264static int endsWithNL(Explain *p){
64265  return p && p->str.zText && p->str.nChar
64266           && p->str.zText[p->str.nChar-1]=='\n';
64267}
64268
64269/*
64270** Append text to the indentation
64271*/
64272SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
64273  Explain *p;
64274  if( pVdbe && (p = pVdbe->pExplain)!=0 ){
64275    va_list ap;
64276    if( p->nIndent && endsWithNL(p) ){
64277      int n = p->nIndent;
64278      if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
64279      sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
64280    }
64281    va_start(ap, zFormat);
64282    sqlite3VXPrintf(&p->str, 1, zFormat, ap);
64283    va_end(ap);
64284  }
64285}
64286
64287/*
64288** Append a '\n' if there is not already one.
64289*/
64290SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
64291  Explain *p;
64292  if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
64293    sqlite3StrAccumAppend(&p->str, "\n", 1);
64294  }
64295}
64296
64297/*
64298** Push a new indentation level.  Subsequent lines will be indented
64299** so that they begin at the current cursor position.
64300*/
64301SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
64302  Explain *p;
64303  if( pVdbe && (p = pVdbe->pExplain)!=0 ){
64304    if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
64305      const char *z = p->str.zText;
64306      int i = p->str.nChar-1;
64307      int x;
64308      while( i>=0 && z[i]!='\n' ){ i--; }
64309      x = (p->str.nChar - 1) - i;
64310      if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
64311        x = p->aIndent[p->nIndent-1];
64312      }
64313      p->aIndent[p->nIndent] = x;
64314    }
64315    p->nIndent++;
64316  }
64317}
64318
64319/*
64320** Pop the indentation stack by one level.
64321*/
64322SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
64323  if( p && p->pExplain ) p->pExplain->nIndent--;
64324}
64325
64326/*
64327** Free the indentation structure
64328*/
64329SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
64330  if( pVdbe && pVdbe->pExplain ){
64331    sqlite3_free(pVdbe->zExplain);
64332    sqlite3ExplainNL(pVdbe);
64333    pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
64334    sqlite3_free(pVdbe->pExplain);
64335    pVdbe->pExplain = 0;
64336    sqlite3EndBenignMalloc();
64337  }
64338}
64339
64340/*
64341** Return the explanation of a virtual machine.
64342*/
64343SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
64344  return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
64345}
64346#endif /* defined(SQLITE_DEBUG) */
64347
64348/************** End of vdbetrace.c *******************************************/
64349/************** Begin file vdbe.c ********************************************/
64350/*
64351** 2001 September 15
64352**
64353** The author disclaims copyright to this source code.  In place of
64354** a legal notice, here is a blessing:
64355**
64356**    May you do good and not evil.
64357**    May you find forgiveness for yourself and forgive others.
64358**    May you share freely, never taking more than you give.
64359**
64360*************************************************************************
64361** The code in this file implements execution method of the
64362** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
64363** handles housekeeping details such as creating and deleting
64364** VDBE instances.  This file is solely interested in executing
64365** the VDBE program.
64366**
64367** In the external interface, an "sqlite3_stmt*" is an opaque pointer
64368** to a VDBE.
64369**
64370** The SQL parser generates a program which is then executed by
64371** the VDBE to do the work of the SQL statement.  VDBE programs are
64372** similar in form to assembly language.  The program consists of
64373** a linear sequence of operations.  Each operation has an opcode
64374** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
64375** is a null-terminated string.  Operand P5 is an unsigned character.
64376** Few opcodes use all 5 operands.
64377**
64378** Computation results are stored on a set of registers numbered beginning
64379** with 1 and going up to Vdbe.nMem.  Each register can store
64380** either an integer, a null-terminated string, a floating point
64381** number, or the SQL "NULL" value.  An implicit conversion from one
64382** type to the other occurs as necessary.
64383**
64384** Most of the code in this file is taken up by the sqlite3VdbeExec()
64385** function which does the work of interpreting a VDBE program.
64386** But other routines are also provided to help in building up
64387** a program instruction by instruction.
64388**
64389** Various scripts scan this source file in order to generate HTML
64390** documentation, headers files, or other derived files.  The formatting
64391** of the code in this file is, therefore, important.  See other comments
64392** in this file for details.  If in doubt, do not deviate from existing
64393** commenting and indentation practices when changing or adding code.
64394*/
64395
64396/*
64397** Invoke this macro on memory cells just prior to changing the
64398** value of the cell.  This macro verifies that shallow copies are
64399** not misused.
64400*/
64401#ifdef SQLITE_DEBUG
64402# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
64403#else
64404# define memAboutToChange(P,M)
64405#endif
64406
64407/*
64408** The following global variable is incremented every time a cursor
64409** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
64410** procedures use this information to make sure that indices are
64411** working correctly.  This variable has no function other than to
64412** help verify the correct operation of the library.
64413*/
64414#ifdef SQLITE_TEST
64415SQLITE_API int sqlite3_search_count = 0;
64416#endif
64417
64418/*
64419** When this global variable is positive, it gets decremented once before
64420** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
64421** field of the sqlite3 structure is set in order to simulate an interrupt.
64422**
64423** This facility is used for testing purposes only.  It does not function
64424** in an ordinary build.
64425*/
64426#ifdef SQLITE_TEST
64427SQLITE_API int sqlite3_interrupt_count = 0;
64428#endif
64429
64430/*
64431** The next global variable is incremented each type the OP_Sort opcode
64432** is executed.  The test procedures use this information to make sure that
64433** sorting is occurring or not occurring at appropriate times.   This variable
64434** has no function other than to help verify the correct operation of the
64435** library.
64436*/
64437#ifdef SQLITE_TEST
64438SQLITE_API int sqlite3_sort_count = 0;
64439#endif
64440
64441/*
64442** The next global variable records the size of the largest MEM_Blob
64443** or MEM_Str that has been used by a VDBE opcode.  The test procedures
64444** use this information to make sure that the zero-blob functionality
64445** is working correctly.   This variable has no function other than to
64446** help verify the correct operation of the library.
64447*/
64448#ifdef SQLITE_TEST
64449SQLITE_API int sqlite3_max_blobsize = 0;
64450static void updateMaxBlobsize(Mem *p){
64451  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
64452    sqlite3_max_blobsize = p->n;
64453  }
64454}
64455#endif
64456
64457/*
64458** The next global variable is incremented each type the OP_Found opcode
64459** is executed. This is used to test whether or not the foreign key
64460** operation implemented using OP_FkIsZero is working. This variable
64461** has no function other than to help verify the correct operation of the
64462** library.
64463*/
64464#ifdef SQLITE_TEST
64465SQLITE_API int sqlite3_found_count = 0;
64466#endif
64467
64468/*
64469** Test a register to see if it exceeds the current maximum blob size.
64470** If it does, record the new maximum blob size.
64471*/
64472#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
64473# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
64474#else
64475# define UPDATE_MAX_BLOBSIZE(P)
64476#endif
64477
64478/*
64479** Convert the given register into a string if it isn't one
64480** already. Return non-zero if a malloc() fails.
64481*/
64482#define Stringify(P, enc) \
64483   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
64484     { goto no_mem; }
64485
64486/*
64487** An ephemeral string value (signified by the MEM_Ephem flag) contains
64488** a pointer to a dynamically allocated string where some other entity
64489** is responsible for deallocating that string.  Because the register
64490** does not control the string, it might be deleted without the register
64491** knowing it.
64492**
64493** This routine converts an ephemeral string into a dynamically allocated
64494** string that the register itself controls.  In other words, it
64495** converts an MEM_Ephem string into an MEM_Dyn string.
64496*/
64497#define Deephemeralize(P) \
64498   if( ((P)->flags&MEM_Ephem)!=0 \
64499       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
64500
64501/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
64502#ifdef SQLITE_OMIT_MERGE_SORT
64503# define isSorter(x) 0
64504#else
64505# define isSorter(x) ((x)->pSorter!=0)
64506#endif
64507
64508/*
64509** Argument pMem points at a register that will be passed to a
64510** user-defined function or returned to the user as the result of a query.
64511** This routine sets the pMem->type variable used by the sqlite3_value_*()
64512** routines.
64513*/
64514SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
64515  int flags = pMem->flags;
64516  if( flags & MEM_Null ){
64517    pMem->type = SQLITE_NULL;
64518  }
64519  else if( flags & MEM_Int ){
64520    pMem->type = SQLITE_INTEGER;
64521  }
64522  else if( flags & MEM_Real ){
64523    pMem->type = SQLITE_FLOAT;
64524  }
64525  else if( flags & MEM_Str ){
64526    pMem->type = SQLITE_TEXT;
64527  }else{
64528    pMem->type = SQLITE_BLOB;
64529  }
64530}
64531
64532/*
64533** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
64534** if we run out of memory.
64535*/
64536static VdbeCursor *allocateCursor(
64537  Vdbe *p,              /* The virtual machine */
64538  int iCur,             /* Index of the new VdbeCursor */
64539  int nField,           /* Number of fields in the table or index */
64540  int iDb,              /* Database the cursor belongs to, or -1 */
64541  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
64542){
64543  /* Find the memory cell that will be used to store the blob of memory
64544  ** required for this VdbeCursor structure. It is convenient to use a
64545  ** vdbe memory cell to manage the memory allocation required for a
64546  ** VdbeCursor structure for the following reasons:
64547  **
64548  **   * Sometimes cursor numbers are used for a couple of different
64549  **     purposes in a vdbe program. The different uses might require
64550  **     different sized allocations. Memory cells provide growable
64551  **     allocations.
64552  **
64553  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
64554  **     be freed lazily via the sqlite3_release_memory() API. This
64555  **     minimizes the number of malloc calls made by the system.
64556  **
64557  ** Memory cells for cursors are allocated at the top of the address
64558  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
64559  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
64560  */
64561  Mem *pMem = &p->aMem[p->nMem-iCur];
64562
64563  int nByte;
64564  VdbeCursor *pCx = 0;
64565  nByte =
64566      ROUND8(sizeof(VdbeCursor)) +
64567      (isBtreeCursor?sqlite3BtreeCursorSize():0) +
64568      2*nField*sizeof(u32);
64569
64570  assert( iCur<p->nCursor );
64571  if( p->apCsr[iCur] ){
64572    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
64573    p->apCsr[iCur] = 0;
64574  }
64575  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
64576    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
64577    memset(pCx, 0, sizeof(VdbeCursor));
64578    pCx->iDb = iDb;
64579    pCx->nField = nField;
64580    if( nField ){
64581      pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
64582    }
64583    if( isBtreeCursor ){
64584      pCx->pCursor = (BtCursor*)
64585          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
64586      sqlite3BtreeCursorZero(pCx->pCursor);
64587    }
64588  }
64589  return pCx;
64590}
64591
64592/*
64593** Try to convert a value into a numeric representation if we can
64594** do so without loss of information.  In other words, if the string
64595** looks like a number, convert it into a number.  If it does not
64596** look like a number, leave it alone.
64597*/
64598static void applyNumericAffinity(Mem *pRec){
64599  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
64600    double rValue;
64601    i64 iValue;
64602    u8 enc = pRec->enc;
64603    if( (pRec->flags&MEM_Str)==0 ) return;
64604    if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
64605    if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
64606      pRec->u.i = iValue;
64607      pRec->flags |= MEM_Int;
64608    }else{
64609      pRec->r = rValue;
64610      pRec->flags |= MEM_Real;
64611    }
64612  }
64613}
64614
64615/*
64616** Processing is determine by the affinity parameter:
64617**
64618** SQLITE_AFF_INTEGER:
64619** SQLITE_AFF_REAL:
64620** SQLITE_AFF_NUMERIC:
64621**    Try to convert pRec to an integer representation or a
64622**    floating-point representation if an integer representation
64623**    is not possible.  Note that the integer representation is
64624**    always preferred, even if the affinity is REAL, because
64625**    an integer representation is more space efficient on disk.
64626**
64627** SQLITE_AFF_TEXT:
64628**    Convert pRec to a text representation.
64629**
64630** SQLITE_AFF_NONE:
64631**    No-op.  pRec is unchanged.
64632*/
64633static void applyAffinity(
64634  Mem *pRec,          /* The value to apply affinity to */
64635  char affinity,      /* The affinity to be applied */
64636  u8 enc              /* Use this text encoding */
64637){
64638  if( affinity==SQLITE_AFF_TEXT ){
64639    /* Only attempt the conversion to TEXT if there is an integer or real
64640    ** representation (blob and NULL do not get converted) but no string
64641    ** representation.
64642    */
64643    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
64644      sqlite3VdbeMemStringify(pRec, enc);
64645    }
64646    pRec->flags &= ~(MEM_Real|MEM_Int);
64647  }else if( affinity!=SQLITE_AFF_NONE ){
64648    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
64649             || affinity==SQLITE_AFF_NUMERIC );
64650    applyNumericAffinity(pRec);
64651    if( pRec->flags & MEM_Real ){
64652      sqlite3VdbeIntegerAffinity(pRec);
64653    }
64654  }
64655}
64656
64657/*
64658** Try to convert the type of a function argument or a result column
64659** into a numeric representation.  Use either INTEGER or REAL whichever
64660** is appropriate.  But only do the conversion if it is possible without
64661** loss of information and return the revised type of the argument.
64662*/
64663SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
64664  Mem *pMem = (Mem*)pVal;
64665  if( pMem->type==SQLITE_TEXT ){
64666    applyNumericAffinity(pMem);
64667    sqlite3VdbeMemStoreType(pMem);
64668  }
64669  return pMem->type;
64670}
64671
64672/*
64673** Exported version of applyAffinity(). This one works on sqlite3_value*,
64674** not the internal Mem* type.
64675*/
64676SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
64677  sqlite3_value *pVal,
64678  u8 affinity,
64679  u8 enc
64680){
64681  applyAffinity((Mem *)pVal, affinity, enc);
64682}
64683
64684#ifdef SQLITE_DEBUG
64685/*
64686** Write a nice string representation of the contents of cell pMem
64687** into buffer zBuf, length nBuf.
64688*/
64689SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
64690  char *zCsr = zBuf;
64691  int f = pMem->flags;
64692
64693  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
64694
64695  if( f&MEM_Blob ){
64696    int i;
64697    char c;
64698    if( f & MEM_Dyn ){
64699      c = 'z';
64700      assert( (f & (MEM_Static|MEM_Ephem))==0 );
64701    }else if( f & MEM_Static ){
64702      c = 't';
64703      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
64704    }else if( f & MEM_Ephem ){
64705      c = 'e';
64706      assert( (f & (MEM_Static|MEM_Dyn))==0 );
64707    }else{
64708      c = 's';
64709    }
64710
64711    sqlite3_snprintf(100, zCsr, "%c", c);
64712    zCsr += sqlite3Strlen30(zCsr);
64713    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
64714    zCsr += sqlite3Strlen30(zCsr);
64715    for(i=0; i<16 && i<pMem->n; i++){
64716      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
64717      zCsr += sqlite3Strlen30(zCsr);
64718    }
64719    for(i=0; i<16 && i<pMem->n; i++){
64720      char z = pMem->z[i];
64721      if( z<32 || z>126 ) *zCsr++ = '.';
64722      else *zCsr++ = z;
64723    }
64724
64725    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
64726    zCsr += sqlite3Strlen30(zCsr);
64727    if( f & MEM_Zero ){
64728      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
64729      zCsr += sqlite3Strlen30(zCsr);
64730    }
64731    *zCsr = '\0';
64732  }else if( f & MEM_Str ){
64733    int j, k;
64734    zBuf[0] = ' ';
64735    if( f & MEM_Dyn ){
64736      zBuf[1] = 'z';
64737      assert( (f & (MEM_Static|MEM_Ephem))==0 );
64738    }else if( f & MEM_Static ){
64739      zBuf[1] = 't';
64740      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
64741    }else if( f & MEM_Ephem ){
64742      zBuf[1] = 'e';
64743      assert( (f & (MEM_Static|MEM_Dyn))==0 );
64744    }else{
64745      zBuf[1] = 's';
64746    }
64747    k = 2;
64748    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
64749    k += sqlite3Strlen30(&zBuf[k]);
64750    zBuf[k++] = '[';
64751    for(j=0; j<15 && j<pMem->n; j++){
64752      u8 c = pMem->z[j];
64753      if( c>=0x20 && c<0x7f ){
64754        zBuf[k++] = c;
64755      }else{
64756        zBuf[k++] = '.';
64757      }
64758    }
64759    zBuf[k++] = ']';
64760    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
64761    k += sqlite3Strlen30(&zBuf[k]);
64762    zBuf[k++] = 0;
64763  }
64764}
64765#endif
64766
64767#ifdef SQLITE_DEBUG
64768/*
64769** Print the value of a register for tracing purposes:
64770*/
64771static void memTracePrint(FILE *out, Mem *p){
64772  if( p->flags & MEM_Null ){
64773    fprintf(out, " NULL");
64774  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
64775    fprintf(out, " si:%lld", p->u.i);
64776  }else if( p->flags & MEM_Int ){
64777    fprintf(out, " i:%lld", p->u.i);
64778#ifndef SQLITE_OMIT_FLOATING_POINT
64779  }else if( p->flags & MEM_Real ){
64780    fprintf(out, " r:%g", p->r);
64781#endif
64782  }else if( p->flags & MEM_RowSet ){
64783    fprintf(out, " (rowset)");
64784  }else{
64785    char zBuf[200];
64786    sqlite3VdbeMemPrettyPrint(p, zBuf);
64787    fprintf(out, " ");
64788    fprintf(out, "%s", zBuf);
64789  }
64790}
64791static void registerTrace(FILE *out, int iReg, Mem *p){
64792  fprintf(out, "REG[%d] = ", iReg);
64793  memTracePrint(out, p);
64794  fprintf(out, "\n");
64795}
64796#endif
64797
64798#ifdef SQLITE_DEBUG
64799#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
64800#else
64801#  define REGISTER_TRACE(R,M)
64802#endif
64803
64804
64805#ifdef VDBE_PROFILE
64806
64807/*
64808** hwtime.h contains inline assembler code for implementing
64809** high-performance timing routines.
64810*/
64811/************** Include hwtime.h in the middle of vdbe.c *********************/
64812/************** Begin file hwtime.h ******************************************/
64813/*
64814** 2008 May 27
64815**
64816** The author disclaims copyright to this source code.  In place of
64817** a legal notice, here is a blessing:
64818**
64819**    May you do good and not evil.
64820**    May you find forgiveness for yourself and forgive others.
64821**    May you share freely, never taking more than you give.
64822**
64823******************************************************************************
64824**
64825** This file contains inline asm code for retrieving "high-performance"
64826** counters for x86 class CPUs.
64827*/
64828#ifndef _HWTIME_H_
64829#define _HWTIME_H_
64830
64831/*
64832** The following routine only works on pentium-class (or newer) processors.
64833** It uses the RDTSC opcode to read the cycle count value out of the
64834** processor and returns that value.  This can be used for high-res
64835** profiling.
64836*/
64837#if (defined(__GNUC__) || defined(_MSC_VER)) && \
64838      (defined(i386) || defined(__i386__) || defined(_M_IX86))
64839
64840  #if defined(__GNUC__)
64841
64842  __inline__ sqlite_uint64 sqlite3Hwtime(void){
64843     unsigned int lo, hi;
64844     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
64845     return (sqlite_uint64)hi << 32 | lo;
64846  }
64847
64848  #elif defined(_MSC_VER)
64849
64850  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
64851     __asm {
64852        rdtsc
64853        ret       ; return value at EDX:EAX
64854     }
64855  }
64856
64857  #endif
64858
64859#elif (defined(__GNUC__) && defined(__x86_64__))
64860
64861  __inline__ sqlite_uint64 sqlite3Hwtime(void){
64862      unsigned long val;
64863      __asm__ __volatile__ ("rdtsc" : "=A" (val));
64864      return val;
64865  }
64866
64867#elif (defined(__GNUC__) && defined(__ppc__))
64868
64869  __inline__ sqlite_uint64 sqlite3Hwtime(void){
64870      unsigned long long retval;
64871      unsigned long junk;
64872      __asm__ __volatile__ ("\n\
64873          1:      mftbu   %1\n\
64874                  mftb    %L0\n\
64875                  mftbu   %0\n\
64876                  cmpw    %0,%1\n\
64877                  bne     1b"
64878                  : "=r" (retval), "=r" (junk));
64879      return retval;
64880  }
64881
64882#else
64883
64884  #error Need implementation of sqlite3Hwtime() for your platform.
64885
64886  /*
64887  ** To compile without implementing sqlite3Hwtime() for your platform,
64888  ** you can remove the above #error and use the following
64889  ** stub function.  You will lose timing support for many
64890  ** of the debugging and testing utilities, but it should at
64891  ** least compile and run.
64892  */
64893SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
64894
64895#endif
64896
64897#endif /* !defined(_HWTIME_H_) */
64898
64899/************** End of hwtime.h **********************************************/
64900/************** Continuing where we left off in vdbe.c ***********************/
64901
64902#endif
64903
64904/*
64905** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
64906** sqlite3_interrupt() routine has been called.  If it has been, then
64907** processing of the VDBE program is interrupted.
64908**
64909** This macro added to every instruction that does a jump in order to
64910** implement a loop.  This test used to be on every single instruction,
64911** but that meant we more testing than we needed.  By only testing the
64912** flag on jump instructions, we get a (small) speed improvement.
64913*/
64914#define CHECK_FOR_INTERRUPT \
64915   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
64916
64917
64918#ifndef NDEBUG
64919/*
64920** This function is only called from within an assert() expression. It
64921** checks that the sqlite3.nTransaction variable is correctly set to
64922** the number of non-transaction savepoints currently in the
64923** linked list starting at sqlite3.pSavepoint.
64924**
64925** Usage:
64926**
64927**     assert( checkSavepointCount(db) );
64928*/
64929static int checkSavepointCount(sqlite3 *db){
64930  int n = 0;
64931  Savepoint *p;
64932  for(p=db->pSavepoint; p; p=p->pNext) n++;
64933  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
64934  return 1;
64935}
64936#endif
64937
64938/*
64939** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
64940** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
64941** in memory obtained from sqlite3DbMalloc).
64942*/
64943static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
64944  sqlite3 *db = p->db;
64945  sqlite3DbFree(db, p->zErrMsg);
64946  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
64947  sqlite3_free(pVtab->zErrMsg);
64948  pVtab->zErrMsg = 0;
64949}
64950
64951
64952/*
64953** Execute as much of a VDBE program as we can then return.
64954**
64955** sqlite3VdbeMakeReady() must be called before this routine in order to
64956** close the program with a final OP_Halt and to set up the callbacks
64957** and the error message pointer.
64958**
64959** Whenever a row or result data is available, this routine will either
64960** invoke the result callback (if there is one) or return with
64961** SQLITE_ROW.
64962**
64963** If an attempt is made to open a locked database, then this routine
64964** will either invoke the busy callback (if there is one) or it will
64965** return SQLITE_BUSY.
64966**
64967** If an error occurs, an error message is written to memory obtained
64968** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
64969** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
64970**
64971** If the callback ever returns non-zero, then the program exits
64972** immediately.  There will be no error message but the p->rc field is
64973** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
64974**
64975** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
64976** routine to return SQLITE_ERROR.
64977**
64978** Other fatal errors return SQLITE_ERROR.
64979**
64980** After this routine has finished, sqlite3VdbeFinalize() should be
64981** used to clean up the mess that was left behind.
64982*/
64983SQLITE_PRIVATE int sqlite3VdbeExec(
64984  Vdbe *p                    /* The VDBE */
64985){
64986  int pc=0;                  /* The program counter */
64987  Op *aOp = p->aOp;          /* Copy of p->aOp */
64988  Op *pOp;                   /* Current operation */
64989  int rc = SQLITE_OK;        /* Value to return */
64990  sqlite3 *db = p->db;       /* The database */
64991  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
64992  u8 encoding = ENC(db);     /* The database encoding */
64993#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64994  int checkProgress;         /* True if progress callbacks are enabled */
64995  int nProgressOps = 0;      /* Opcodes executed since progress callback. */
64996#endif
64997  Mem *aMem = p->aMem;       /* Copy of p->aMem */
64998  Mem *pIn1 = 0;             /* 1st input operand */
64999  Mem *pIn2 = 0;             /* 2nd input operand */
65000  Mem *pIn3 = 0;             /* 3rd input operand */
65001  Mem *pOut = 0;             /* Output operand */
65002  int iCompare = 0;          /* Result of last OP_Compare operation */
65003  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
65004  i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
65005#ifdef VDBE_PROFILE
65006  u64 start;                 /* CPU clock count at start of opcode */
65007  int origPc;                /* Program counter at start of opcode */
65008#endif
65009  /********************************************************************
65010  ** Automatically generated code
65011  **
65012  ** The following union is automatically generated by the
65013  ** vdbe-compress.tcl script.  The purpose of this union is to
65014  ** reduce the amount of stack space required by this function.
65015  ** See comments in the vdbe-compress.tcl script for details.
65016  */
65017  union vdbeExecUnion {
65018    struct OP_Yield_stack_vars {
65019      int pcDest;
65020    } aa;
65021    struct OP_Null_stack_vars {
65022      int cnt;
65023    } ab;
65024    struct OP_Variable_stack_vars {
65025      Mem *pVar;       /* Value being transferred */
65026    } ac;
65027    struct OP_Move_stack_vars {
65028      char *zMalloc;   /* Holding variable for allocated memory */
65029      int n;           /* Number of registers left to copy */
65030      int p1;          /* Register to copy from */
65031      int p2;          /* Register to copy to */
65032    } ad;
65033    struct OP_ResultRow_stack_vars {
65034      Mem *pMem;
65035      int i;
65036    } ae;
65037    struct OP_Concat_stack_vars {
65038      i64 nByte;
65039    } af;
65040    struct OP_Remainder_stack_vars {
65041      int flags;      /* Combined MEM_* flags from both inputs */
65042      i64 iA;         /* Integer value of left operand */
65043      i64 iB;         /* Integer value of right operand */
65044      double rA;      /* Real value of left operand */
65045      double rB;      /* Real value of right operand */
65046    } ag;
65047    struct OP_Function_stack_vars {
65048      int i;
65049      Mem *pArg;
65050      sqlite3_context ctx;
65051      sqlite3_value **apVal;
65052      int n;
65053    } ah;
65054    struct OP_ShiftRight_stack_vars {
65055      i64 iA;
65056      u64 uA;
65057      i64 iB;
65058      u8 op;
65059    } ai;
65060    struct OP_Ge_stack_vars {
65061      int res;            /* Result of the comparison of pIn1 against pIn3 */
65062      char affinity;      /* Affinity to use for comparison */
65063      u16 flags1;         /* Copy of initial value of pIn1->flags */
65064      u16 flags3;         /* Copy of initial value of pIn3->flags */
65065    } aj;
65066    struct OP_Compare_stack_vars {
65067      int n;
65068      int i;
65069      int p1;
65070      int p2;
65071      const KeyInfo *pKeyInfo;
65072      int idx;
65073      CollSeq *pColl;    /* Collating sequence to use on this term */
65074      int bRev;          /* True for DESCENDING sort order */
65075    } ak;
65076    struct OP_Or_stack_vars {
65077      int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65078      int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65079    } al;
65080    struct OP_IfNot_stack_vars {
65081      int c;
65082    } am;
65083    struct OP_Column_stack_vars {
65084      u32 payloadSize;   /* Number of bytes in the record */
65085      i64 payloadSize64; /* Number of bytes in the record */
65086      int p1;            /* P1 value of the opcode */
65087      int p2;            /* column number to retrieve */
65088      VdbeCursor *pC;    /* The VDBE cursor */
65089      char *zRec;        /* Pointer to complete record-data */
65090      BtCursor *pCrsr;   /* The BTree cursor */
65091      u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
65092      u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
65093      int nField;        /* number of fields in the record */
65094      int len;           /* The length of the serialized data for the column */
65095      int i;             /* Loop counter */
65096      char *zData;       /* Part of the record being decoded */
65097      Mem *pDest;        /* Where to write the extracted value */
65098      Mem sMem;          /* For storing the record being decoded */
65099      u8 *zIdx;          /* Index into header */
65100      u8 *zEndHdr;       /* Pointer to first byte after the header */
65101      u32 offset;        /* Offset into the data */
65102      u32 szField;       /* Number of bytes in the content of a field */
65103      int szHdr;         /* Size of the header size field at start of record */
65104      int avail;         /* Number of bytes of available data */
65105      u32 t;             /* A type code from the record header */
65106      Mem *pReg;         /* PseudoTable input register */
65107    } an;
65108    struct OP_Affinity_stack_vars {
65109      const char *zAffinity;   /* The affinity to be applied */
65110      char cAff;               /* A single character of affinity */
65111    } ao;
65112    struct OP_MakeRecord_stack_vars {
65113      u8 *zNewRecord;        /* A buffer to hold the data for the new record */
65114      Mem *pRec;             /* The new record */
65115      u64 nData;             /* Number of bytes of data space */
65116      int nHdr;              /* Number of bytes of header space */
65117      i64 nByte;             /* Data space required for this record */
65118      int nZero;             /* Number of zero bytes at the end of the record */
65119      int nVarint;           /* Number of bytes in a varint */
65120      u32 serial_type;       /* Type field */
65121      Mem *pData0;           /* First field to be combined into the record */
65122      Mem *pLast;            /* Last field of the record */
65123      int nField;            /* Number of fields in the record */
65124      char *zAffinity;       /* The affinity string for the record */
65125      int file_format;       /* File format to use for encoding */
65126      int i;                 /* Space used in zNewRecord[] */
65127      int len;               /* Length of a field */
65128    } ap;
65129    struct OP_Count_stack_vars {
65130      i64 nEntry;
65131      BtCursor *pCrsr;
65132    } aq;
65133    struct OP_Savepoint_stack_vars {
65134      int p1;                         /* Value of P1 operand */
65135      char *zName;                    /* Name of savepoint */
65136      int nName;
65137      Savepoint *pNew;
65138      Savepoint *pSavepoint;
65139      Savepoint *pTmp;
65140      int iSavepoint;
65141      int ii;
65142    } ar;
65143    struct OP_AutoCommit_stack_vars {
65144      int desiredAutoCommit;
65145      int iRollback;
65146      int turnOnAC;
65147    } as;
65148    struct OP_Transaction_stack_vars {
65149      Btree *pBt;
65150    } at;
65151    struct OP_ReadCookie_stack_vars {
65152      int iMeta;
65153      int iDb;
65154      int iCookie;
65155    } au;
65156    struct OP_SetCookie_stack_vars {
65157      Db *pDb;
65158    } av;
65159    struct OP_VerifyCookie_stack_vars {
65160      int iMeta;
65161      int iGen;
65162      Btree *pBt;
65163    } aw;
65164    struct OP_OpenWrite_stack_vars {
65165      int nField;
65166      KeyInfo *pKeyInfo;
65167      int p2;
65168      int iDb;
65169      int wrFlag;
65170      Btree *pX;
65171      VdbeCursor *pCur;
65172      Db *pDb;
65173    } ax;
65174    struct OP_OpenEphemeral_stack_vars {
65175      VdbeCursor *pCx;
65176    } ay;
65177    struct OP_SorterOpen_stack_vars {
65178      VdbeCursor *pCx;
65179    } az;
65180    struct OP_OpenPseudo_stack_vars {
65181      VdbeCursor *pCx;
65182    } ba;
65183    struct OP_SeekGt_stack_vars {
65184      int res;
65185      int oc;
65186      VdbeCursor *pC;
65187      UnpackedRecord r;
65188      int nField;
65189      i64 iKey;      /* The rowid we are to seek to */
65190    } bb;
65191    struct OP_Seek_stack_vars {
65192      VdbeCursor *pC;
65193    } bc;
65194    struct OP_Found_stack_vars {
65195      int alreadyExists;
65196      VdbeCursor *pC;
65197      int res;
65198      char *pFree;
65199      UnpackedRecord *pIdxKey;
65200      UnpackedRecord r;
65201      char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65202    } bd;
65203    struct OP_IsUnique_stack_vars {
65204      u16 ii;
65205      VdbeCursor *pCx;
65206      BtCursor *pCrsr;
65207      u16 nField;
65208      Mem *aMx;
65209      UnpackedRecord r;                  /* B-Tree index search key */
65210      i64 R;                             /* Rowid stored in register P3 */
65211    } be;
65212    struct OP_NotExists_stack_vars {
65213      VdbeCursor *pC;
65214      BtCursor *pCrsr;
65215      int res;
65216      u64 iKey;
65217    } bf;
65218    struct OP_NewRowid_stack_vars {
65219      i64 v;                 /* The new rowid */
65220      VdbeCursor *pC;        /* Cursor of table to get the new rowid */
65221      int res;               /* Result of an sqlite3BtreeLast() */
65222      int cnt;               /* Counter to limit the number of searches */
65223      Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
65224      VdbeFrame *pFrame;     /* Root frame of VDBE */
65225    } bg;
65226    struct OP_InsertInt_stack_vars {
65227      Mem *pData;       /* MEM cell holding data for the record to be inserted */
65228      Mem *pKey;        /* MEM cell holding key  for the record */
65229      i64 iKey;         /* The integer ROWID or key for the record to be inserted */
65230      VdbeCursor *pC;   /* Cursor to table into which insert is written */
65231      int nZero;        /* Number of zero-bytes to append */
65232      int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
65233      const char *zDb;  /* database name - used by the update hook */
65234      const char *zTbl; /* Table name - used by the opdate hook */
65235      int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
65236    } bh;
65237    struct OP_Delete_stack_vars {
65238      i64 iKey;
65239      VdbeCursor *pC;
65240    } bi;
65241    struct OP_SorterCompare_stack_vars {
65242      VdbeCursor *pC;
65243      int res;
65244    } bj;
65245    struct OP_SorterData_stack_vars {
65246      VdbeCursor *pC;
65247    } bk;
65248    struct OP_RowData_stack_vars {
65249      VdbeCursor *pC;
65250      BtCursor *pCrsr;
65251      u32 n;
65252      i64 n64;
65253    } bl;
65254    struct OP_Rowid_stack_vars {
65255      VdbeCursor *pC;
65256      i64 v;
65257      sqlite3_vtab *pVtab;
65258      const sqlite3_module *pModule;
65259    } bm;
65260    struct OP_NullRow_stack_vars {
65261      VdbeCursor *pC;
65262    } bn;
65263    struct OP_Last_stack_vars {
65264      VdbeCursor *pC;
65265      BtCursor *pCrsr;
65266      int res;
65267    } bo;
65268    struct OP_Rewind_stack_vars {
65269      VdbeCursor *pC;
65270      BtCursor *pCrsr;
65271      int res;
65272    } bp;
65273    struct OP_Next_stack_vars {
65274      VdbeCursor *pC;
65275      int res;
65276    } bq;
65277    struct OP_IdxInsert_stack_vars {
65278      VdbeCursor *pC;
65279      BtCursor *pCrsr;
65280      int nKey;
65281      const char *zKey;
65282    } br;
65283    struct OP_IdxDelete_stack_vars {
65284      VdbeCursor *pC;
65285      BtCursor *pCrsr;
65286      int res;
65287      UnpackedRecord r;
65288    } bs;
65289    struct OP_IdxRowid_stack_vars {
65290      BtCursor *pCrsr;
65291      VdbeCursor *pC;
65292      i64 rowid;
65293    } bt;
65294    struct OP_IdxGE_stack_vars {
65295      VdbeCursor *pC;
65296      int res;
65297      UnpackedRecord r;
65298    } bu;
65299    struct OP_Destroy_stack_vars {
65300      int iMoved;
65301      int iCnt;
65302      Vdbe *pVdbe;
65303      int iDb;
65304    } bv;
65305    struct OP_Clear_stack_vars {
65306      int nChange;
65307    } bw;
65308    struct OP_CreateTable_stack_vars {
65309      int pgno;
65310      int flags;
65311      Db *pDb;
65312    } bx;
65313    struct OP_ParseSchema_stack_vars {
65314      int iDb;
65315      const char *zMaster;
65316      char *zSql;
65317      InitData initData;
65318    } by;
65319    struct OP_IntegrityCk_stack_vars {
65320      int nRoot;      /* Number of tables to check.  (Number of root pages.) */
65321      int *aRoot;     /* Array of rootpage numbers for tables to be checked */
65322      int j;          /* Loop counter */
65323      int nErr;       /* Number of errors reported */
65324      char *z;        /* Text of the error report */
65325      Mem *pnErr;     /* Register keeping track of errors remaining */
65326    } bz;
65327    struct OP_RowSetRead_stack_vars {
65328      i64 val;
65329    } ca;
65330    struct OP_RowSetTest_stack_vars {
65331      int iSet;
65332      int exists;
65333    } cb;
65334    struct OP_Program_stack_vars {
65335      int nMem;               /* Number of memory registers for sub-program */
65336      int nByte;              /* Bytes of runtime space required for sub-program */
65337      Mem *pRt;               /* Register to allocate runtime space */
65338      Mem *pMem;              /* Used to iterate through memory cells */
65339      Mem *pEnd;              /* Last memory cell in new array */
65340      VdbeFrame *pFrame;      /* New vdbe frame to execute in */
65341      SubProgram *pProgram;   /* Sub-program to execute */
65342      void *t;                /* Token identifying trigger */
65343    } cc;
65344    struct OP_Param_stack_vars {
65345      VdbeFrame *pFrame;
65346      Mem *pIn;
65347    } cd;
65348    struct OP_MemMax_stack_vars {
65349      Mem *pIn1;
65350      VdbeFrame *pFrame;
65351    } ce;
65352    struct OP_AggStep_stack_vars {
65353      int n;
65354      int i;
65355      Mem *pMem;
65356      Mem *pRec;
65357      sqlite3_context ctx;
65358      sqlite3_value **apVal;
65359    } cf;
65360    struct OP_AggFinal_stack_vars {
65361      Mem *pMem;
65362    } cg;
65363    struct OP_Checkpoint_stack_vars {
65364      int i;                          /* Loop counter */
65365      int aRes[3];                    /* Results */
65366      Mem *pMem;                      /* Write results here */
65367    } ch;
65368    struct OP_JournalMode_stack_vars {
65369      Btree *pBt;                     /* Btree to change journal mode of */
65370      Pager *pPager;                  /* Pager associated with pBt */
65371      int eNew;                       /* New journal mode */
65372      int eOld;                       /* The old journal mode */
65373      const char *zFilename;          /* Name of database file for pPager */
65374    } ci;
65375    struct OP_IncrVacuum_stack_vars {
65376      Btree *pBt;
65377    } cj;
65378    struct OP_VBegin_stack_vars {
65379      VTable *pVTab;
65380    } ck;
65381    struct OP_VOpen_stack_vars {
65382      VdbeCursor *pCur;
65383      sqlite3_vtab_cursor *pVtabCursor;
65384      sqlite3_vtab *pVtab;
65385      sqlite3_module *pModule;
65386    } cl;
65387    struct OP_VFilter_stack_vars {
65388      int nArg;
65389      int iQuery;
65390      const sqlite3_module *pModule;
65391      Mem *pQuery;
65392      Mem *pArgc;
65393      sqlite3_vtab_cursor *pVtabCursor;
65394      sqlite3_vtab *pVtab;
65395      VdbeCursor *pCur;
65396      int res;
65397      int i;
65398      Mem **apArg;
65399    } cm;
65400    struct OP_VColumn_stack_vars {
65401      sqlite3_vtab *pVtab;
65402      const sqlite3_module *pModule;
65403      Mem *pDest;
65404      sqlite3_context sContext;
65405    } cn;
65406    struct OP_VNext_stack_vars {
65407      sqlite3_vtab *pVtab;
65408      const sqlite3_module *pModule;
65409      int res;
65410      VdbeCursor *pCur;
65411    } co;
65412    struct OP_VRename_stack_vars {
65413      sqlite3_vtab *pVtab;
65414      Mem *pName;
65415    } cp;
65416    struct OP_VUpdate_stack_vars {
65417      sqlite3_vtab *pVtab;
65418      sqlite3_module *pModule;
65419      int nArg;
65420      int i;
65421      sqlite_int64 rowid;
65422      Mem **apArg;
65423      Mem *pX;
65424    } cq;
65425    struct OP_Trace_stack_vars {
65426      char *zTrace;
65427      char *z;
65428    } cr;
65429  } u;
65430  /* End automatically generated code
65431  ********************************************************************/
65432
65433  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
65434  sqlite3VdbeEnter(p);
65435  if( p->rc==SQLITE_NOMEM ){
65436    /* This happens if a malloc() inside a call to sqlite3_column_text() or
65437    ** sqlite3_column_text16() failed.  */
65438    goto no_mem;
65439  }
65440  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
65441  p->rc = SQLITE_OK;
65442  assert( p->explain==0 );
65443  p->pResultSet = 0;
65444  db->busyHandler.nBusy = 0;
65445  CHECK_FOR_INTERRUPT;
65446  sqlite3VdbeIOTraceSql(p);
65447#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65448  checkProgress = db->xProgress!=0;
65449#endif
65450#ifdef SQLITE_DEBUG
65451  sqlite3BeginBenignMalloc();
65452  if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
65453    int i;
65454    printf("VDBE Program Listing:\n");
65455    sqlite3VdbePrintSql(p);
65456    for(i=0; i<p->nOp; i++){
65457      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
65458    }
65459  }
65460  sqlite3EndBenignMalloc();
65461#endif
65462  for(pc=p->pc; rc==SQLITE_OK; pc++){
65463    assert( pc>=0 && pc<p->nOp );
65464    if( db->mallocFailed ) goto no_mem;
65465#ifdef VDBE_PROFILE
65466    origPc = pc;
65467    start = sqlite3Hwtime();
65468#endif
65469    pOp = &aOp[pc];
65470
65471    /* Only allow tracing if SQLITE_DEBUG is defined.
65472    */
65473#ifdef SQLITE_DEBUG
65474    if( p->trace ){
65475      if( pc==0 ){
65476        printf("VDBE Execution Trace:\n");
65477        sqlite3VdbePrintSql(p);
65478      }
65479      sqlite3VdbePrintOp(p->trace, pc, pOp);
65480    }
65481#endif
65482
65483
65484    /* Check to see if we need to simulate an interrupt.  This only happens
65485    ** if we have a special test build.
65486    */
65487#ifdef SQLITE_TEST
65488    if( sqlite3_interrupt_count>0 ){
65489      sqlite3_interrupt_count--;
65490      if( sqlite3_interrupt_count==0 ){
65491        sqlite3_interrupt(db);
65492      }
65493    }
65494#endif
65495
65496#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65497    /* Call the progress callback if it is configured and the required number
65498    ** of VDBE ops have been executed (either since this invocation of
65499    ** sqlite3VdbeExec() or since last time the progress callback was called).
65500    ** If the progress callback returns non-zero, exit the virtual machine with
65501    ** a return code SQLITE_ABORT.
65502    */
65503    if( checkProgress ){
65504      if( db->nProgressOps==nProgressOps ){
65505        int prc;
65506        prc = db->xProgress(db->pProgressArg);
65507        if( prc!=0 ){
65508          rc = SQLITE_INTERRUPT;
65509          goto vdbe_error_halt;
65510        }
65511        nProgressOps = 0;
65512      }
65513      nProgressOps++;
65514    }
65515#endif
65516
65517    /* On any opcode with the "out2-prerelase" tag, free any
65518    ** external allocations out of mem[p2] and set mem[p2] to be
65519    ** an undefined integer.  Opcodes will either fill in the integer
65520    ** value or convert mem[p2] to a different type.
65521    */
65522    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
65523    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
65524      assert( pOp->p2>0 );
65525      assert( pOp->p2<=p->nMem );
65526      pOut = &aMem[pOp->p2];
65527      memAboutToChange(p, pOut);
65528      VdbeMemRelease(pOut);
65529      pOut->flags = MEM_Int;
65530    }
65531
65532    /* Sanity checking on other operands */
65533#ifdef SQLITE_DEBUG
65534    if( (pOp->opflags & OPFLG_IN1)!=0 ){
65535      assert( pOp->p1>0 );
65536      assert( pOp->p1<=p->nMem );
65537      assert( memIsValid(&aMem[pOp->p1]) );
65538      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
65539    }
65540    if( (pOp->opflags & OPFLG_IN2)!=0 ){
65541      assert( pOp->p2>0 );
65542      assert( pOp->p2<=p->nMem );
65543      assert( memIsValid(&aMem[pOp->p2]) );
65544      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
65545    }
65546    if( (pOp->opflags & OPFLG_IN3)!=0 ){
65547      assert( pOp->p3>0 );
65548      assert( pOp->p3<=p->nMem );
65549      assert( memIsValid(&aMem[pOp->p3]) );
65550      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
65551    }
65552    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
65553      assert( pOp->p2>0 );
65554      assert( pOp->p2<=p->nMem );
65555      memAboutToChange(p, &aMem[pOp->p2]);
65556    }
65557    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
65558      assert( pOp->p3>0 );
65559      assert( pOp->p3<=p->nMem );
65560      memAboutToChange(p, &aMem[pOp->p3]);
65561    }
65562#endif
65563
65564    switch( pOp->opcode ){
65565
65566/*****************************************************************************
65567** What follows is a massive switch statement where each case implements a
65568** separate instruction in the virtual machine.  If we follow the usual
65569** indentation conventions, each case should be indented by 6 spaces.  But
65570** that is a lot of wasted space on the left margin.  So the code within
65571** the switch statement will break with convention and be flush-left. Another
65572** big comment (similar to this one) will mark the point in the code where
65573** we transition back to normal indentation.
65574**
65575** The formatting of each case is important.  The makefile for SQLite
65576** generates two C files "opcodes.h" and "opcodes.c" by scanning this
65577** file looking for lines that begin with "case OP_".  The opcodes.h files
65578** will be filled with #defines that give unique integer values to each
65579** opcode and the opcodes.c file is filled with an array of strings where
65580** each string is the symbolic name for the corresponding opcode.  If the
65581** case statement is followed by a comment of the form "/# same as ... #/"
65582** that comment is used to determine the particular value of the opcode.
65583**
65584** Other keywords in the comment that follows each case are used to
65585** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
65586** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
65587** the mkopcodeh.awk script for additional information.
65588**
65589** Documentation about VDBE opcodes is generated by scanning this file
65590** for lines of that contain "Opcode:".  That line and all subsequent
65591** comment lines are used in the generation of the opcode.html documentation
65592** file.
65593**
65594** SUMMARY:
65595**
65596**     Formatting is important to scripts that scan this file.
65597**     Do not deviate from the formatting style currently in use.
65598**
65599*****************************************************************************/
65600
65601/* Opcode:  Goto * P2 * * *
65602**
65603** An unconditional jump to address P2.
65604** The next instruction executed will be
65605** the one at index P2 from the beginning of
65606** the program.
65607*/
65608case OP_Goto: {             /* jump */
65609  CHECK_FOR_INTERRUPT;
65610  pc = pOp->p2 - 1;
65611  break;
65612}
65613
65614/* Opcode:  Gosub P1 P2 * * *
65615**
65616** Write the current address onto register P1
65617** and then jump to address P2.
65618*/
65619case OP_Gosub: {            /* jump */
65620  assert( pOp->p1>0 && pOp->p1<=p->nMem );
65621  pIn1 = &aMem[pOp->p1];
65622  assert( (pIn1->flags & MEM_Dyn)==0 );
65623  memAboutToChange(p, pIn1);
65624  pIn1->flags = MEM_Int;
65625  pIn1->u.i = pc;
65626  REGISTER_TRACE(pOp->p1, pIn1);
65627  pc = pOp->p2 - 1;
65628  break;
65629}
65630
65631/* Opcode:  Return P1 * * * *
65632**
65633** Jump to the next instruction after the address in register P1.
65634*/
65635case OP_Return: {           /* in1 */
65636  pIn1 = &aMem[pOp->p1];
65637  assert( pIn1->flags & MEM_Int );
65638  pc = (int)pIn1->u.i;
65639  break;
65640}
65641
65642/* Opcode:  Yield P1 * * * *
65643**
65644** Swap the program counter with the value in register P1.
65645*/
65646case OP_Yield: {            /* in1 */
65647#if 0  /* local variables moved into u.aa */
65648  int pcDest;
65649#endif /* local variables moved into u.aa */
65650  pIn1 = &aMem[pOp->p1];
65651  assert( (pIn1->flags & MEM_Dyn)==0 );
65652  pIn1->flags = MEM_Int;
65653  u.aa.pcDest = (int)pIn1->u.i;
65654  pIn1->u.i = pc;
65655  REGISTER_TRACE(pOp->p1, pIn1);
65656  pc = u.aa.pcDest;
65657  break;
65658}
65659
65660/* Opcode:  HaltIfNull  P1 P2 P3 P4 *
65661**
65662** Check the value in register P3.  If it is NULL then Halt using
65663** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
65664** value in register P3 is not NULL, then this routine is a no-op.
65665*/
65666case OP_HaltIfNull: {      /* in3 */
65667  pIn3 = &aMem[pOp->p3];
65668  if( (pIn3->flags & MEM_Null)==0 ) break;
65669  /* Fall through into OP_Halt */
65670}
65671
65672/* Opcode:  Halt P1 P2 * P4 *
65673**
65674** Exit immediately.  All open cursors, etc are closed
65675** automatically.
65676**
65677** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
65678** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
65679** For errors, it can be some other value.  If P1!=0 then P2 will determine
65680** whether or not to rollback the current transaction.  Do not rollback
65681** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
65682** then back out all changes that have occurred during this execution of the
65683** VDBE, but do not rollback the transaction.
65684**
65685** If P4 is not null then it is an error message string.
65686**
65687** There is an implied "Halt 0 0 0" instruction inserted at the very end of
65688** every program.  So a jump past the last instruction of the program
65689** is the same as executing Halt.
65690*/
65691case OP_Halt: {
65692  if( pOp->p1==SQLITE_OK && p->pFrame ){
65693    /* Halt the sub-program. Return control to the parent frame. */
65694    VdbeFrame *pFrame = p->pFrame;
65695    p->pFrame = pFrame->pParent;
65696    p->nFrame--;
65697    sqlite3VdbeSetChanges(db, p->nChange);
65698    pc = sqlite3VdbeFrameRestore(pFrame);
65699    lastRowid = db->lastRowid;
65700    if( pOp->p2==OE_Ignore ){
65701      /* Instruction pc is the OP_Program that invoked the sub-program
65702      ** currently being halted. If the p2 instruction of this OP_Halt
65703      ** instruction is set to OE_Ignore, then the sub-program is throwing
65704      ** an IGNORE exception. In this case jump to the address specified
65705      ** as the p2 of the calling OP_Program.  */
65706      pc = p->aOp[pc].p2-1;
65707    }
65708    aOp = p->aOp;
65709    aMem = p->aMem;
65710    break;
65711  }
65712
65713  p->rc = pOp->p1;
65714  p->errorAction = (u8)pOp->p2;
65715  p->pc = pc;
65716  if( pOp->p4.z ){
65717    assert( p->rc!=SQLITE_OK );
65718    sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
65719    testcase( sqlite3GlobalConfig.xLog!=0 );
65720    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
65721  }else if( p->rc ){
65722    testcase( sqlite3GlobalConfig.xLog!=0 );
65723    sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
65724  }
65725  rc = sqlite3VdbeHalt(p);
65726  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
65727  if( rc==SQLITE_BUSY ){
65728    p->rc = rc = SQLITE_BUSY;
65729  }else{
65730    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
65731    assert( rc==SQLITE_OK || db->nDeferredCons>0 );
65732    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
65733  }
65734  goto vdbe_return;
65735}
65736
65737/* Opcode: Integer P1 P2 * * *
65738**
65739** The 32-bit integer value P1 is written into register P2.
65740*/
65741case OP_Integer: {         /* out2-prerelease */
65742  pOut->u.i = pOp->p1;
65743  break;
65744}
65745
65746/* Opcode: Int64 * P2 * P4 *
65747**
65748** P4 is a pointer to a 64-bit integer value.
65749** Write that value into register P2.
65750*/
65751case OP_Int64: {           /* out2-prerelease */
65752  assert( pOp->p4.pI64!=0 );
65753  pOut->u.i = *pOp->p4.pI64;
65754  break;
65755}
65756
65757#ifndef SQLITE_OMIT_FLOATING_POINT
65758/* Opcode: Real * P2 * P4 *
65759**
65760** P4 is a pointer to a 64-bit floating point value.
65761** Write that value into register P2.
65762*/
65763case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
65764  pOut->flags = MEM_Real;
65765  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
65766  pOut->r = *pOp->p4.pReal;
65767  break;
65768}
65769#endif
65770
65771/* Opcode: String8 * P2 * P4 *
65772**
65773** P4 points to a nul terminated UTF-8 string. This opcode is transformed
65774** into an OP_String before it is executed for the first time.
65775*/
65776case OP_String8: {         /* same as TK_STRING, out2-prerelease */
65777  assert( pOp->p4.z!=0 );
65778  pOp->opcode = OP_String;
65779  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
65780
65781#ifndef SQLITE_OMIT_UTF16
65782  if( encoding!=SQLITE_UTF8 ){
65783    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
65784    if( rc==SQLITE_TOOBIG ) goto too_big;
65785    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
65786    assert( pOut->zMalloc==pOut->z );
65787    assert( pOut->flags & MEM_Dyn );
65788    pOut->zMalloc = 0;
65789    pOut->flags |= MEM_Static;
65790    pOut->flags &= ~MEM_Dyn;
65791    if( pOp->p4type==P4_DYNAMIC ){
65792      sqlite3DbFree(db, pOp->p4.z);
65793    }
65794    pOp->p4type = P4_DYNAMIC;
65795    pOp->p4.z = pOut->z;
65796    pOp->p1 = pOut->n;
65797  }
65798#endif
65799  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
65800    goto too_big;
65801  }
65802  /* Fall through to the next case, OP_String */
65803}
65804
65805/* Opcode: String P1 P2 * P4 *
65806**
65807** The string value P4 of length P1 (bytes) is stored in register P2.
65808*/
65809case OP_String: {          /* out2-prerelease */
65810  assert( pOp->p4.z!=0 );
65811  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
65812  pOut->z = pOp->p4.z;
65813  pOut->n = pOp->p1;
65814  pOut->enc = encoding;
65815  UPDATE_MAX_BLOBSIZE(pOut);
65816  break;
65817}
65818
65819/* Opcode: Null * P2 P3 * *
65820**
65821** Write a NULL into registers P2.  If P3 greater than P2, then also write
65822** NULL into register P3 and ever register in between P2 and P3.  If P3
65823** is less than P2 (typically P3 is zero) then only register P2 is
65824** set to NULL
65825*/
65826case OP_Null: {           /* out2-prerelease */
65827#if 0  /* local variables moved into u.ab */
65828  int cnt;
65829#endif /* local variables moved into u.ab */
65830  u.ab.cnt = pOp->p3-pOp->p2;
65831  assert( pOp->p3<=p->nMem );
65832  pOut->flags = MEM_Null;
65833  while( u.ab.cnt>0 ){
65834    pOut++;
65835    memAboutToChange(p, pOut);
65836    VdbeMemRelease(pOut);
65837    pOut->flags = MEM_Null;
65838    u.ab.cnt--;
65839  }
65840  break;
65841}
65842
65843
65844/* Opcode: Blob P1 P2 * P4
65845**
65846** P4 points to a blob of data P1 bytes long.  Store this
65847** blob in register P2.
65848*/
65849case OP_Blob: {                /* out2-prerelease */
65850  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
65851  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
65852  pOut->enc = encoding;
65853  UPDATE_MAX_BLOBSIZE(pOut);
65854  break;
65855}
65856
65857/* Opcode: Variable P1 P2 * P4 *
65858**
65859** Transfer the values of bound parameter P1 into register P2
65860**
65861** If the parameter is named, then its name appears in P4 and P3==1.
65862** The P4 value is used by sqlite3_bind_parameter_name().
65863*/
65864case OP_Variable: {            /* out2-prerelease */
65865#if 0  /* local variables moved into u.ac */
65866  Mem *pVar;       /* Value being transferred */
65867#endif /* local variables moved into u.ac */
65868
65869  assert( pOp->p1>0 && pOp->p1<=p->nVar );
65870  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
65871  u.ac.pVar = &p->aVar[pOp->p1 - 1];
65872  if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
65873    goto too_big;
65874  }
65875  sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
65876  UPDATE_MAX_BLOBSIZE(pOut);
65877  break;
65878}
65879
65880/* Opcode: Move P1 P2 P3 * *
65881**
65882** Move the values in register P1..P1+P3-1 over into
65883** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
65884** left holding a NULL.  It is an error for register ranges
65885** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
65886*/
65887case OP_Move: {
65888#if 0  /* local variables moved into u.ad */
65889  char *zMalloc;   /* Holding variable for allocated memory */
65890  int n;           /* Number of registers left to copy */
65891  int p1;          /* Register to copy from */
65892  int p2;          /* Register to copy to */
65893#endif /* local variables moved into u.ad */
65894
65895  u.ad.n = pOp->p3;
65896  u.ad.p1 = pOp->p1;
65897  u.ad.p2 = pOp->p2;
65898  assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
65899  assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
65900
65901  pIn1 = &aMem[u.ad.p1];
65902  pOut = &aMem[u.ad.p2];
65903  while( u.ad.n-- ){
65904    assert( pOut<=&aMem[p->nMem] );
65905    assert( pIn1<=&aMem[p->nMem] );
65906    assert( memIsValid(pIn1) );
65907    memAboutToChange(p, pOut);
65908    u.ad.zMalloc = pOut->zMalloc;
65909    pOut->zMalloc = 0;
65910    sqlite3VdbeMemMove(pOut, pIn1);
65911#ifdef SQLITE_DEBUG
65912    if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
65913      pOut->pScopyFrom += u.ad.p1 - pOp->p2;
65914    }
65915#endif
65916    pIn1->zMalloc = u.ad.zMalloc;
65917    REGISTER_TRACE(u.ad.p2++, pOut);
65918    pIn1++;
65919    pOut++;
65920  }
65921  break;
65922}
65923
65924/* Opcode: Copy P1 P2 * * *
65925**
65926** Make a copy of register P1 into register P2.
65927**
65928** This instruction makes a deep copy of the value.  A duplicate
65929** is made of any string or blob constant.  See also OP_SCopy.
65930*/
65931case OP_Copy: {             /* in1, out2 */
65932  pIn1 = &aMem[pOp->p1];
65933  pOut = &aMem[pOp->p2];
65934  assert( pOut!=pIn1 );
65935  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65936  Deephemeralize(pOut);
65937  REGISTER_TRACE(pOp->p2, pOut);
65938  break;
65939}
65940
65941/* Opcode: SCopy P1 P2 * * *
65942**
65943** Make a shallow copy of register P1 into register P2.
65944**
65945** This instruction makes a shallow copy of the value.  If the value
65946** is a string or blob, then the copy is only a pointer to the
65947** original and hence if the original changes so will the copy.
65948** Worse, if the original is deallocated, the copy becomes invalid.
65949** Thus the program must guarantee that the original will not change
65950** during the lifetime of the copy.  Use OP_Copy to make a complete
65951** copy.
65952*/
65953case OP_SCopy: {            /* in1, out2 */
65954  pIn1 = &aMem[pOp->p1];
65955  pOut = &aMem[pOp->p2];
65956  assert( pOut!=pIn1 );
65957  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65958#ifdef SQLITE_DEBUG
65959  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
65960#endif
65961  REGISTER_TRACE(pOp->p2, pOut);
65962  break;
65963}
65964
65965/* Opcode: ResultRow P1 P2 * * *
65966**
65967** The registers P1 through P1+P2-1 contain a single row of
65968** results. This opcode causes the sqlite3_step() call to terminate
65969** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
65970** structure to provide access to the top P1 values as the result
65971** row.
65972*/
65973case OP_ResultRow: {
65974#if 0  /* local variables moved into u.ae */
65975  Mem *pMem;
65976  int i;
65977#endif /* local variables moved into u.ae */
65978  assert( p->nResColumn==pOp->p2 );
65979  assert( pOp->p1>0 );
65980  assert( pOp->p1+pOp->p2<=p->nMem+1 );
65981
65982  /* If this statement has violated immediate foreign key constraints, do
65983  ** not return the number of rows modified. And do not RELEASE the statement
65984  ** transaction. It needs to be rolled back.  */
65985  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
65986    assert( db->flags&SQLITE_CountRows );
65987    assert( p->usesStmtJournal );
65988    break;
65989  }
65990
65991  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
65992  ** DML statements invoke this opcode to return the number of rows
65993  ** modified to the user. This is the only way that a VM that
65994  ** opens a statement transaction may invoke this opcode.
65995  **
65996  ** In case this is such a statement, close any statement transaction
65997  ** opened by this VM before returning control to the user. This is to
65998  ** ensure that statement-transactions are always nested, not overlapping.
65999  ** If the open statement-transaction is not closed here, then the user
66000  ** may step another VM that opens its own statement transaction. This
66001  ** may lead to overlapping statement transactions.
66002  **
66003  ** The statement transaction is never a top-level transaction.  Hence
66004  ** the RELEASE call below can never fail.
66005  */
66006  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
66007  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
66008  if( NEVER(rc!=SQLITE_OK) ){
66009    break;
66010  }
66011
66012  /* Invalidate all ephemeral cursor row caches */
66013  p->cacheCtr = (p->cacheCtr + 2)|1;
66014
66015  /* Make sure the results of the current row are \000 terminated
66016  ** and have an assigned type.  The results are de-ephemeralized as
66017  ** a side effect.
66018  */
66019  u.ae.pMem = p->pResultSet = &aMem[pOp->p1];
66020  for(u.ae.i=0; u.ae.i<pOp->p2; u.ae.i++){
66021    assert( memIsValid(&u.ae.pMem[u.ae.i]) );
66022    Deephemeralize(&u.ae.pMem[u.ae.i]);
66023    assert( (u.ae.pMem[u.ae.i].flags & MEM_Ephem)==0
66024            || (u.ae.pMem[u.ae.i].flags & (MEM_Str|MEM_Blob))==0 );
66025    sqlite3VdbeMemNulTerminate(&u.ae.pMem[u.ae.i]);
66026    sqlite3VdbeMemStoreType(&u.ae.pMem[u.ae.i]);
66027    REGISTER_TRACE(pOp->p1+u.ae.i, &u.ae.pMem[u.ae.i]);
66028  }
66029  if( db->mallocFailed ) goto no_mem;
66030
66031  /* Return SQLITE_ROW
66032  */
66033  p->pc = pc + 1;
66034  rc = SQLITE_ROW;
66035  goto vdbe_return;
66036}
66037
66038/* Opcode: Concat P1 P2 P3 * *
66039**
66040** Add the text in register P1 onto the end of the text in
66041** register P2 and store the result in register P3.
66042** If either the P1 or P2 text are NULL then store NULL in P3.
66043**
66044**   P3 = P2 || P1
66045**
66046** It is illegal for P1 and P3 to be the same register. Sometimes,
66047** if P3 is the same register as P2, the implementation is able
66048** to avoid a memcpy().
66049*/
66050case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
66051#if 0  /* local variables moved into u.af */
66052  i64 nByte;
66053#endif /* local variables moved into u.af */
66054
66055  pIn1 = &aMem[pOp->p1];
66056  pIn2 = &aMem[pOp->p2];
66057  pOut = &aMem[pOp->p3];
66058  assert( pIn1!=pOut );
66059  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66060    sqlite3VdbeMemSetNull(pOut);
66061    break;
66062  }
66063  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
66064  Stringify(pIn1, encoding);
66065  Stringify(pIn2, encoding);
66066  u.af.nByte = pIn1->n + pIn2->n;
66067  if( u.af.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66068    goto too_big;
66069  }
66070  MemSetTypeFlag(pOut, MEM_Str);
66071  if( sqlite3VdbeMemGrow(pOut, (int)u.af.nByte+2, pOut==pIn2) ){
66072    goto no_mem;
66073  }
66074  if( pOut!=pIn2 ){
66075    memcpy(pOut->z, pIn2->z, pIn2->n);
66076  }
66077  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
66078  pOut->z[u.af.nByte] = 0;
66079  pOut->z[u.af.nByte+1] = 0;
66080  pOut->flags |= MEM_Term;
66081  pOut->n = (int)u.af.nByte;
66082  pOut->enc = encoding;
66083  UPDATE_MAX_BLOBSIZE(pOut);
66084  break;
66085}
66086
66087/* Opcode: Add P1 P2 P3 * *
66088**
66089** Add the value in register P1 to the value in register P2
66090** and store the result in register P3.
66091** If either input is NULL, the result is NULL.
66092*/
66093/* Opcode: Multiply P1 P2 P3 * *
66094**
66095**
66096** Multiply the value in register P1 by the value in register P2
66097** and store the result in register P3.
66098** If either input is NULL, the result is NULL.
66099*/
66100/* Opcode: Subtract P1 P2 P3 * *
66101**
66102** Subtract the value in register P1 from the value in register P2
66103** and store the result in register P3.
66104** If either input is NULL, the result is NULL.
66105*/
66106/* Opcode: Divide P1 P2 P3 * *
66107**
66108** Divide the value in register P1 by the value in register P2
66109** and store the result in register P3 (P3=P2/P1). If the value in
66110** register P1 is zero, then the result is NULL. If either input is
66111** NULL, the result is NULL.
66112*/
66113/* Opcode: Remainder P1 P2 P3 * *
66114**
66115** Compute the remainder after integer division of the value in
66116** register P1 by the value in register P2 and store the result in P3.
66117** If the value in register P2 is zero the result is NULL.
66118** If either operand is NULL, the result is NULL.
66119*/
66120case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
66121case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
66122case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
66123case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
66124case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
66125#if 0  /* local variables moved into u.ag */
66126  int flags;      /* Combined MEM_* flags from both inputs */
66127  i64 iA;         /* Integer value of left operand */
66128  i64 iB;         /* Integer value of right operand */
66129  double rA;      /* Real value of left operand */
66130  double rB;      /* Real value of right operand */
66131#endif /* local variables moved into u.ag */
66132
66133  pIn1 = &aMem[pOp->p1];
66134  applyNumericAffinity(pIn1);
66135  pIn2 = &aMem[pOp->p2];
66136  applyNumericAffinity(pIn2);
66137  pOut = &aMem[pOp->p3];
66138  u.ag.flags = pIn1->flags | pIn2->flags;
66139  if( (u.ag.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
66140  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
66141    u.ag.iA = pIn1->u.i;
66142    u.ag.iB = pIn2->u.i;
66143    switch( pOp->opcode ){
66144      case OP_Add:       if( sqlite3AddInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
66145      case OP_Subtract:  if( sqlite3SubInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
66146      case OP_Multiply:  if( sqlite3MulInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
66147      case OP_Divide: {
66148        if( u.ag.iA==0 ) goto arithmetic_result_is_null;
66149        if( u.ag.iA==-1 && u.ag.iB==SMALLEST_INT64 ) goto fp_math;
66150        u.ag.iB /= u.ag.iA;
66151        break;
66152      }
66153      default: {
66154        if( u.ag.iA==0 ) goto arithmetic_result_is_null;
66155        if( u.ag.iA==-1 ) u.ag.iA = 1;
66156        u.ag.iB %= u.ag.iA;
66157        break;
66158      }
66159    }
66160    pOut->u.i = u.ag.iB;
66161    MemSetTypeFlag(pOut, MEM_Int);
66162  }else{
66163fp_math:
66164    u.ag.rA = sqlite3VdbeRealValue(pIn1);
66165    u.ag.rB = sqlite3VdbeRealValue(pIn2);
66166    switch( pOp->opcode ){
66167      case OP_Add:         u.ag.rB += u.ag.rA;       break;
66168      case OP_Subtract:    u.ag.rB -= u.ag.rA;       break;
66169      case OP_Multiply:    u.ag.rB *= u.ag.rA;       break;
66170      case OP_Divide: {
66171        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
66172        if( u.ag.rA==(double)0 ) goto arithmetic_result_is_null;
66173        u.ag.rB /= u.ag.rA;
66174        break;
66175      }
66176      default: {
66177        u.ag.iA = (i64)u.ag.rA;
66178        u.ag.iB = (i64)u.ag.rB;
66179        if( u.ag.iA==0 ) goto arithmetic_result_is_null;
66180        if( u.ag.iA==-1 ) u.ag.iA = 1;
66181        u.ag.rB = (double)(u.ag.iB % u.ag.iA);
66182        break;
66183      }
66184    }
66185#ifdef SQLITE_OMIT_FLOATING_POINT
66186    pOut->u.i = u.ag.rB;
66187    MemSetTypeFlag(pOut, MEM_Int);
66188#else
66189    if( sqlite3IsNaN(u.ag.rB) ){
66190      goto arithmetic_result_is_null;
66191    }
66192    pOut->r = u.ag.rB;
66193    MemSetTypeFlag(pOut, MEM_Real);
66194    if( (u.ag.flags & MEM_Real)==0 ){
66195      sqlite3VdbeIntegerAffinity(pOut);
66196    }
66197#endif
66198  }
66199  break;
66200
66201arithmetic_result_is_null:
66202  sqlite3VdbeMemSetNull(pOut);
66203  break;
66204}
66205
66206/* Opcode: CollSeq P1 * * P4
66207**
66208** P4 is a pointer to a CollSeq struct. If the next call to a user function
66209** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
66210** be returned. This is used by the built-in min(), max() and nullif()
66211** functions.
66212**
66213** If P1 is not zero, then it is a register that a subsequent min() or
66214** max() aggregate will set to 1 if the current row is not the minimum or
66215** maximum.  The P1 register is initialized to 0 by this instruction.
66216**
66217** The interface used by the implementation of the aforementioned functions
66218** to retrieve the collation sequence set by this opcode is not available
66219** publicly, only to user functions defined in func.c.
66220*/
66221case OP_CollSeq: {
66222  assert( pOp->p4type==P4_COLLSEQ );
66223  if( pOp->p1 ){
66224    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
66225  }
66226  break;
66227}
66228
66229/* Opcode: Function P1 P2 P3 P4 P5
66230**
66231** Invoke a user function (P4 is a pointer to a Function structure that
66232** defines the function) with P5 arguments taken from register P2 and
66233** successors.  The result of the function is stored in register P3.
66234** Register P3 must not be one of the function inputs.
66235**
66236** P1 is a 32-bit bitmask indicating whether or not each argument to the
66237** function was determined to be constant at compile time. If the first
66238** argument was constant then bit 0 of P1 is set. This is used to determine
66239** whether meta data associated with a user function argument using the
66240** sqlite3_set_auxdata() API may be safely retained until the next
66241** invocation of this opcode.
66242**
66243** See also: AggStep and AggFinal
66244*/
66245case OP_Function: {
66246#if 0  /* local variables moved into u.ah */
66247  int i;
66248  Mem *pArg;
66249  sqlite3_context ctx;
66250  sqlite3_value **apVal;
66251  int n;
66252#endif /* local variables moved into u.ah */
66253
66254  u.ah.n = pOp->p5;
66255  u.ah.apVal = p->apArg;
66256  assert( u.ah.apVal || u.ah.n==0 );
66257  assert( pOp->p3>0 && pOp->p3<=p->nMem );
66258  pOut = &aMem[pOp->p3];
66259  memAboutToChange(p, pOut);
66260
66261  assert( u.ah.n==0 || (pOp->p2>0 && pOp->p2+u.ah.n<=p->nMem+1) );
66262  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ah.n );
66263  u.ah.pArg = &aMem[pOp->p2];
66264  for(u.ah.i=0; u.ah.i<u.ah.n; u.ah.i++, u.ah.pArg++){
66265    assert( memIsValid(u.ah.pArg) );
66266    u.ah.apVal[u.ah.i] = u.ah.pArg;
66267    Deephemeralize(u.ah.pArg);
66268    sqlite3VdbeMemStoreType(u.ah.pArg);
66269    REGISTER_TRACE(pOp->p2+u.ah.i, u.ah.pArg);
66270  }
66271
66272  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
66273  if( pOp->p4type==P4_FUNCDEF ){
66274    u.ah.ctx.pFunc = pOp->p4.pFunc;
66275    u.ah.ctx.pVdbeFunc = 0;
66276  }else{
66277    u.ah.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
66278    u.ah.ctx.pFunc = u.ah.ctx.pVdbeFunc->pFunc;
66279  }
66280
66281  u.ah.ctx.s.flags = MEM_Null;
66282  u.ah.ctx.s.db = db;
66283  u.ah.ctx.s.xDel = 0;
66284  u.ah.ctx.s.zMalloc = 0;
66285
66286  /* The output cell may already have a buffer allocated. Move
66287  ** the pointer to u.ah.ctx.s so in case the user-function can use
66288  ** the already allocated buffer instead of allocating a new one.
66289  */
66290  sqlite3VdbeMemMove(&u.ah.ctx.s, pOut);
66291  MemSetTypeFlag(&u.ah.ctx.s, MEM_Null);
66292
66293  u.ah.ctx.isError = 0;
66294  if( u.ah.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
66295    assert( pOp>aOp );
66296    assert( pOp[-1].p4type==P4_COLLSEQ );
66297    assert( pOp[-1].opcode==OP_CollSeq );
66298    u.ah.ctx.pColl = pOp[-1].p4.pColl;
66299  }
66300  db->lastRowid = lastRowid;
66301  (*u.ah.ctx.pFunc->xFunc)(&u.ah.ctx, u.ah.n, u.ah.apVal); /* IMP: R-24505-23230 */
66302  lastRowid = db->lastRowid;
66303
66304  /* If any auxiliary data functions have been called by this user function,
66305  ** immediately call the destructor for any non-static values.
66306  */
66307  if( u.ah.ctx.pVdbeFunc ){
66308    sqlite3VdbeDeleteAuxData(u.ah.ctx.pVdbeFunc, pOp->p1);
66309    pOp->p4.pVdbeFunc = u.ah.ctx.pVdbeFunc;
66310    pOp->p4type = P4_VDBEFUNC;
66311  }
66312
66313  if( db->mallocFailed ){
66314    /* Even though a malloc() has failed, the implementation of the
66315    ** user function may have called an sqlite3_result_XXX() function
66316    ** to return a value. The following call releases any resources
66317    ** associated with such a value.
66318    */
66319    sqlite3VdbeMemRelease(&u.ah.ctx.s);
66320    goto no_mem;
66321  }
66322
66323  /* If the function returned an error, throw an exception */
66324  if( u.ah.ctx.isError ){
66325    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ah.ctx.s));
66326    rc = u.ah.ctx.isError;
66327  }
66328
66329  /* Copy the result of the function into register P3 */
66330  sqlite3VdbeChangeEncoding(&u.ah.ctx.s, encoding);
66331  sqlite3VdbeMemMove(pOut, &u.ah.ctx.s);
66332  if( sqlite3VdbeMemTooBig(pOut) ){
66333    goto too_big;
66334  }
66335
66336#if 0
66337  /* The app-defined function has done something that as caused this
66338  ** statement to expire.  (Perhaps the function called sqlite3_exec()
66339  ** with a CREATE TABLE statement.)
66340  */
66341  if( p->expired ) rc = SQLITE_ABORT;
66342#endif
66343
66344  REGISTER_TRACE(pOp->p3, pOut);
66345  UPDATE_MAX_BLOBSIZE(pOut);
66346  break;
66347}
66348
66349/* Opcode: BitAnd P1 P2 P3 * *
66350**
66351** Take the bit-wise AND of the values in register P1 and P2 and
66352** store the result in register P3.
66353** If either input is NULL, the result is NULL.
66354*/
66355/* Opcode: BitOr P1 P2 P3 * *
66356**
66357** Take the bit-wise OR of the values in register P1 and P2 and
66358** store the result in register P3.
66359** If either input is NULL, the result is NULL.
66360*/
66361/* Opcode: ShiftLeft P1 P2 P3 * *
66362**
66363** Shift the integer value in register P2 to the left by the
66364** number of bits specified by the integer in register P1.
66365** Store the result in register P3.
66366** If either input is NULL, the result is NULL.
66367*/
66368/* Opcode: ShiftRight P1 P2 P3 * *
66369**
66370** Shift the integer value in register P2 to the right by the
66371** number of bits specified by the integer in register P1.
66372** Store the result in register P3.
66373** If either input is NULL, the result is NULL.
66374*/
66375case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
66376case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
66377case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
66378case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
66379#if 0  /* local variables moved into u.ai */
66380  i64 iA;
66381  u64 uA;
66382  i64 iB;
66383  u8 op;
66384#endif /* local variables moved into u.ai */
66385
66386  pIn1 = &aMem[pOp->p1];
66387  pIn2 = &aMem[pOp->p2];
66388  pOut = &aMem[pOp->p3];
66389  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66390    sqlite3VdbeMemSetNull(pOut);
66391    break;
66392  }
66393  u.ai.iA = sqlite3VdbeIntValue(pIn2);
66394  u.ai.iB = sqlite3VdbeIntValue(pIn1);
66395  u.ai.op = pOp->opcode;
66396  if( u.ai.op==OP_BitAnd ){
66397    u.ai.iA &= u.ai.iB;
66398  }else if( u.ai.op==OP_BitOr ){
66399    u.ai.iA |= u.ai.iB;
66400  }else if( u.ai.iB!=0 ){
66401    assert( u.ai.op==OP_ShiftRight || u.ai.op==OP_ShiftLeft );
66402
66403    /* If shifting by a negative amount, shift in the other direction */
66404    if( u.ai.iB<0 ){
66405      assert( OP_ShiftRight==OP_ShiftLeft+1 );
66406      u.ai.op = 2*OP_ShiftLeft + 1 - u.ai.op;
66407      u.ai.iB = u.ai.iB>(-64) ? -u.ai.iB : 64;
66408    }
66409
66410    if( u.ai.iB>=64 ){
66411      u.ai.iA = (u.ai.iA>=0 || u.ai.op==OP_ShiftLeft) ? 0 : -1;
66412    }else{
66413      memcpy(&u.ai.uA, &u.ai.iA, sizeof(u.ai.uA));
66414      if( u.ai.op==OP_ShiftLeft ){
66415        u.ai.uA <<= u.ai.iB;
66416      }else{
66417        u.ai.uA >>= u.ai.iB;
66418        /* Sign-extend on a right shift of a negative number */
66419        if( u.ai.iA<0 ) u.ai.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ai.iB);
66420      }
66421      memcpy(&u.ai.iA, &u.ai.uA, sizeof(u.ai.iA));
66422    }
66423  }
66424  pOut->u.i = u.ai.iA;
66425  MemSetTypeFlag(pOut, MEM_Int);
66426  break;
66427}
66428
66429/* Opcode: AddImm  P1 P2 * * *
66430**
66431** Add the constant P2 to the value in register P1.
66432** The result is always an integer.
66433**
66434** To force any register to be an integer, just add 0.
66435*/
66436case OP_AddImm: {            /* in1 */
66437  pIn1 = &aMem[pOp->p1];
66438  memAboutToChange(p, pIn1);
66439  sqlite3VdbeMemIntegerify(pIn1);
66440  pIn1->u.i += pOp->p2;
66441  break;
66442}
66443
66444/* Opcode: MustBeInt P1 P2 * * *
66445**
66446** Force the value in register P1 to be an integer.  If the value
66447** in P1 is not an integer and cannot be converted into an integer
66448** without data loss, then jump immediately to P2, or if P2==0
66449** raise an SQLITE_MISMATCH exception.
66450*/
66451case OP_MustBeInt: {            /* jump, in1 */
66452  pIn1 = &aMem[pOp->p1];
66453  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
66454  if( (pIn1->flags & MEM_Int)==0 ){
66455    if( pOp->p2==0 ){
66456      rc = SQLITE_MISMATCH;
66457      goto abort_due_to_error;
66458    }else{
66459      pc = pOp->p2 - 1;
66460    }
66461  }else{
66462    MemSetTypeFlag(pIn1, MEM_Int);
66463  }
66464  break;
66465}
66466
66467#ifndef SQLITE_OMIT_FLOATING_POINT
66468/* Opcode: RealAffinity P1 * * * *
66469**
66470** If register P1 holds an integer convert it to a real value.
66471**
66472** This opcode is used when extracting information from a column that
66473** has REAL affinity.  Such column values may still be stored as
66474** integers, for space efficiency, but after extraction we want them
66475** to have only a real value.
66476*/
66477case OP_RealAffinity: {                  /* in1 */
66478  pIn1 = &aMem[pOp->p1];
66479  if( pIn1->flags & MEM_Int ){
66480    sqlite3VdbeMemRealify(pIn1);
66481  }
66482  break;
66483}
66484#endif
66485
66486#ifndef SQLITE_OMIT_CAST
66487/* Opcode: ToText P1 * * * *
66488**
66489** Force the value in register P1 to be text.
66490** If the value is numeric, convert it to a string using the
66491** equivalent of printf().  Blob values are unchanged and
66492** are afterwards simply interpreted as text.
66493**
66494** A NULL value is not changed by this routine.  It remains NULL.
66495*/
66496case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
66497  pIn1 = &aMem[pOp->p1];
66498  memAboutToChange(p, pIn1);
66499  if( pIn1->flags & MEM_Null ) break;
66500  assert( MEM_Str==(MEM_Blob>>3) );
66501  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
66502  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
66503  rc = ExpandBlob(pIn1);
66504  assert( pIn1->flags & MEM_Str || db->mallocFailed );
66505  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
66506  UPDATE_MAX_BLOBSIZE(pIn1);
66507  break;
66508}
66509
66510/* Opcode: ToBlob P1 * * * *
66511**
66512** Force the value in register P1 to be a BLOB.
66513** If the value is numeric, convert it to a string first.
66514** Strings are simply reinterpreted as blobs with no change
66515** to the underlying data.
66516**
66517** A NULL value is not changed by this routine.  It remains NULL.
66518*/
66519case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
66520  pIn1 = &aMem[pOp->p1];
66521  if( pIn1->flags & MEM_Null ) break;
66522  if( (pIn1->flags & MEM_Blob)==0 ){
66523    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
66524    assert( pIn1->flags & MEM_Str || db->mallocFailed );
66525    MemSetTypeFlag(pIn1, MEM_Blob);
66526  }else{
66527    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
66528  }
66529  UPDATE_MAX_BLOBSIZE(pIn1);
66530  break;
66531}
66532
66533/* Opcode: ToNumeric P1 * * * *
66534**
66535** Force the value in register P1 to be numeric (either an
66536** integer or a floating-point number.)
66537** If the value is text or blob, try to convert it to an using the
66538** equivalent of atoi() or atof() and store 0 if no such conversion
66539** is possible.
66540**
66541** A NULL value is not changed by this routine.  It remains NULL.
66542*/
66543case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
66544  pIn1 = &aMem[pOp->p1];
66545  sqlite3VdbeMemNumerify(pIn1);
66546  break;
66547}
66548#endif /* SQLITE_OMIT_CAST */
66549
66550/* Opcode: ToInt P1 * * * *
66551**
66552** Force the value in register P1 to be an integer.  If
66553** The value is currently a real number, drop its fractional part.
66554** If the value is text or blob, try to convert it to an integer using the
66555** equivalent of atoi() and store 0 if no such conversion is possible.
66556**
66557** A NULL value is not changed by this routine.  It remains NULL.
66558*/
66559case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
66560  pIn1 = &aMem[pOp->p1];
66561  if( (pIn1->flags & MEM_Null)==0 ){
66562    sqlite3VdbeMemIntegerify(pIn1);
66563  }
66564  break;
66565}
66566
66567#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
66568/* Opcode: ToReal P1 * * * *
66569**
66570** Force the value in register P1 to be a floating point number.
66571** If The value is currently an integer, convert it.
66572** If the value is text or blob, try to convert it to an integer using the
66573** equivalent of atoi() and store 0.0 if no such conversion is possible.
66574**
66575** A NULL value is not changed by this routine.  It remains NULL.
66576*/
66577case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
66578  pIn1 = &aMem[pOp->p1];
66579  memAboutToChange(p, pIn1);
66580  if( (pIn1->flags & MEM_Null)==0 ){
66581    sqlite3VdbeMemRealify(pIn1);
66582  }
66583  break;
66584}
66585#endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
66586
66587/* Opcode: Lt P1 P2 P3 P4 P5
66588**
66589** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
66590** jump to address P2.
66591**
66592** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
66593** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
66594** bit is clear then fall through if either operand is NULL.
66595**
66596** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
66597** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
66598** to coerce both inputs according to this affinity before the
66599** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
66600** affinity is used. Note that the affinity conversions are stored
66601** back into the input registers P1 and P3.  So this opcode can cause
66602** persistent changes to registers P1 and P3.
66603**
66604** Once any conversions have taken place, and neither value is NULL,
66605** the values are compared. If both values are blobs then memcmp() is
66606** used to determine the results of the comparison.  If both values
66607** are text, then the appropriate collating function specified in
66608** P4 is  used to do the comparison.  If P4 is not specified then
66609** memcmp() is used to compare text string.  If both values are
66610** numeric, then a numeric comparison is used. If the two values
66611** are of different types, then numbers are considered less than
66612** strings and strings are considered less than blobs.
66613**
66614** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
66615** store a boolean result (either 0, or 1, or NULL) in register P2.
66616*/
66617/* Opcode: Ne P1 P2 P3 P4 P5
66618**
66619** This works just like the Lt opcode except that the jump is taken if
66620** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
66621** additional information.
66622**
66623** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
66624** true or false and is never NULL.  If both operands are NULL then the result
66625** of comparison is false.  If either operand is NULL then the result is true.
66626** If neither operand is NULL the result is the same as it would be if
66627** the SQLITE_NULLEQ flag were omitted from P5.
66628*/
66629/* Opcode: Eq P1 P2 P3 P4 P5
66630**
66631** This works just like the Lt opcode except that the jump is taken if
66632** the operands in registers P1 and P3 are equal.
66633** See the Lt opcode for additional information.
66634**
66635** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
66636** true or false and is never NULL.  If both operands are NULL then the result
66637** of comparison is true.  If either operand is NULL then the result is false.
66638** If neither operand is NULL the result is the same as it would be if
66639** the SQLITE_NULLEQ flag were omitted from P5.
66640*/
66641/* Opcode: Le P1 P2 P3 P4 P5
66642**
66643** This works just like the Lt opcode except that the jump is taken if
66644** the content of register P3 is less than or equal to the content of
66645** register P1.  See the Lt opcode for additional information.
66646*/
66647/* Opcode: Gt P1 P2 P3 P4 P5
66648**
66649** This works just like the Lt opcode except that the jump is taken if
66650** the content of register P3 is greater than the content of
66651** register P1.  See the Lt opcode for additional information.
66652*/
66653/* Opcode: Ge P1 P2 P3 P4 P5
66654**
66655** This works just like the Lt opcode except that the jump is taken if
66656** the content of register P3 is greater than or equal to the content of
66657** register P1.  See the Lt opcode for additional information.
66658*/
66659case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
66660case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
66661case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
66662case OP_Le:               /* same as TK_LE, jump, in1, in3 */
66663case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
66664case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
66665#if 0  /* local variables moved into u.aj */
66666  int res;            /* Result of the comparison of pIn1 against pIn3 */
66667  char affinity;      /* Affinity to use for comparison */
66668  u16 flags1;         /* Copy of initial value of pIn1->flags */
66669  u16 flags3;         /* Copy of initial value of pIn3->flags */
66670#endif /* local variables moved into u.aj */
66671
66672  pIn1 = &aMem[pOp->p1];
66673  pIn3 = &aMem[pOp->p3];
66674  u.aj.flags1 = pIn1->flags;
66675  u.aj.flags3 = pIn3->flags;
66676  if( (u.aj.flags1 | u.aj.flags3)&MEM_Null ){
66677    /* One or both operands are NULL */
66678    if( pOp->p5 & SQLITE_NULLEQ ){
66679      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
66680      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
66681      ** or not both operands are null.
66682      */
66683      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
66684      u.aj.res = (u.aj.flags1 & u.aj.flags3 & MEM_Null)==0;
66685    }else{
66686      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
66687      ** then the result is always NULL.
66688      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
66689      */
66690      if( pOp->p5 & SQLITE_STOREP2 ){
66691        pOut = &aMem[pOp->p2];
66692        MemSetTypeFlag(pOut, MEM_Null);
66693        REGISTER_TRACE(pOp->p2, pOut);
66694      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
66695        pc = pOp->p2-1;
66696      }
66697      break;
66698    }
66699  }else{
66700    /* Neither operand is NULL.  Do a comparison. */
66701    u.aj.affinity = pOp->p5 & SQLITE_AFF_MASK;
66702    if( u.aj.affinity ){
66703      applyAffinity(pIn1, u.aj.affinity, encoding);
66704      applyAffinity(pIn3, u.aj.affinity, encoding);
66705      if( db->mallocFailed ) goto no_mem;
66706    }
66707
66708    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
66709    ExpandBlob(pIn1);
66710    ExpandBlob(pIn3);
66711    u.aj.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
66712  }
66713  switch( pOp->opcode ){
66714    case OP_Eq:    u.aj.res = u.aj.res==0;     break;
66715    case OP_Ne:    u.aj.res = u.aj.res!=0;     break;
66716    case OP_Lt:    u.aj.res = u.aj.res<0;      break;
66717    case OP_Le:    u.aj.res = u.aj.res<=0;     break;
66718    case OP_Gt:    u.aj.res = u.aj.res>0;      break;
66719    default:       u.aj.res = u.aj.res>=0;     break;
66720  }
66721
66722  if( pOp->p5 & SQLITE_STOREP2 ){
66723    pOut = &aMem[pOp->p2];
66724    memAboutToChange(p, pOut);
66725    MemSetTypeFlag(pOut, MEM_Int);
66726    pOut->u.i = u.aj.res;
66727    REGISTER_TRACE(pOp->p2, pOut);
66728  }else if( u.aj.res ){
66729    pc = pOp->p2-1;
66730  }
66731
66732  /* Undo any changes made by applyAffinity() to the input registers. */
66733  pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.aj.flags1&MEM_TypeMask);
66734  pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.aj.flags3&MEM_TypeMask);
66735  break;
66736}
66737
66738/* Opcode: Permutation * * * P4 *
66739**
66740** Set the permutation used by the OP_Compare operator to be the array
66741** of integers in P4.
66742**
66743** The permutation is only valid until the next OP_Permutation, OP_Compare,
66744** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
66745** immediately prior to the OP_Compare.
66746*/
66747case OP_Permutation: {
66748  assert( pOp->p4type==P4_INTARRAY );
66749  assert( pOp->p4.ai );
66750  aPermute = pOp->p4.ai;
66751  break;
66752}
66753
66754/* Opcode: Compare P1 P2 P3 P4 *
66755**
66756** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
66757** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
66758** the comparison for use by the next OP_Jump instruct.
66759**
66760** P4 is a KeyInfo structure that defines collating sequences and sort
66761** orders for the comparison.  The permutation applies to registers
66762** only.  The KeyInfo elements are used sequentially.
66763**
66764** The comparison is a sort comparison, so NULLs compare equal,
66765** NULLs are less than numbers, numbers are less than strings,
66766** and strings are less than blobs.
66767*/
66768case OP_Compare: {
66769#if 0  /* local variables moved into u.ak */
66770  int n;
66771  int i;
66772  int p1;
66773  int p2;
66774  const KeyInfo *pKeyInfo;
66775  int idx;
66776  CollSeq *pColl;    /* Collating sequence to use on this term */
66777  int bRev;          /* True for DESCENDING sort order */
66778#endif /* local variables moved into u.ak */
66779
66780  u.ak.n = pOp->p3;
66781  u.ak.pKeyInfo = pOp->p4.pKeyInfo;
66782  assert( u.ak.n>0 );
66783  assert( u.ak.pKeyInfo!=0 );
66784  u.ak.p1 = pOp->p1;
66785  u.ak.p2 = pOp->p2;
66786#if SQLITE_DEBUG
66787  if( aPermute ){
66788    int k, mx = 0;
66789    for(k=0; k<u.ak.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
66790    assert( u.ak.p1>0 && u.ak.p1+mx<=p->nMem+1 );
66791    assert( u.ak.p2>0 && u.ak.p2+mx<=p->nMem+1 );
66792  }else{
66793    assert( u.ak.p1>0 && u.ak.p1+u.ak.n<=p->nMem+1 );
66794    assert( u.ak.p2>0 && u.ak.p2+u.ak.n<=p->nMem+1 );
66795  }
66796#endif /* SQLITE_DEBUG */
66797  for(u.ak.i=0; u.ak.i<u.ak.n; u.ak.i++){
66798    u.ak.idx = aPermute ? aPermute[u.ak.i] : u.ak.i;
66799    assert( memIsValid(&aMem[u.ak.p1+u.ak.idx]) );
66800    assert( memIsValid(&aMem[u.ak.p2+u.ak.idx]) );
66801    REGISTER_TRACE(u.ak.p1+u.ak.idx, &aMem[u.ak.p1+u.ak.idx]);
66802    REGISTER_TRACE(u.ak.p2+u.ak.idx, &aMem[u.ak.p2+u.ak.idx]);
66803    assert( u.ak.i<u.ak.pKeyInfo->nField );
66804    u.ak.pColl = u.ak.pKeyInfo->aColl[u.ak.i];
66805    u.ak.bRev = u.ak.pKeyInfo->aSortOrder[u.ak.i];
66806    iCompare = sqlite3MemCompare(&aMem[u.ak.p1+u.ak.idx], &aMem[u.ak.p2+u.ak.idx], u.ak.pColl);
66807    if( iCompare ){
66808      if( u.ak.bRev ) iCompare = -iCompare;
66809      break;
66810    }
66811  }
66812  aPermute = 0;
66813  break;
66814}
66815
66816/* Opcode: Jump P1 P2 P3 * *
66817**
66818** Jump to the instruction at address P1, P2, or P3 depending on whether
66819** in the most recent OP_Compare instruction the P1 vector was less than
66820** equal to, or greater than the P2 vector, respectively.
66821*/
66822case OP_Jump: {             /* jump */
66823  if( iCompare<0 ){
66824    pc = pOp->p1 - 1;
66825  }else if( iCompare==0 ){
66826    pc = pOp->p2 - 1;
66827  }else{
66828    pc = pOp->p3 - 1;
66829  }
66830  break;
66831}
66832
66833/* Opcode: And P1 P2 P3 * *
66834**
66835** Take the logical AND of the values in registers P1 and P2 and
66836** write the result into register P3.
66837**
66838** If either P1 or P2 is 0 (false) then the result is 0 even if
66839** the other input is NULL.  A NULL and true or two NULLs give
66840** a NULL output.
66841*/
66842/* Opcode: Or P1 P2 P3 * *
66843**
66844** Take the logical OR of the values in register P1 and P2 and
66845** store the answer in register P3.
66846**
66847** If either P1 or P2 is nonzero (true) then the result is 1 (true)
66848** even if the other input is NULL.  A NULL and false or two NULLs
66849** give a NULL output.
66850*/
66851case OP_And:              /* same as TK_AND, in1, in2, out3 */
66852case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
66853#if 0  /* local variables moved into u.al */
66854  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66855  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66856#endif /* local variables moved into u.al */
66857
66858  pIn1 = &aMem[pOp->p1];
66859  if( pIn1->flags & MEM_Null ){
66860    u.al.v1 = 2;
66861  }else{
66862    u.al.v1 = sqlite3VdbeIntValue(pIn1)!=0;
66863  }
66864  pIn2 = &aMem[pOp->p2];
66865  if( pIn2->flags & MEM_Null ){
66866    u.al.v2 = 2;
66867  }else{
66868    u.al.v2 = sqlite3VdbeIntValue(pIn2)!=0;
66869  }
66870  if( pOp->opcode==OP_And ){
66871    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
66872    u.al.v1 = and_logic[u.al.v1*3+u.al.v2];
66873  }else{
66874    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
66875    u.al.v1 = or_logic[u.al.v1*3+u.al.v2];
66876  }
66877  pOut = &aMem[pOp->p3];
66878  if( u.al.v1==2 ){
66879    MemSetTypeFlag(pOut, MEM_Null);
66880  }else{
66881    pOut->u.i = u.al.v1;
66882    MemSetTypeFlag(pOut, MEM_Int);
66883  }
66884  break;
66885}
66886
66887/* Opcode: Not P1 P2 * * *
66888**
66889** Interpret the value in register P1 as a boolean value.  Store the
66890** boolean complement in register P2.  If the value in register P1 is
66891** NULL, then a NULL is stored in P2.
66892*/
66893case OP_Not: {                /* same as TK_NOT, in1, out2 */
66894  pIn1 = &aMem[pOp->p1];
66895  pOut = &aMem[pOp->p2];
66896  if( pIn1->flags & MEM_Null ){
66897    sqlite3VdbeMemSetNull(pOut);
66898  }else{
66899    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
66900  }
66901  break;
66902}
66903
66904/* Opcode: BitNot P1 P2 * * *
66905**
66906** Interpret the content of register P1 as an integer.  Store the
66907** ones-complement of the P1 value into register P2.  If P1 holds
66908** a NULL then store a NULL in P2.
66909*/
66910case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
66911  pIn1 = &aMem[pOp->p1];
66912  pOut = &aMem[pOp->p2];
66913  if( pIn1->flags & MEM_Null ){
66914    sqlite3VdbeMemSetNull(pOut);
66915  }else{
66916    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
66917  }
66918  break;
66919}
66920
66921/* Opcode: Once P1 P2 * * *
66922**
66923** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
66924** set the flag and fall through to the next instruction.
66925**
66926** See also: JumpOnce
66927*/
66928case OP_Once: {             /* jump */
66929  assert( pOp->p1<p->nOnceFlag );
66930  if( p->aOnceFlag[pOp->p1] ){
66931    pc = pOp->p2-1;
66932  }else{
66933    p->aOnceFlag[pOp->p1] = 1;
66934  }
66935  break;
66936}
66937
66938/* Opcode: If P1 P2 P3 * *
66939**
66940** Jump to P2 if the value in register P1 is true.  The value
66941** is considered true if it is numeric and non-zero.  If the value
66942** in P1 is NULL then take the jump if P3 is non-zero.
66943*/
66944/* Opcode: IfNot P1 P2 P3 * *
66945**
66946** Jump to P2 if the value in register P1 is False.  The value
66947** is considered false if it has a numeric value of zero.  If the value
66948** in P1 is NULL then take the jump if P3 is zero.
66949*/
66950case OP_If:                 /* jump, in1 */
66951case OP_IfNot: {            /* jump, in1 */
66952#if 0  /* local variables moved into u.am */
66953  int c;
66954#endif /* local variables moved into u.am */
66955  pIn1 = &aMem[pOp->p1];
66956  if( pIn1->flags & MEM_Null ){
66957    u.am.c = pOp->p3;
66958  }else{
66959#ifdef SQLITE_OMIT_FLOATING_POINT
66960    u.am.c = sqlite3VdbeIntValue(pIn1)!=0;
66961#else
66962    u.am.c = sqlite3VdbeRealValue(pIn1)!=0.0;
66963#endif
66964    if( pOp->opcode==OP_IfNot ) u.am.c = !u.am.c;
66965  }
66966  if( u.am.c ){
66967    pc = pOp->p2-1;
66968  }
66969  break;
66970}
66971
66972/* Opcode: IsNull P1 P2 * * *
66973**
66974** Jump to P2 if the value in register P1 is NULL.
66975*/
66976case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
66977  pIn1 = &aMem[pOp->p1];
66978  if( (pIn1->flags & MEM_Null)!=0 ){
66979    pc = pOp->p2 - 1;
66980  }
66981  break;
66982}
66983
66984/* Opcode: NotNull P1 P2 * * *
66985**
66986** Jump to P2 if the value in register P1 is not NULL.
66987*/
66988case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
66989  pIn1 = &aMem[pOp->p1];
66990  if( (pIn1->flags & MEM_Null)==0 ){
66991    pc = pOp->p2 - 1;
66992  }
66993  break;
66994}
66995
66996/* Opcode: Column P1 P2 P3 P4 P5
66997**
66998** Interpret the data that cursor P1 points to as a structure built using
66999** the MakeRecord instruction.  (See the MakeRecord opcode for additional
67000** information about the format of the data.)  Extract the P2-th column
67001** from this record.  If there are less that (P2+1)
67002** values in the record, extract a NULL.
67003**
67004** The value extracted is stored in register P3.
67005**
67006** If the column contains fewer than P2 fields, then extract a NULL.  Or,
67007** if the P4 argument is a P4_MEM use the value of the P4 argument as
67008** the result.
67009**
67010** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
67011** then the cache of the cursor is reset prior to extracting the column.
67012** The first OP_Column against a pseudo-table after the value of the content
67013** register has changed should have this bit set.
67014*/
67015case OP_Column: {
67016#if 0  /* local variables moved into u.an */
67017  u32 payloadSize;   /* Number of bytes in the record */
67018  i64 payloadSize64; /* Number of bytes in the record */
67019  int p1;            /* P1 value of the opcode */
67020  int p2;            /* column number to retrieve */
67021  VdbeCursor *pC;    /* The VDBE cursor */
67022  char *zRec;        /* Pointer to complete record-data */
67023  BtCursor *pCrsr;   /* The BTree cursor */
67024  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
67025  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
67026  int nField;        /* number of fields in the record */
67027  int len;           /* The length of the serialized data for the column */
67028  int i;             /* Loop counter */
67029  char *zData;       /* Part of the record being decoded */
67030  Mem *pDest;        /* Where to write the extracted value */
67031  Mem sMem;          /* For storing the record being decoded */
67032  u8 *zIdx;          /* Index into header */
67033  u8 *zEndHdr;       /* Pointer to first byte after the header */
67034  u32 offset;        /* Offset into the data */
67035  u32 szField;       /* Number of bytes in the content of a field */
67036  int szHdr;         /* Size of the header size field at start of record */
67037  int avail;         /* Number of bytes of available data */
67038  u32 t;             /* A type code from the record header */
67039  Mem *pReg;         /* PseudoTable input register */
67040#endif /* local variables moved into u.an */
67041
67042
67043  u.an.p1 = pOp->p1;
67044  u.an.p2 = pOp->p2;
67045  u.an.pC = 0;
67046  memset(&u.an.sMem, 0, sizeof(u.an.sMem));
67047  assert( u.an.p1<p->nCursor );
67048  assert( pOp->p3>0 && pOp->p3<=p->nMem );
67049  u.an.pDest = &aMem[pOp->p3];
67050  memAboutToChange(p, u.an.pDest);
67051  u.an.zRec = 0;
67052
67053  /* This block sets the variable u.an.payloadSize to be the total number of
67054  ** bytes in the record.
67055  **
67056  ** u.an.zRec is set to be the complete text of the record if it is available.
67057  ** The complete record text is always available for pseudo-tables
67058  ** If the record is stored in a cursor, the complete record text
67059  ** might be available in the  u.an.pC->aRow cache.  Or it might not be.
67060  ** If the data is unavailable,  u.an.zRec is set to NULL.
67061  **
67062  ** We also compute the number of columns in the record.  For cursors,
67063  ** the number of columns is stored in the VdbeCursor.nField element.
67064  */
67065  u.an.pC = p->apCsr[u.an.p1];
67066  assert( u.an.pC!=0 );
67067#ifndef SQLITE_OMIT_VIRTUALTABLE
67068  assert( u.an.pC->pVtabCursor==0 );
67069#endif
67070  u.an.pCrsr = u.an.pC->pCursor;
67071  if( u.an.pCrsr!=0 ){
67072    /* The record is stored in a B-Tree */
67073    rc = sqlite3VdbeCursorMoveto(u.an.pC);
67074    if( rc ) goto abort_due_to_error;
67075    if( u.an.pC->nullRow ){
67076      u.an.payloadSize = 0;
67077    }else if( u.an.pC->cacheStatus==p->cacheCtr ){
67078      u.an.payloadSize = u.an.pC->payloadSize;
67079      u.an.zRec = (char*)u.an.pC->aRow;
67080    }else if( u.an.pC->isIndex ){
67081      assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
67082      VVA_ONLY(rc =) sqlite3BtreeKeySize(u.an.pCrsr, &u.an.payloadSize64);
67083      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
67084      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
67085      ** payload size, so it is impossible for u.an.payloadSize64 to be
67086      ** larger than 32 bits. */
67087      assert( (u.an.payloadSize64 & SQLITE_MAX_U32)==(u64)u.an.payloadSize64 );
67088      u.an.payloadSize = (u32)u.an.payloadSize64;
67089    }else{
67090      assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
67091      VVA_ONLY(rc =) sqlite3BtreeDataSize(u.an.pCrsr, &u.an.payloadSize);
67092      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
67093    }
67094  }else if( ALWAYS(u.an.pC->pseudoTableReg>0) ){
67095    u.an.pReg = &aMem[u.an.pC->pseudoTableReg];
67096    assert( u.an.pReg->flags & MEM_Blob );
67097    assert( memIsValid(u.an.pReg) );
67098    u.an.payloadSize = u.an.pReg->n;
67099    u.an.zRec = u.an.pReg->z;
67100    u.an.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
67101    assert( u.an.payloadSize==0 || u.an.zRec!=0 );
67102  }else{
67103    /* Consider the row to be NULL */
67104    u.an.payloadSize = 0;
67105  }
67106
67107  /* If u.an.payloadSize is 0, then just store a NULL.  This can happen because of
67108  ** nullRow or because of a corrupt database. */
67109  if( u.an.payloadSize==0 ){
67110    MemSetTypeFlag(u.an.pDest, MEM_Null);
67111    goto op_column_out;
67112  }
67113  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
67114  if( u.an.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
67115    goto too_big;
67116  }
67117
67118  u.an.nField = u.an.pC->nField;
67119  assert( u.an.p2<u.an.nField );
67120
67121  /* Read and parse the table header.  Store the results of the parse
67122  ** into the record header cache fields of the cursor.
67123  */
67124  u.an.aType = u.an.pC->aType;
67125  if( u.an.pC->cacheStatus==p->cacheCtr ){
67126    u.an.aOffset = u.an.pC->aOffset;
67127  }else{
67128    assert(u.an.aType);
67129    u.an.avail = 0;
67130    u.an.pC->aOffset = u.an.aOffset = &u.an.aType[u.an.nField];
67131    u.an.pC->payloadSize = u.an.payloadSize;
67132    u.an.pC->cacheStatus = p->cacheCtr;
67133
67134    /* Figure out how many bytes are in the header */
67135    if( u.an.zRec ){
67136      u.an.zData = u.an.zRec;
67137    }else{
67138      if( u.an.pC->isIndex ){
67139        u.an.zData = (char*)sqlite3BtreeKeyFetch(u.an.pCrsr, &u.an.avail);
67140      }else{
67141        u.an.zData = (char*)sqlite3BtreeDataFetch(u.an.pCrsr, &u.an.avail);
67142      }
67143      /* If KeyFetch()/DataFetch() managed to get the entire payload,
67144      ** save the payload in the u.an.pC->aRow cache.  That will save us from
67145      ** having to make additional calls to fetch the content portion of
67146      ** the record.
67147      */
67148      assert( u.an.avail>=0 );
67149      if( u.an.payloadSize <= (u32)u.an.avail ){
67150        u.an.zRec = u.an.zData;
67151        u.an.pC->aRow = (u8*)u.an.zData;
67152      }else{
67153        u.an.pC->aRow = 0;
67154      }
67155    }
67156    /* The following assert is true in all cases accept when
67157    ** the database file has been corrupted externally.
67158    **    assert( u.an.zRec!=0 || u.an.avail>=u.an.payloadSize || u.an.avail>=9 ); */
67159    u.an.szHdr = getVarint32((u8*)u.an.zData, u.an.offset);
67160
67161    /* Make sure a corrupt database has not given us an oversize header.
67162    ** Do this now to avoid an oversize memory allocation.
67163    **
67164    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
67165    ** types use so much data space that there can only be 4096 and 32 of
67166    ** them, respectively.  So the maximum header length results from a
67167    ** 3-byte type for each of the maximum of 32768 columns plus three
67168    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
67169    */
67170    if( u.an.offset > 98307 ){
67171      rc = SQLITE_CORRUPT_BKPT;
67172      goto op_column_out;
67173    }
67174
67175    /* Compute in u.an.len the number of bytes of data we need to read in order
67176    ** to get u.an.nField type values.  u.an.offset is an upper bound on this.  But
67177    ** u.an.nField might be significantly less than the true number of columns
67178    ** in the table, and in that case, 5*u.an.nField+3 might be smaller than u.an.offset.
67179    ** We want to minimize u.an.len in order to limit the size of the memory
67180    ** allocation, especially if a corrupt database file has caused u.an.offset
67181    ** to be oversized. Offset is limited to 98307 above.  But 98307 might
67182    ** still exceed Robson memory allocation limits on some configurations.
67183    ** On systems that cannot tolerate large memory allocations, u.an.nField*5+3
67184    ** will likely be much smaller since u.an.nField will likely be less than
67185    ** 20 or so.  This insures that Robson memory allocation limits are
67186    ** not exceeded even for corrupt database files.
67187    */
67188    u.an.len = u.an.nField*5 + 3;
67189    if( u.an.len > (int)u.an.offset ) u.an.len = (int)u.an.offset;
67190
67191    /* The KeyFetch() or DataFetch() above are fast and will get the entire
67192    ** record header in most cases.  But they will fail to get the complete
67193    ** record header if the record header does not fit on a single page
67194    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
67195    ** acquire the complete header text.
67196    */
67197    if( !u.an.zRec && u.an.avail<u.an.len ){
67198      u.an.sMem.flags = 0;
67199      u.an.sMem.db = 0;
67200      rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, 0, u.an.len, u.an.pC->isIndex, &u.an.sMem);
67201      if( rc!=SQLITE_OK ){
67202        goto op_column_out;
67203      }
67204      u.an.zData = u.an.sMem.z;
67205    }
67206    u.an.zEndHdr = (u8 *)&u.an.zData[u.an.len];
67207    u.an.zIdx = (u8 *)&u.an.zData[u.an.szHdr];
67208
67209    /* Scan the header and use it to fill in the u.an.aType[] and u.an.aOffset[]
67210    ** arrays.  u.an.aType[u.an.i] will contain the type integer for the u.an.i-th
67211    ** column and u.an.aOffset[u.an.i] will contain the u.an.offset from the beginning
67212    ** of the record to the start of the data for the u.an.i-th column
67213    */
67214    for(u.an.i=0; u.an.i<u.an.nField; u.an.i++){
67215      if( u.an.zIdx<u.an.zEndHdr ){
67216        u.an.aOffset[u.an.i] = u.an.offset;
67217        if( u.an.zIdx[0]<0x80 ){
67218          u.an.t = u.an.zIdx[0];
67219          u.an.zIdx++;
67220        }else{
67221          u.an.zIdx += sqlite3GetVarint32(u.an.zIdx, &u.an.t);
67222        }
67223        u.an.aType[u.an.i] = u.an.t;
67224        u.an.szField = sqlite3VdbeSerialTypeLen(u.an.t);
67225        u.an.offset += u.an.szField;
67226        if( u.an.offset<u.an.szField ){  /* True if u.an.offset overflows */
67227          u.an.zIdx = &u.an.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
67228          break;
67229        }
67230      }else{
67231        /* If u.an.i is less that u.an.nField, then there are less fields in this
67232        ** record than SetNumColumns indicated there are columns in the
67233        ** table. Set the u.an.offset for any extra columns not present in
67234        ** the record to 0. This tells code below to store a NULL
67235        ** instead of deserializing a value from the record.
67236        */
67237        u.an.aOffset[u.an.i] = 0;
67238      }
67239    }
67240    sqlite3VdbeMemRelease(&u.an.sMem);
67241    u.an.sMem.flags = MEM_Null;
67242
67243    /* If we have read more header data than was contained in the header,
67244    ** or if the end of the last field appears to be past the end of the
67245    ** record, or if the end of the last field appears to be before the end
67246    ** of the record (when all fields present), then we must be dealing
67247    ** with a corrupt database.
67248    */
67249    if( (u.an.zIdx > u.an.zEndHdr) || (u.an.offset > u.an.payloadSize)
67250         || (u.an.zIdx==u.an.zEndHdr && u.an.offset!=u.an.payloadSize) ){
67251      rc = SQLITE_CORRUPT_BKPT;
67252      goto op_column_out;
67253    }
67254  }
67255
67256  /* Get the column information. If u.an.aOffset[u.an.p2] is non-zero, then
67257  ** deserialize the value from the record. If u.an.aOffset[u.an.p2] is zero,
67258  ** then there are not enough fields in the record to satisfy the
67259  ** request.  In this case, set the value NULL or to P4 if P4 is
67260  ** a pointer to a Mem object.
67261  */
67262  if( u.an.aOffset[u.an.p2] ){
67263    assert( rc==SQLITE_OK );
67264    if( u.an.zRec ){
67265      VdbeMemRelease(u.an.pDest);
67266      sqlite3VdbeSerialGet((u8 *)&u.an.zRec[u.an.aOffset[u.an.p2]], u.an.aType[u.an.p2], u.an.pDest);
67267    }else{
67268      u.an.len = sqlite3VdbeSerialTypeLen(u.an.aType[u.an.p2]);
67269      sqlite3VdbeMemMove(&u.an.sMem, u.an.pDest);
67270      rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, u.an.aOffset[u.an.p2], u.an.len, u.an.pC->isIndex, &u.an.sMem);
67271      if( rc!=SQLITE_OK ){
67272        goto op_column_out;
67273      }
67274      u.an.zData = u.an.sMem.z;
67275      sqlite3VdbeSerialGet((u8*)u.an.zData, u.an.aType[u.an.p2], u.an.pDest);
67276    }
67277    u.an.pDest->enc = encoding;
67278  }else{
67279    if( pOp->p4type==P4_MEM ){
67280      sqlite3VdbeMemShallowCopy(u.an.pDest, pOp->p4.pMem, MEM_Static);
67281    }else{
67282      MemSetTypeFlag(u.an.pDest, MEM_Null);
67283    }
67284  }
67285
67286  /* If we dynamically allocated space to hold the data (in the
67287  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
67288  ** dynamically allocated space over to the u.an.pDest structure.
67289  ** This prevents a memory copy.
67290  */
67291  if( u.an.sMem.zMalloc ){
67292    assert( u.an.sMem.z==u.an.sMem.zMalloc );
67293    assert( !(u.an.pDest->flags & MEM_Dyn) );
67294    assert( !(u.an.pDest->flags & (MEM_Blob|MEM_Str)) || u.an.pDest->z==u.an.sMem.z );
67295    u.an.pDest->flags &= ~(MEM_Ephem|MEM_Static);
67296    u.an.pDest->flags |= MEM_Term;
67297    u.an.pDest->z = u.an.sMem.z;
67298    u.an.pDest->zMalloc = u.an.sMem.zMalloc;
67299  }
67300
67301  rc = sqlite3VdbeMemMakeWriteable(u.an.pDest);
67302
67303op_column_out:
67304  UPDATE_MAX_BLOBSIZE(u.an.pDest);
67305  REGISTER_TRACE(pOp->p3, u.an.pDest);
67306  break;
67307}
67308
67309/* Opcode: Affinity P1 P2 * P4 *
67310**
67311** Apply affinities to a range of P2 registers starting with P1.
67312**
67313** P4 is a string that is P2 characters long. The nth character of the
67314** string indicates the column affinity that should be used for the nth
67315** memory cell in the range.
67316*/
67317case OP_Affinity: {
67318#if 0  /* local variables moved into u.ao */
67319  const char *zAffinity;   /* The affinity to be applied */
67320  char cAff;               /* A single character of affinity */
67321#endif /* local variables moved into u.ao */
67322
67323  u.ao.zAffinity = pOp->p4.z;
67324  assert( u.ao.zAffinity!=0 );
67325  assert( u.ao.zAffinity[pOp->p2]==0 );
67326  pIn1 = &aMem[pOp->p1];
67327  while( (u.ao.cAff = *(u.ao.zAffinity++))!=0 ){
67328    assert( pIn1 <= &p->aMem[p->nMem] );
67329    assert( memIsValid(pIn1) );
67330    ExpandBlob(pIn1);
67331    applyAffinity(pIn1, u.ao.cAff, encoding);
67332    pIn1++;
67333  }
67334  break;
67335}
67336
67337/* Opcode: MakeRecord P1 P2 P3 P4 *
67338**
67339** Convert P2 registers beginning with P1 into the [record format]
67340** use as a data record in a database table or as a key
67341** in an index.  The OP_Column opcode can decode the record later.
67342**
67343** P4 may be a string that is P2 characters long.  The nth character of the
67344** string indicates the column affinity that should be used for the nth
67345** field of the index key.
67346**
67347** The mapping from character to affinity is given by the SQLITE_AFF_
67348** macros defined in sqliteInt.h.
67349**
67350** If P4 is NULL then all index fields have the affinity NONE.
67351*/
67352case OP_MakeRecord: {
67353#if 0  /* local variables moved into u.ap */
67354  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
67355  Mem *pRec;             /* The new record */
67356  u64 nData;             /* Number of bytes of data space */
67357  int nHdr;              /* Number of bytes of header space */
67358  i64 nByte;             /* Data space required for this record */
67359  int nZero;             /* Number of zero bytes at the end of the record */
67360  int nVarint;           /* Number of bytes in a varint */
67361  u32 serial_type;       /* Type field */
67362  Mem *pData0;           /* First field to be combined into the record */
67363  Mem *pLast;            /* Last field of the record */
67364  int nField;            /* Number of fields in the record */
67365  char *zAffinity;       /* The affinity string for the record */
67366  int file_format;       /* File format to use for encoding */
67367  int i;                 /* Space used in zNewRecord[] */
67368  int len;               /* Length of a field */
67369#endif /* local variables moved into u.ap */
67370
67371  /* Assuming the record contains N fields, the record format looks
67372  ** like this:
67373  **
67374  ** ------------------------------------------------------------------------
67375  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
67376  ** ------------------------------------------------------------------------
67377  **
67378  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
67379  ** and so froth.
67380  **
67381  ** Each type field is a varint representing the serial type of the
67382  ** corresponding data element (see sqlite3VdbeSerialType()). The
67383  ** hdr-size field is also a varint which is the offset from the beginning
67384  ** of the record to data0.
67385  */
67386  u.ap.nData = 0;         /* Number of bytes of data space */
67387  u.ap.nHdr = 0;          /* Number of bytes of header space */
67388  u.ap.nZero = 0;         /* Number of zero bytes at the end of the record */
67389  u.ap.nField = pOp->p1;
67390  u.ap.zAffinity = pOp->p4.z;
67391  assert( u.ap.nField>0 && pOp->p2>0 && pOp->p2+u.ap.nField<=p->nMem+1 );
67392  u.ap.pData0 = &aMem[u.ap.nField];
67393  u.ap.nField = pOp->p2;
67394  u.ap.pLast = &u.ap.pData0[u.ap.nField-1];
67395  u.ap.file_format = p->minWriteFileFormat;
67396
67397  /* Identify the output register */
67398  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
67399  pOut = &aMem[pOp->p3];
67400  memAboutToChange(p, pOut);
67401
67402  /* Loop through the elements that will make up the record to figure
67403  ** out how much space is required for the new record.
67404  */
67405  for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
67406    assert( memIsValid(u.ap.pRec) );
67407    if( u.ap.zAffinity ){
67408      applyAffinity(u.ap.pRec, u.ap.zAffinity[u.ap.pRec-u.ap.pData0], encoding);
67409    }
67410    if( u.ap.pRec->flags&MEM_Zero && u.ap.pRec->n>0 ){
67411      sqlite3VdbeMemExpandBlob(u.ap.pRec);
67412    }
67413    u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
67414    u.ap.len = sqlite3VdbeSerialTypeLen(u.ap.serial_type);
67415    u.ap.nData += u.ap.len;
67416    u.ap.nHdr += sqlite3VarintLen(u.ap.serial_type);
67417    if( u.ap.pRec->flags & MEM_Zero ){
67418      /* Only pure zero-filled BLOBs can be input to this Opcode.
67419      ** We do not allow blobs with a prefix and a zero-filled tail. */
67420      u.ap.nZero += u.ap.pRec->u.nZero;
67421    }else if( u.ap.len ){
67422      u.ap.nZero = 0;
67423    }
67424  }
67425
67426  /* Add the initial header varint and total the size */
67427  u.ap.nHdr += u.ap.nVarint = sqlite3VarintLen(u.ap.nHdr);
67428  if( u.ap.nVarint<sqlite3VarintLen(u.ap.nHdr) ){
67429    u.ap.nHdr++;
67430  }
67431  u.ap.nByte = u.ap.nHdr+u.ap.nData-u.ap.nZero;
67432  if( u.ap.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
67433    goto too_big;
67434  }
67435
67436  /* Make sure the output register has a buffer large enough to store
67437  ** the new record. The output register (pOp->p3) is not allowed to
67438  ** be one of the input registers (because the following call to
67439  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
67440  */
67441  if( sqlite3VdbeMemGrow(pOut, (int)u.ap.nByte, 0) ){
67442    goto no_mem;
67443  }
67444  u.ap.zNewRecord = (u8 *)pOut->z;
67445
67446  /* Write the record */
67447  u.ap.i = putVarint32(u.ap.zNewRecord, u.ap.nHdr);
67448  for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
67449    u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
67450    u.ap.i += putVarint32(&u.ap.zNewRecord[u.ap.i], u.ap.serial_type);      /* serial type */
67451  }
67452  for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){  /* serial data */
67453    u.ap.i += sqlite3VdbeSerialPut(&u.ap.zNewRecord[u.ap.i], (int)(u.ap.nByte-u.ap.i), u.ap.pRec,u.ap.file_format);
67454  }
67455  assert( u.ap.i==u.ap.nByte );
67456
67457  assert( pOp->p3>0 && pOp->p3<=p->nMem );
67458  pOut->n = (int)u.ap.nByte;
67459  pOut->flags = MEM_Blob | MEM_Dyn;
67460  pOut->xDel = 0;
67461  if( u.ap.nZero ){
67462    pOut->u.nZero = u.ap.nZero;
67463    pOut->flags |= MEM_Zero;
67464  }
67465  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
67466  REGISTER_TRACE(pOp->p3, pOut);
67467  UPDATE_MAX_BLOBSIZE(pOut);
67468  break;
67469}
67470
67471/* Opcode: Count P1 P2 * * *
67472**
67473** Store the number of entries (an integer value) in the table or index
67474** opened by cursor P1 in register P2
67475*/
67476#ifndef SQLITE_OMIT_BTREECOUNT
67477case OP_Count: {         /* out2-prerelease */
67478#if 0  /* local variables moved into u.aq */
67479  i64 nEntry;
67480  BtCursor *pCrsr;
67481#endif /* local variables moved into u.aq */
67482
67483  u.aq.pCrsr = p->apCsr[pOp->p1]->pCursor;
67484  if( ALWAYS(u.aq.pCrsr) ){
67485    rc = sqlite3BtreeCount(u.aq.pCrsr, &u.aq.nEntry);
67486  }else{
67487    u.aq.nEntry = 0;
67488  }
67489  pOut->u.i = u.aq.nEntry;
67490  break;
67491}
67492#endif
67493
67494/* Opcode: Savepoint P1 * * P4 *
67495**
67496** Open, release or rollback the savepoint named by parameter P4, depending
67497** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
67498** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
67499*/
67500case OP_Savepoint: {
67501#if 0  /* local variables moved into u.ar */
67502  int p1;                         /* Value of P1 operand */
67503  char *zName;                    /* Name of savepoint */
67504  int nName;
67505  Savepoint *pNew;
67506  Savepoint *pSavepoint;
67507  Savepoint *pTmp;
67508  int iSavepoint;
67509  int ii;
67510#endif /* local variables moved into u.ar */
67511
67512  u.ar.p1 = pOp->p1;
67513  u.ar.zName = pOp->p4.z;
67514
67515  /* Assert that the u.ar.p1 parameter is valid. Also that if there is no open
67516  ** transaction, then there cannot be any savepoints.
67517  */
67518  assert( db->pSavepoint==0 || db->autoCommit==0 );
67519  assert( u.ar.p1==SAVEPOINT_BEGIN||u.ar.p1==SAVEPOINT_RELEASE||u.ar.p1==SAVEPOINT_ROLLBACK );
67520  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
67521  assert( checkSavepointCount(db) );
67522
67523  if( u.ar.p1==SAVEPOINT_BEGIN ){
67524    if( db->writeVdbeCnt>0 ){
67525      /* A new savepoint cannot be created if there are active write
67526      ** statements (i.e. open read/write incremental blob handles).
67527      */
67528      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
67529        "SQL statements in progress");
67530      rc = SQLITE_BUSY;
67531    }else{
67532      u.ar.nName = sqlite3Strlen30(u.ar.zName);
67533
67534#ifndef SQLITE_OMIT_VIRTUALTABLE
67535      /* This call is Ok even if this savepoint is actually a transaction
67536      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
67537      ** If this is a transaction savepoint being opened, it is guaranteed
67538      ** that the db->aVTrans[] array is empty.  */
67539      assert( db->autoCommit==0 || db->nVTrans==0 );
67540      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
67541                                db->nStatement+db->nSavepoint);
67542      if( rc!=SQLITE_OK ) goto abort_due_to_error;
67543#endif
67544
67545      /* Create a new savepoint structure. */
67546      u.ar.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.ar.nName+1);
67547      if( u.ar.pNew ){
67548        u.ar.pNew->zName = (char *)&u.ar.pNew[1];
67549        memcpy(u.ar.pNew->zName, u.ar.zName, u.ar.nName+1);
67550
67551        /* If there is no open transaction, then mark this as a special
67552        ** "transaction savepoint". */
67553        if( db->autoCommit ){
67554          db->autoCommit = 0;
67555          db->isTransactionSavepoint = 1;
67556        }else{
67557          db->nSavepoint++;
67558        }
67559
67560        /* Link the new savepoint into the database handle's list. */
67561        u.ar.pNew->pNext = db->pSavepoint;
67562        db->pSavepoint = u.ar.pNew;
67563        u.ar.pNew->nDeferredCons = db->nDeferredCons;
67564      }
67565    }
67566  }else{
67567    u.ar.iSavepoint = 0;
67568
67569    /* Find the named savepoint. If there is no such savepoint, then an
67570    ** an error is returned to the user.  */
67571    for(
67572      u.ar.pSavepoint = db->pSavepoint;
67573      u.ar.pSavepoint && sqlite3StrICmp(u.ar.pSavepoint->zName, u.ar.zName);
67574      u.ar.pSavepoint = u.ar.pSavepoint->pNext
67575    ){
67576      u.ar.iSavepoint++;
67577    }
67578    if( !u.ar.pSavepoint ){
67579      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.ar.zName);
67580      rc = SQLITE_ERROR;
67581    }else if( db->writeVdbeCnt>0 && u.ar.p1==SAVEPOINT_RELEASE ){
67582      /* It is not possible to release (commit) a savepoint if there are
67583      ** active write statements.
67584      */
67585      sqlite3SetString(&p->zErrMsg, db,
67586        "cannot release savepoint - SQL statements in progress"
67587      );
67588      rc = SQLITE_BUSY;
67589    }else{
67590
67591      /* Determine whether or not this is a transaction savepoint. If so,
67592      ** and this is a RELEASE command, then the current transaction
67593      ** is committed.
67594      */
67595      int isTransaction = u.ar.pSavepoint->pNext==0 && db->isTransactionSavepoint;
67596      if( isTransaction && u.ar.p1==SAVEPOINT_RELEASE ){
67597        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
67598          goto vdbe_return;
67599        }
67600        db->autoCommit = 1;
67601        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
67602          p->pc = pc;
67603          db->autoCommit = 0;
67604          p->rc = rc = SQLITE_BUSY;
67605          goto vdbe_return;
67606        }
67607        db->isTransactionSavepoint = 0;
67608        rc = p->rc;
67609      }else{
67610        u.ar.iSavepoint = db->nSavepoint - u.ar.iSavepoint - 1;
67611        for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
67612          sqlite3BtreeTripAllCursors(db->aDb[u.ar.ii].pBt, SQLITE_ABORT);
67613        }
67614        for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
67615          rc = sqlite3BtreeSavepoint(db->aDb[u.ar.ii].pBt, u.ar.p1, u.ar.iSavepoint);
67616          if( rc!=SQLITE_OK ){
67617            goto abort_due_to_error;
67618          }
67619        }
67620        if( u.ar.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
67621          sqlite3ExpirePreparedStatements(db);
67622          sqlite3ResetInternalSchema(db, -1);
67623          db->flags = (db->flags | SQLITE_InternChanges);
67624        }
67625      }
67626
67627      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
67628      ** savepoints nested inside of the savepoint being operated on. */
67629      while( db->pSavepoint!=u.ar.pSavepoint ){
67630        u.ar.pTmp = db->pSavepoint;
67631        db->pSavepoint = u.ar.pTmp->pNext;
67632        sqlite3DbFree(db, u.ar.pTmp);
67633        db->nSavepoint--;
67634      }
67635
67636      /* If it is a RELEASE, then destroy the savepoint being operated on
67637      ** too. If it is a ROLLBACK TO, then set the number of deferred
67638      ** constraint violations present in the database to the value stored
67639      ** when the savepoint was created.  */
67640      if( u.ar.p1==SAVEPOINT_RELEASE ){
67641        assert( u.ar.pSavepoint==db->pSavepoint );
67642        db->pSavepoint = u.ar.pSavepoint->pNext;
67643        sqlite3DbFree(db, u.ar.pSavepoint);
67644        if( !isTransaction ){
67645          db->nSavepoint--;
67646        }
67647      }else{
67648        db->nDeferredCons = u.ar.pSavepoint->nDeferredCons;
67649      }
67650
67651      if( !isTransaction ){
67652        rc = sqlite3VtabSavepoint(db, u.ar.p1, u.ar.iSavepoint);
67653        if( rc!=SQLITE_OK ) goto abort_due_to_error;
67654      }
67655    }
67656  }
67657
67658  break;
67659}
67660
67661/* Opcode: AutoCommit P1 P2 * * *
67662**
67663** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
67664** back any currently active btree transactions. If there are any active
67665** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
67666** there are active writing VMs or active VMs that use shared cache.
67667**
67668** This instruction causes the VM to halt.
67669*/
67670case OP_AutoCommit: {
67671#if 0  /* local variables moved into u.as */
67672  int desiredAutoCommit;
67673  int iRollback;
67674  int turnOnAC;
67675#endif /* local variables moved into u.as */
67676
67677  u.as.desiredAutoCommit = pOp->p1;
67678  u.as.iRollback = pOp->p2;
67679  u.as.turnOnAC = u.as.desiredAutoCommit && !db->autoCommit;
67680  assert( u.as.desiredAutoCommit==1 || u.as.desiredAutoCommit==0 );
67681  assert( u.as.desiredAutoCommit==1 || u.as.iRollback==0 );
67682  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
67683
67684#if 0
67685  if( u.as.turnOnAC && u.as.iRollback && db->activeVdbeCnt>1 ){
67686    /* If this instruction implements a ROLLBACK and other VMs are
67687    ** still running, and a transaction is active, return an error indicating
67688    ** that the other VMs must complete first.
67689    */
67690    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
67691        "SQL statements in progress");
67692    rc = SQLITE_BUSY;
67693  }else
67694#endif
67695  if( u.as.turnOnAC && !u.as.iRollback && db->writeVdbeCnt>0 ){
67696    /* If this instruction implements a COMMIT and other VMs are writing
67697    ** return an error indicating that the other VMs must complete first.
67698    */
67699    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
67700        "SQL statements in progress");
67701    rc = SQLITE_BUSY;
67702  }else if( u.as.desiredAutoCommit!=db->autoCommit ){
67703    if( u.as.iRollback ){
67704      assert( u.as.desiredAutoCommit==1 );
67705      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
67706      db->autoCommit = 1;
67707    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
67708      goto vdbe_return;
67709    }else{
67710      db->autoCommit = (u8)u.as.desiredAutoCommit;
67711      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
67712        p->pc = pc;
67713        db->autoCommit = (u8)(1-u.as.desiredAutoCommit);
67714        p->rc = rc = SQLITE_BUSY;
67715        goto vdbe_return;
67716      }
67717    }
67718    assert( db->nStatement==0 );
67719    sqlite3CloseSavepoints(db);
67720    if( p->rc==SQLITE_OK ){
67721      rc = SQLITE_DONE;
67722    }else{
67723      rc = SQLITE_ERROR;
67724    }
67725    goto vdbe_return;
67726  }else{
67727    sqlite3SetString(&p->zErrMsg, db,
67728        (!u.as.desiredAutoCommit)?"cannot start a transaction within a transaction":(
67729        (u.as.iRollback)?"cannot rollback - no transaction is active":
67730                   "cannot commit - no transaction is active"));
67731
67732    rc = SQLITE_ERROR;
67733  }
67734  break;
67735}
67736
67737/* Opcode: Transaction P1 P2 * * *
67738**
67739** Begin a transaction.  The transaction ends when a Commit or Rollback
67740** opcode is encountered.  Depending on the ON CONFLICT setting, the
67741** transaction might also be rolled back if an error is encountered.
67742**
67743** P1 is the index of the database file on which the transaction is
67744** started.  Index 0 is the main database file and index 1 is the
67745** file used for temporary tables.  Indices of 2 or more are used for
67746** attached databases.
67747**
67748** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
67749** obtained on the database file when a write-transaction is started.  No
67750** other process can start another write transaction while this transaction is
67751** underway.  Starting a write transaction also creates a rollback journal. A
67752** write transaction must be started before any changes can be made to the
67753** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
67754** on the file.
67755**
67756** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
67757** true (this flag is set if the Vdbe may modify more than one row and may
67758** throw an ABORT exception), a statement transaction may also be opened.
67759** More specifically, a statement transaction is opened iff the database
67760** connection is currently not in autocommit mode, or if there are other
67761** active statements. A statement transaction allows the changes made by this
67762** VDBE to be rolled back after an error without having to roll back the
67763** entire transaction. If no error is encountered, the statement transaction
67764** will automatically commit when the VDBE halts.
67765**
67766** If P2 is zero, then a read-lock is obtained on the database file.
67767*/
67768case OP_Transaction: {
67769#if 0  /* local variables moved into u.at */
67770  Btree *pBt;
67771#endif /* local variables moved into u.at */
67772
67773  assert( pOp->p1>=0 && pOp->p1<db->nDb );
67774  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67775  u.at.pBt = db->aDb[pOp->p1].pBt;
67776
67777  if( u.at.pBt ){
67778    rc = sqlite3BtreeBeginTrans(u.at.pBt, pOp->p2);
67779    if( rc==SQLITE_BUSY ){
67780      p->pc = pc;
67781      p->rc = rc = SQLITE_BUSY;
67782      goto vdbe_return;
67783    }
67784    if( rc!=SQLITE_OK ){
67785      goto abort_due_to_error;
67786    }
67787
67788    if( pOp->p2 && p->usesStmtJournal
67789     && (db->autoCommit==0 || db->activeVdbeCnt>1)
67790    ){
67791      assert( sqlite3BtreeIsInTrans(u.at.pBt) );
67792      if( p->iStatement==0 ){
67793        assert( db->nStatement>=0 && db->nSavepoint>=0 );
67794        db->nStatement++;
67795        p->iStatement = db->nSavepoint + db->nStatement;
67796      }
67797
67798      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
67799      if( rc==SQLITE_OK ){
67800        rc = sqlite3BtreeBeginStmt(u.at.pBt, p->iStatement);
67801      }
67802
67803      /* Store the current value of the database handles deferred constraint
67804      ** counter. If the statement transaction needs to be rolled back,
67805      ** the value of this counter needs to be restored too.  */
67806      p->nStmtDefCons = db->nDeferredCons;
67807    }
67808  }
67809  break;
67810}
67811
67812/* Opcode: ReadCookie P1 P2 P3 * *
67813**
67814** Read cookie number P3 from database P1 and write it into register P2.
67815** P3==1 is the schema version.  P3==2 is the database format.
67816** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
67817** the main database file and P1==1 is the database file used to store
67818** temporary tables.
67819**
67820** There must be a read-lock on the database (either a transaction
67821** must be started or there must be an open cursor) before
67822** executing this instruction.
67823*/
67824case OP_ReadCookie: {               /* out2-prerelease */
67825#if 0  /* local variables moved into u.au */
67826  int iMeta;
67827  int iDb;
67828  int iCookie;
67829#endif /* local variables moved into u.au */
67830
67831  u.au.iDb = pOp->p1;
67832  u.au.iCookie = pOp->p3;
67833  assert( pOp->p3<SQLITE_N_BTREE_META );
67834  assert( u.au.iDb>=0 && u.au.iDb<db->nDb );
67835  assert( db->aDb[u.au.iDb].pBt!=0 );
67836  assert( (p->btreeMask & (((yDbMask)1)<<u.au.iDb))!=0 );
67837
67838  sqlite3BtreeGetMeta(db->aDb[u.au.iDb].pBt, u.au.iCookie, (u32 *)&u.au.iMeta);
67839  pOut->u.i = u.au.iMeta;
67840  break;
67841}
67842
67843/* Opcode: SetCookie P1 P2 P3 * *
67844**
67845** Write the content of register P3 (interpreted as an integer)
67846** into cookie number P2 of database P1.  P2==1 is the schema version.
67847** P2==2 is the database format. P2==3 is the recommended pager cache
67848** size, and so forth.  P1==0 is the main database file and P1==1 is the
67849** database file used to store temporary tables.
67850**
67851** A transaction must be started before executing this opcode.
67852*/
67853case OP_SetCookie: {       /* in3 */
67854#if 0  /* local variables moved into u.av */
67855  Db *pDb;
67856#endif /* local variables moved into u.av */
67857  assert( pOp->p2<SQLITE_N_BTREE_META );
67858  assert( pOp->p1>=0 && pOp->p1<db->nDb );
67859  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67860  u.av.pDb = &db->aDb[pOp->p1];
67861  assert( u.av.pDb->pBt!=0 );
67862  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
67863  pIn3 = &aMem[pOp->p3];
67864  sqlite3VdbeMemIntegerify(pIn3);
67865  /* See note about index shifting on OP_ReadCookie */
67866  rc = sqlite3BtreeUpdateMeta(u.av.pDb->pBt, pOp->p2, (int)pIn3->u.i);
67867  if( pOp->p2==BTREE_SCHEMA_VERSION ){
67868    /* When the schema cookie changes, record the new cookie internally */
67869    u.av.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
67870    db->flags |= SQLITE_InternChanges;
67871  }else if( pOp->p2==BTREE_FILE_FORMAT ){
67872    /* Record changes in the file format */
67873    u.av.pDb->pSchema->file_format = (u8)pIn3->u.i;
67874  }
67875  if( pOp->p1==1 ){
67876    /* Invalidate all prepared statements whenever the TEMP database
67877    ** schema is changed.  Ticket #1644 */
67878    sqlite3ExpirePreparedStatements(db);
67879    p->expired = 0;
67880  }
67881  break;
67882}
67883
67884/* Opcode: VerifyCookie P1 P2 P3 * *
67885**
67886** Check the value of global database parameter number 0 (the
67887** schema version) and make sure it is equal to P2 and that the
67888** generation counter on the local schema parse equals P3.
67889**
67890** P1 is the database number which is 0 for the main database file
67891** and 1 for the file holding temporary tables and some higher number
67892** for auxiliary databases.
67893**
67894** The cookie changes its value whenever the database schema changes.
67895** This operation is used to detect when that the cookie has changed
67896** and that the current process needs to reread the schema.
67897**
67898** Either a transaction needs to have been started or an OP_Open needs
67899** to be executed (to establish a read lock) before this opcode is
67900** invoked.
67901*/
67902case OP_VerifyCookie: {
67903#if 0  /* local variables moved into u.aw */
67904  int iMeta;
67905  int iGen;
67906  Btree *pBt;
67907#endif /* local variables moved into u.aw */
67908
67909  assert( pOp->p1>=0 && pOp->p1<db->nDb );
67910  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67911  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
67912  u.aw.pBt = db->aDb[pOp->p1].pBt;
67913  if( u.aw.pBt ){
67914    sqlite3BtreeGetMeta(u.aw.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.aw.iMeta);
67915    u.aw.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
67916  }else{
67917    u.aw.iGen = u.aw.iMeta = 0;
67918  }
67919  if( u.aw.iMeta!=pOp->p2 || u.aw.iGen!=pOp->p3 ){
67920    sqlite3DbFree(db, p->zErrMsg);
67921    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
67922    /* If the schema-cookie from the database file matches the cookie
67923    ** stored with the in-memory representation of the schema, do
67924    ** not reload the schema from the database file.
67925    **
67926    ** If virtual-tables are in use, this is not just an optimization.
67927    ** Often, v-tables store their data in other SQLite tables, which
67928    ** are queried from within xNext() and other v-table methods using
67929    ** prepared queries. If such a query is out-of-date, we do not want to
67930    ** discard the database schema, as the user code implementing the
67931    ** v-table would have to be ready for the sqlite3_vtab structure itself
67932    ** to be invalidated whenever sqlite3_step() is called from within
67933    ** a v-table method.
67934    */
67935    if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.aw.iMeta ){
67936      sqlite3ResetInternalSchema(db, pOp->p1);
67937    }
67938
67939    p->expired = 1;
67940    rc = SQLITE_SCHEMA;
67941  }
67942  break;
67943}
67944
67945/* Opcode: OpenRead P1 P2 P3 P4 P5
67946**
67947** Open a read-only cursor for the database table whose root page is
67948** P2 in a database file.  The database file is determined by P3.
67949** P3==0 means the main database, P3==1 means the database used for
67950** temporary tables, and P3>1 means used the corresponding attached
67951** database.  Give the new cursor an identifier of P1.  The P1
67952** values need not be contiguous but all P1 values should be small integers.
67953** It is an error for P1 to be negative.
67954**
67955** If P5!=0 then use the content of register P2 as the root page, not
67956** the value of P2 itself.
67957**
67958** There will be a read lock on the database whenever there is an
67959** open cursor.  If the database was unlocked prior to this instruction
67960** then a read lock is acquired as part of this instruction.  A read
67961** lock allows other processes to read the database but prohibits
67962** any other process from modifying the database.  The read lock is
67963** released when all cursors are closed.  If this instruction attempts
67964** to get a read lock but fails, the script terminates with an
67965** SQLITE_BUSY error code.
67966**
67967** The P4 value may be either an integer (P4_INT32) or a pointer to
67968** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
67969** structure, then said structure defines the content and collating
67970** sequence of the index being opened. Otherwise, if P4 is an integer
67971** value, it is set to the number of columns in the table.
67972**
67973** See also OpenWrite.
67974*/
67975/* Opcode: OpenWrite P1 P2 P3 P4 P5
67976**
67977** Open a read/write cursor named P1 on the table or index whose root
67978** page is P2.  Or if P5!=0 use the content of register P2 to find the
67979** root page.
67980**
67981** The P4 value may be either an integer (P4_INT32) or a pointer to
67982** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
67983** structure, then said structure defines the content and collating
67984** sequence of the index being opened. Otherwise, if P4 is an integer
67985** value, it is set to the number of columns in the table, or to the
67986** largest index of any column of the table that is actually used.
67987**
67988** This instruction works just like OpenRead except that it opens the cursor
67989** in read/write mode.  For a given table, there can be one or more read-only
67990** cursors or a single read/write cursor but not both.
67991**
67992** See also OpenRead.
67993*/
67994case OP_OpenRead:
67995case OP_OpenWrite: {
67996#if 0  /* local variables moved into u.ax */
67997  int nField;
67998  KeyInfo *pKeyInfo;
67999  int p2;
68000  int iDb;
68001  int wrFlag;
68002  Btree *pX;
68003  VdbeCursor *pCur;
68004  Db *pDb;
68005#endif /* local variables moved into u.ax */
68006
68007  if( p->expired ){
68008    rc = SQLITE_ABORT;
68009    break;
68010  }
68011
68012  u.ax.nField = 0;
68013  u.ax.pKeyInfo = 0;
68014  u.ax.p2 = pOp->p2;
68015  u.ax.iDb = pOp->p3;
68016  assert( u.ax.iDb>=0 && u.ax.iDb<db->nDb );
68017  assert( (p->btreeMask & (((yDbMask)1)<<u.ax.iDb))!=0 );
68018  u.ax.pDb = &db->aDb[u.ax.iDb];
68019  u.ax.pX = u.ax.pDb->pBt;
68020  assert( u.ax.pX!=0 );
68021  if( pOp->opcode==OP_OpenWrite ){
68022    u.ax.wrFlag = 1;
68023    assert( sqlite3SchemaMutexHeld(db, u.ax.iDb, 0) );
68024    if( u.ax.pDb->pSchema->file_format < p->minWriteFileFormat ){
68025      p->minWriteFileFormat = u.ax.pDb->pSchema->file_format;
68026    }
68027  }else{
68028    u.ax.wrFlag = 0;
68029  }
68030  if( pOp->p5 ){
68031    assert( u.ax.p2>0 );
68032    assert( u.ax.p2<=p->nMem );
68033    pIn2 = &aMem[u.ax.p2];
68034    assert( memIsValid(pIn2) );
68035    assert( (pIn2->flags & MEM_Int)!=0 );
68036    sqlite3VdbeMemIntegerify(pIn2);
68037    u.ax.p2 = (int)pIn2->u.i;
68038    /* The u.ax.p2 value always comes from a prior OP_CreateTable opcode and
68039    ** that opcode will always set the u.ax.p2 value to 2 or more or else fail.
68040    ** If there were a failure, the prepared statement would have halted
68041    ** before reaching this instruction. */
68042    if( NEVER(u.ax.p2<2) ) {
68043      rc = SQLITE_CORRUPT_BKPT;
68044      goto abort_due_to_error;
68045    }
68046  }
68047  if( pOp->p4type==P4_KEYINFO ){
68048    u.ax.pKeyInfo = pOp->p4.pKeyInfo;
68049    u.ax.pKeyInfo->enc = ENC(p->db);
68050    u.ax.nField = u.ax.pKeyInfo->nField+1;
68051  }else if( pOp->p4type==P4_INT32 ){
68052    u.ax.nField = pOp->p4.i;
68053  }
68054  assert( pOp->p1>=0 );
68055  u.ax.pCur = allocateCursor(p, pOp->p1, u.ax.nField, u.ax.iDb, 1);
68056  if( u.ax.pCur==0 ) goto no_mem;
68057  u.ax.pCur->nullRow = 1;
68058  u.ax.pCur->isOrdered = 1;
68059  rc = sqlite3BtreeCursor(u.ax.pX, u.ax.p2, u.ax.wrFlag, u.ax.pKeyInfo, u.ax.pCur->pCursor);
68060  u.ax.pCur->pKeyInfo = u.ax.pKeyInfo;
68061
68062  /* Since it performs no memory allocation or IO, the only value that
68063  ** sqlite3BtreeCursor() may return is SQLITE_OK. */
68064  assert( rc==SQLITE_OK );
68065
68066  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
68067  ** SQLite used to check if the root-page flags were sane at this point
68068  ** and report database corruption if they were not, but this check has
68069  ** since moved into the btree layer.  */
68070  u.ax.pCur->isTable = pOp->p4type!=P4_KEYINFO;
68071  u.ax.pCur->isIndex = !u.ax.pCur->isTable;
68072  break;
68073}
68074
68075/* Opcode: OpenEphemeral P1 P2 * P4 P5
68076**
68077** Open a new cursor P1 to a transient table.
68078** The cursor is always opened read/write even if
68079** the main database is read-only.  The ephemeral
68080** table is deleted automatically when the cursor is closed.
68081**
68082** P2 is the number of columns in the ephemeral table.
68083** The cursor points to a BTree table if P4==0 and to a BTree index
68084** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
68085** that defines the format of keys in the index.
68086**
68087** This opcode was once called OpenTemp.  But that created
68088** confusion because the term "temp table", might refer either
68089** to a TEMP table at the SQL level, or to a table opened by
68090** this opcode.  Then this opcode was call OpenVirtual.  But
68091** that created confusion with the whole virtual-table idea.
68092**
68093** The P5 parameter can be a mask of the BTREE_* flags defined
68094** in btree.h.  These flags control aspects of the operation of
68095** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
68096** added automatically.
68097*/
68098/* Opcode: OpenAutoindex P1 P2 * P4 *
68099**
68100** This opcode works the same as OP_OpenEphemeral.  It has a
68101** different name to distinguish its use.  Tables created using
68102** by this opcode will be used for automatically created transient
68103** indices in joins.
68104*/
68105case OP_OpenAutoindex:
68106case OP_OpenEphemeral: {
68107#if 0  /* local variables moved into u.ay */
68108  VdbeCursor *pCx;
68109#endif /* local variables moved into u.ay */
68110  static const int vfsFlags =
68111      SQLITE_OPEN_READWRITE |
68112      SQLITE_OPEN_CREATE |
68113      SQLITE_OPEN_EXCLUSIVE |
68114      SQLITE_OPEN_DELETEONCLOSE |
68115      SQLITE_OPEN_TRANSIENT_DB;
68116
68117  assert( pOp->p1>=0 );
68118  u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68119  if( u.ay.pCx==0 ) goto no_mem;
68120  u.ay.pCx->nullRow = 1;
68121  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.ay.pCx->pBt,
68122                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
68123  if( rc==SQLITE_OK ){
68124    rc = sqlite3BtreeBeginTrans(u.ay.pCx->pBt, 1);
68125  }
68126  if( rc==SQLITE_OK ){
68127    /* If a transient index is required, create it by calling
68128    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
68129    ** opening it. If a transient table is required, just use the
68130    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
68131    */
68132    if( pOp->p4.pKeyInfo ){
68133      int pgno;
68134      assert( pOp->p4type==P4_KEYINFO );
68135      rc = sqlite3BtreeCreateTable(u.ay.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
68136      if( rc==SQLITE_OK ){
68137        assert( pgno==MASTER_ROOT+1 );
68138        rc = sqlite3BtreeCursor(u.ay.pCx->pBt, pgno, 1,
68139                                (KeyInfo*)pOp->p4.z, u.ay.pCx->pCursor);
68140        u.ay.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68141        u.ay.pCx->pKeyInfo->enc = ENC(p->db);
68142      }
68143      u.ay.pCx->isTable = 0;
68144    }else{
68145      rc = sqlite3BtreeCursor(u.ay.pCx->pBt, MASTER_ROOT, 1, 0, u.ay.pCx->pCursor);
68146      u.ay.pCx->isTable = 1;
68147    }
68148  }
68149  u.ay.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
68150  u.ay.pCx->isIndex = !u.ay.pCx->isTable;
68151  break;
68152}
68153
68154/* Opcode: OpenSorter P1 P2 * P4 *
68155**
68156** This opcode works like OP_OpenEphemeral except that it opens
68157** a transient index that is specifically designed to sort large
68158** tables using an external merge-sort algorithm.
68159*/
68160case OP_SorterOpen: {
68161#if 0  /* local variables moved into u.az */
68162  VdbeCursor *pCx;
68163#endif /* local variables moved into u.az */
68164#ifndef SQLITE_OMIT_MERGE_SORT
68165  u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68166  if( u.az.pCx==0 ) goto no_mem;
68167  u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68168  u.az.pCx->pKeyInfo->enc = ENC(p->db);
68169  u.az.pCx->isSorter = 1;
68170  rc = sqlite3VdbeSorterInit(db, u.az.pCx);
68171#else
68172  pOp->opcode = OP_OpenEphemeral;
68173  pc--;
68174#endif
68175  break;
68176}
68177
68178/* Opcode: OpenPseudo P1 P2 P3 * *
68179**
68180** Open a new cursor that points to a fake table that contains a single
68181** row of data.  The content of that one row in the content of memory
68182** register P2.  In other words, cursor P1 becomes an alias for the
68183** MEM_Blob content contained in register P2.
68184**
68185** A pseudo-table created by this opcode is used to hold a single
68186** row output from the sorter so that the row can be decomposed into
68187** individual columns using the OP_Column opcode.  The OP_Column opcode
68188** is the only cursor opcode that works with a pseudo-table.
68189**
68190** P3 is the number of fields in the records that will be stored by
68191** the pseudo-table.
68192*/
68193case OP_OpenPseudo: {
68194#if 0  /* local variables moved into u.ba */
68195  VdbeCursor *pCx;
68196#endif /* local variables moved into u.ba */
68197
68198  assert( pOp->p1>=0 );
68199  u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
68200  if( u.ba.pCx==0 ) goto no_mem;
68201  u.ba.pCx->nullRow = 1;
68202  u.ba.pCx->pseudoTableReg = pOp->p2;
68203  u.ba.pCx->isTable = 1;
68204  u.ba.pCx->isIndex = 0;
68205  break;
68206}
68207
68208/* Opcode: Close P1 * * * *
68209**
68210** Close a cursor previously opened as P1.  If P1 is not
68211** currently open, this instruction is a no-op.
68212*/
68213case OP_Close: {
68214  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68215  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
68216  p->apCsr[pOp->p1] = 0;
68217  break;
68218}
68219
68220/* Opcode: SeekGe P1 P2 P3 P4 *
68221**
68222** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68223** use the value in register P3 as the key.  If cursor P1 refers
68224** to an SQL index, then P3 is the first in an array of P4 registers
68225** that are used as an unpacked index key.
68226**
68227** Reposition cursor P1 so that  it points to the smallest entry that
68228** is greater than or equal to the key value. If there are no records
68229** greater than or equal to the key and P2 is not zero, then jump to P2.
68230**
68231** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
68232*/
68233/* Opcode: SeekGt P1 P2 P3 P4 *
68234**
68235** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68236** use the value in register P3 as a key. If cursor P1 refers
68237** to an SQL index, then P3 is the first in an array of P4 registers
68238** that are used as an unpacked index key.
68239**
68240** Reposition cursor P1 so that  it points to the smallest entry that
68241** is greater than the key value. If there are no records greater than
68242** the key and P2 is not zero, then jump to P2.
68243**
68244** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
68245*/
68246/* Opcode: SeekLt P1 P2 P3 P4 *
68247**
68248** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68249** use the value in register P3 as a key. If cursor P1 refers
68250** to an SQL index, then P3 is the first in an array of P4 registers
68251** that are used as an unpacked index key.
68252**
68253** Reposition cursor P1 so that  it points to the largest entry that
68254** is less than the key value. If there are no records less than
68255** the key and P2 is not zero, then jump to P2.
68256**
68257** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
68258*/
68259/* Opcode: SeekLe P1 P2 P3 P4 *
68260**
68261** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68262** use the value in register P3 as a key. If cursor P1 refers
68263** to an SQL index, then P3 is the first in an array of P4 registers
68264** that are used as an unpacked index key.
68265**
68266** Reposition cursor P1 so that it points to the largest entry that
68267** is less than or equal to the key value. If there are no records
68268** less than or equal to the key and P2 is not zero, then jump to P2.
68269**
68270** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
68271*/
68272case OP_SeekLt:         /* jump, in3 */
68273case OP_SeekLe:         /* jump, in3 */
68274case OP_SeekGe:         /* jump, in3 */
68275case OP_SeekGt: {       /* jump, in3 */
68276#if 0  /* local variables moved into u.bb */
68277  int res;
68278  int oc;
68279  VdbeCursor *pC;
68280  UnpackedRecord r;
68281  int nField;
68282  i64 iKey;      /* The rowid we are to seek to */
68283#endif /* local variables moved into u.bb */
68284
68285  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68286  assert( pOp->p2!=0 );
68287  u.bb.pC = p->apCsr[pOp->p1];
68288  assert( u.bb.pC!=0 );
68289  assert( u.bb.pC->pseudoTableReg==0 );
68290  assert( OP_SeekLe == OP_SeekLt+1 );
68291  assert( OP_SeekGe == OP_SeekLt+2 );
68292  assert( OP_SeekGt == OP_SeekLt+3 );
68293  assert( u.bb.pC->isOrdered );
68294  if( ALWAYS(u.bb.pC->pCursor!=0) ){
68295    u.bb.oc = pOp->opcode;
68296    u.bb.pC->nullRow = 0;
68297    if( u.bb.pC->isTable ){
68298      /* The input value in P3 might be of any type: integer, real, string,
68299      ** blob, or NULL.  But it needs to be an integer before we can do
68300      ** the seek, so covert it. */
68301      pIn3 = &aMem[pOp->p3];
68302      applyNumericAffinity(pIn3);
68303      u.bb.iKey = sqlite3VdbeIntValue(pIn3);
68304      u.bb.pC->rowidIsValid = 0;
68305
68306      /* If the P3 value could not be converted into an integer without
68307      ** loss of information, then special processing is required... */
68308      if( (pIn3->flags & MEM_Int)==0 ){
68309        if( (pIn3->flags & MEM_Real)==0 ){
68310          /* If the P3 value cannot be converted into any kind of a number,
68311          ** then the seek is not possible, so jump to P2 */
68312          pc = pOp->p2 - 1;
68313          break;
68314        }
68315        /* If we reach this point, then the P3 value must be a floating
68316        ** point number. */
68317        assert( (pIn3->flags & MEM_Real)!=0 );
68318
68319        if( u.bb.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bb.iKey || pIn3->r>0) ){
68320          /* The P3 value is too large in magnitude to be expressed as an
68321          ** integer. */
68322          u.bb.res = 1;
68323          if( pIn3->r<0 ){
68324            if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
68325              rc = sqlite3BtreeFirst(u.bb.pC->pCursor, &u.bb.res);
68326              if( rc!=SQLITE_OK ) goto abort_due_to_error;
68327            }
68328          }else{
68329            if( u.bb.oc<=OP_SeekLe ){  assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
68330              rc = sqlite3BtreeLast(u.bb.pC->pCursor, &u.bb.res);
68331              if( rc!=SQLITE_OK ) goto abort_due_to_error;
68332            }
68333          }
68334          if( u.bb.res ){
68335            pc = pOp->p2 - 1;
68336          }
68337          break;
68338        }else if( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekGe ){
68339          /* Use the ceiling() function to convert real->int */
68340          if( pIn3->r > (double)u.bb.iKey ) u.bb.iKey++;
68341        }else{
68342          /* Use the floor() function to convert real->int */
68343          assert( u.bb.oc==OP_SeekLe || u.bb.oc==OP_SeekGt );
68344          if( pIn3->r < (double)u.bb.iKey ) u.bb.iKey--;
68345        }
68346      }
68347      rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, 0, (u64)u.bb.iKey, 0, &u.bb.res);
68348      if( rc!=SQLITE_OK ){
68349        goto abort_due_to_error;
68350      }
68351      if( u.bb.res==0 ){
68352        u.bb.pC->rowidIsValid = 1;
68353        u.bb.pC->lastRowid = u.bb.iKey;
68354      }
68355    }else{
68356      u.bb.nField = pOp->p4.i;
68357      assert( pOp->p4type==P4_INT32 );
68358      assert( u.bb.nField>0 );
68359      u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
68360      u.bb.r.nField = (u16)u.bb.nField;
68361
68362      /* The next line of code computes as follows, only faster:
68363      **   if( u.bb.oc==OP_SeekGt || u.bb.oc==OP_SeekLe ){
68364      **     u.bb.r.flags = UNPACKED_INCRKEY;
68365      **   }else{
68366      **     u.bb.r.flags = 0;
68367      **   }
68368      */
68369      u.bb.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bb.oc - OP_SeekLt)));
68370      assert( u.bb.oc!=OP_SeekGt || u.bb.r.flags==UNPACKED_INCRKEY );
68371      assert( u.bb.oc!=OP_SeekLe || u.bb.r.flags==UNPACKED_INCRKEY );
68372      assert( u.bb.oc!=OP_SeekGe || u.bb.r.flags==0 );
68373      assert( u.bb.oc!=OP_SeekLt || u.bb.r.flags==0 );
68374
68375      u.bb.r.aMem = &aMem[pOp->p3];
68376#ifdef SQLITE_DEBUG
68377      { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
68378#endif
68379      ExpandBlob(u.bb.r.aMem);
68380      rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, &u.bb.r, 0, 0, &u.bb.res);
68381      if( rc!=SQLITE_OK ){
68382        goto abort_due_to_error;
68383      }
68384      u.bb.pC->rowidIsValid = 0;
68385    }
68386    u.bb.pC->deferredMoveto = 0;
68387    u.bb.pC->cacheStatus = CACHE_STALE;
68388#ifdef SQLITE_TEST
68389    sqlite3_search_count++;
68390#endif
68391    if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
68392      if( u.bb.res<0 || (u.bb.res==0 && u.bb.oc==OP_SeekGt) ){
68393        rc = sqlite3BtreeNext(u.bb.pC->pCursor, &u.bb.res);
68394        if( rc!=SQLITE_OK ) goto abort_due_to_error;
68395        u.bb.pC->rowidIsValid = 0;
68396      }else{
68397        u.bb.res = 0;
68398      }
68399    }else{
68400      assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
68401      if( u.bb.res>0 || (u.bb.res==0 && u.bb.oc==OP_SeekLt) ){
68402        rc = sqlite3BtreePrevious(u.bb.pC->pCursor, &u.bb.res);
68403        if( rc!=SQLITE_OK ) goto abort_due_to_error;
68404        u.bb.pC->rowidIsValid = 0;
68405      }else{
68406        /* u.bb.res might be negative because the table is empty.  Check to
68407        ** see if this is the case.
68408        */
68409        u.bb.res = sqlite3BtreeEof(u.bb.pC->pCursor);
68410      }
68411    }
68412    assert( pOp->p2>0 );
68413    if( u.bb.res ){
68414      pc = pOp->p2 - 1;
68415    }
68416  }else{
68417    /* This happens when attempting to open the sqlite3_master table
68418    ** for read access returns SQLITE_EMPTY. In this case always
68419    ** take the jump (since there are no records in the table).
68420    */
68421    pc = pOp->p2 - 1;
68422  }
68423  break;
68424}
68425
68426/* Opcode: Seek P1 P2 * * *
68427**
68428** P1 is an open table cursor and P2 is a rowid integer.  Arrange
68429** for P1 to move so that it points to the rowid given by P2.
68430**
68431** This is actually a deferred seek.  Nothing actually happens until
68432** the cursor is used to read a record.  That way, if no reads
68433** occur, no unnecessary I/O happens.
68434*/
68435case OP_Seek: {    /* in2 */
68436#if 0  /* local variables moved into u.bc */
68437  VdbeCursor *pC;
68438#endif /* local variables moved into u.bc */
68439
68440  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68441  u.bc.pC = p->apCsr[pOp->p1];
68442  assert( u.bc.pC!=0 );
68443  if( ALWAYS(u.bc.pC->pCursor!=0) ){
68444    assert( u.bc.pC->isTable );
68445    u.bc.pC->nullRow = 0;
68446    pIn2 = &aMem[pOp->p2];
68447    u.bc.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
68448    u.bc.pC->rowidIsValid = 0;
68449    u.bc.pC->deferredMoveto = 1;
68450  }
68451  break;
68452}
68453
68454
68455/* Opcode: Found P1 P2 P3 P4 *
68456**
68457** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68458** P4>0 then register P3 is the first of P4 registers that form an unpacked
68459** record.
68460**
68461** Cursor P1 is on an index btree.  If the record identified by P3 and P4
68462** is a prefix of any entry in P1 then a jump is made to P2 and
68463** P1 is left pointing at the matching entry.
68464*/
68465/* Opcode: NotFound P1 P2 P3 P4 *
68466**
68467** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68468** P4>0 then register P3 is the first of P4 registers that form an unpacked
68469** record.
68470**
68471** Cursor P1 is on an index btree.  If the record identified by P3 and P4
68472** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
68473** does contain an entry whose prefix matches the P3/P4 record then control
68474** falls through to the next instruction and P1 is left pointing at the
68475** matching entry.
68476**
68477** See also: Found, NotExists, IsUnique
68478*/
68479case OP_NotFound:       /* jump, in3 */
68480case OP_Found: {        /* jump, in3 */
68481#if 0  /* local variables moved into u.bd */
68482  int alreadyExists;
68483  VdbeCursor *pC;
68484  int res;
68485  char *pFree;
68486  UnpackedRecord *pIdxKey;
68487  UnpackedRecord r;
68488  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
68489#endif /* local variables moved into u.bd */
68490
68491#ifdef SQLITE_TEST
68492  sqlite3_found_count++;
68493#endif
68494
68495  u.bd.alreadyExists = 0;
68496  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68497  assert( pOp->p4type==P4_INT32 );
68498  u.bd.pC = p->apCsr[pOp->p1];
68499  assert( u.bd.pC!=0 );
68500  pIn3 = &aMem[pOp->p3];
68501  if( ALWAYS(u.bd.pC->pCursor!=0) ){
68502
68503    assert( u.bd.pC->isTable==0 );
68504    if( pOp->p4.i>0 ){
68505      u.bd.r.pKeyInfo = u.bd.pC->pKeyInfo;
68506      u.bd.r.nField = (u16)pOp->p4.i;
68507      u.bd.r.aMem = pIn3;
68508#ifdef SQLITE_DEBUG
68509      { int i; for(i=0; i<u.bd.r.nField; i++) assert( memIsValid(&u.bd.r.aMem[i]) ); }
68510#endif
68511      u.bd.r.flags = UNPACKED_PREFIX_MATCH;
68512      u.bd.pIdxKey = &u.bd.r;
68513    }else{
68514      u.bd.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
68515          u.bd.pC->pKeyInfo, u.bd.aTempRec, sizeof(u.bd.aTempRec), &u.bd.pFree
68516      );
68517      if( u.bd.pIdxKey==0 ) goto no_mem;
68518      assert( pIn3->flags & MEM_Blob );
68519      assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
68520      sqlite3VdbeRecordUnpack(u.bd.pC->pKeyInfo, pIn3->n, pIn3->z, u.bd.pIdxKey);
68521      u.bd.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
68522    }
68523    rc = sqlite3BtreeMovetoUnpacked(u.bd.pC->pCursor, u.bd.pIdxKey, 0, 0, &u.bd.res);
68524    if( pOp->p4.i==0 ){
68525      sqlite3DbFree(db, u.bd.pFree);
68526    }
68527    if( rc!=SQLITE_OK ){
68528      break;
68529    }
68530    u.bd.alreadyExists = (u.bd.res==0);
68531    u.bd.pC->deferredMoveto = 0;
68532    u.bd.pC->cacheStatus = CACHE_STALE;
68533  }
68534  if( pOp->opcode==OP_Found ){
68535    if( u.bd.alreadyExists ) pc = pOp->p2 - 1;
68536  }else{
68537    if( !u.bd.alreadyExists ) pc = pOp->p2 - 1;
68538  }
68539  break;
68540}
68541
68542/* Opcode: IsUnique P1 P2 P3 P4 *
68543**
68544** Cursor P1 is open on an index b-tree - that is to say, a btree which
68545** no data and where the key are records generated by OP_MakeRecord with
68546** the list field being the integer ROWID of the entry that the index
68547** entry refers to.
68548**
68549** The P3 register contains an integer record number. Call this record
68550** number R. Register P4 is the first in a set of N contiguous registers
68551** that make up an unpacked index key that can be used with cursor P1.
68552** The value of N can be inferred from the cursor. N includes the rowid
68553** value appended to the end of the index record. This rowid value may
68554** or may not be the same as R.
68555**
68556** If any of the N registers beginning with register P4 contains a NULL
68557** value, jump immediately to P2.
68558**
68559** Otherwise, this instruction checks if cursor P1 contains an entry
68560** where the first (N-1) fields match but the rowid value at the end
68561** of the index entry is not R. If there is no such entry, control jumps
68562** to instruction P2. Otherwise, the rowid of the conflicting index
68563** entry is copied to register P3 and control falls through to the next
68564** instruction.
68565**
68566** See also: NotFound, NotExists, Found
68567*/
68568case OP_IsUnique: {        /* jump, in3 */
68569#if 0  /* local variables moved into u.be */
68570  u16 ii;
68571  VdbeCursor *pCx;
68572  BtCursor *pCrsr;
68573  u16 nField;
68574  Mem *aMx;
68575  UnpackedRecord r;                  /* B-Tree index search key */
68576  i64 R;                             /* Rowid stored in register P3 */
68577#endif /* local variables moved into u.be */
68578
68579  pIn3 = &aMem[pOp->p3];
68580  u.be.aMx = &aMem[pOp->p4.i];
68581  /* Assert that the values of parameters P1 and P4 are in range. */
68582  assert( pOp->p4type==P4_INT32 );
68583  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
68584  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68585
68586  /* Find the index cursor. */
68587  u.be.pCx = p->apCsr[pOp->p1];
68588  assert( u.be.pCx->deferredMoveto==0 );
68589  u.be.pCx->seekResult = 0;
68590  u.be.pCx->cacheStatus = CACHE_STALE;
68591  u.be.pCrsr = u.be.pCx->pCursor;
68592
68593  /* If any of the values are NULL, take the jump. */
68594  u.be.nField = u.be.pCx->pKeyInfo->nField;
68595  for(u.be.ii=0; u.be.ii<u.be.nField; u.be.ii++){
68596    if( u.be.aMx[u.be.ii].flags & MEM_Null ){
68597      pc = pOp->p2 - 1;
68598      u.be.pCrsr = 0;
68599      break;
68600    }
68601  }
68602  assert( (u.be.aMx[u.be.nField].flags & MEM_Null)==0 );
68603
68604  if( u.be.pCrsr!=0 ){
68605    /* Populate the index search key. */
68606    u.be.r.pKeyInfo = u.be.pCx->pKeyInfo;
68607    u.be.r.nField = u.be.nField + 1;
68608    u.be.r.flags = UNPACKED_PREFIX_SEARCH;
68609    u.be.r.aMem = u.be.aMx;
68610#ifdef SQLITE_DEBUG
68611    { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
68612#endif
68613
68614    /* Extract the value of u.be.R from register P3. */
68615    sqlite3VdbeMemIntegerify(pIn3);
68616    u.be.R = pIn3->u.i;
68617
68618    /* Search the B-Tree index. If no conflicting record is found, jump
68619    ** to P2. Otherwise, copy the rowid of the conflicting record to
68620    ** register P3 and fall through to the next instruction.  */
68621    rc = sqlite3BtreeMovetoUnpacked(u.be.pCrsr, &u.be.r, 0, 0, &u.be.pCx->seekResult);
68622    if( (u.be.r.flags & UNPACKED_PREFIX_SEARCH) || u.be.r.rowid==u.be.R ){
68623      pc = pOp->p2 - 1;
68624    }else{
68625      pIn3->u.i = u.be.r.rowid;
68626    }
68627  }
68628  break;
68629}
68630
68631/* Opcode: NotExists P1 P2 P3 * *
68632**
68633** Use the content of register P3 as an integer key.  If a record
68634** with that key does not exist in table of P1, then jump to P2.
68635** If the record does exist, then fall through.  The cursor is left
68636** pointing to the record if it exists.
68637**
68638** The difference between this operation and NotFound is that this
68639** operation assumes the key is an integer and that P1 is a table whereas
68640** NotFound assumes key is a blob constructed from MakeRecord and
68641** P1 is an index.
68642**
68643** See also: Found, NotFound, IsUnique
68644*/
68645case OP_NotExists: {        /* jump, in3 */
68646#if 0  /* local variables moved into u.bf */
68647  VdbeCursor *pC;
68648  BtCursor *pCrsr;
68649  int res;
68650  u64 iKey;
68651#endif /* local variables moved into u.bf */
68652
68653  pIn3 = &aMem[pOp->p3];
68654  assert( pIn3->flags & MEM_Int );
68655  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68656  u.bf.pC = p->apCsr[pOp->p1];
68657  assert( u.bf.pC!=0 );
68658  assert( u.bf.pC->isTable );
68659  assert( u.bf.pC->pseudoTableReg==0 );
68660  u.bf.pCrsr = u.bf.pC->pCursor;
68661  if( ALWAYS(u.bf.pCrsr!=0) ){
68662    u.bf.res = 0;
68663    u.bf.iKey = pIn3->u.i;
68664    rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, 0, u.bf.iKey, 0, &u.bf.res);
68665    u.bf.pC->lastRowid = pIn3->u.i;
68666    u.bf.pC->rowidIsValid = u.bf.res==0 ?1:0;
68667    u.bf.pC->nullRow = 0;
68668    u.bf.pC->cacheStatus = CACHE_STALE;
68669    u.bf.pC->deferredMoveto = 0;
68670    if( u.bf.res!=0 ){
68671      pc = pOp->p2 - 1;
68672      assert( u.bf.pC->rowidIsValid==0 );
68673    }
68674    u.bf.pC->seekResult = u.bf.res;
68675  }else{
68676    /* This happens when an attempt to open a read cursor on the
68677    ** sqlite_master table returns SQLITE_EMPTY.
68678    */
68679    pc = pOp->p2 - 1;
68680    assert( u.bf.pC->rowidIsValid==0 );
68681    u.bf.pC->seekResult = 0;
68682  }
68683  break;
68684}
68685
68686/* Opcode: Sequence P1 P2 * * *
68687**
68688** Find the next available sequence number for cursor P1.
68689** Write the sequence number into register P2.
68690** The sequence number on the cursor is incremented after this
68691** instruction.
68692*/
68693case OP_Sequence: {           /* out2-prerelease */
68694  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68695  assert( p->apCsr[pOp->p1]!=0 );
68696  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
68697  break;
68698}
68699
68700
68701/* Opcode: NewRowid P1 P2 P3 * *
68702**
68703** Get a new integer record number (a.k.a "rowid") used as the key to a table.
68704** The record number is not previously used as a key in the database
68705** table that cursor P1 points to.  The new record number is written
68706** written to register P2.
68707**
68708** If P3>0 then P3 is a register in the root frame of this VDBE that holds
68709** the largest previously generated record number. No new record numbers are
68710** allowed to be less than this value. When this value reaches its maximum,
68711** an SQLITE_FULL error is generated. The P3 register is updated with the '
68712** generated record number. This P3 mechanism is used to help implement the
68713** AUTOINCREMENT feature.
68714*/
68715case OP_NewRowid: {           /* out2-prerelease */
68716#if 0  /* local variables moved into u.bg */
68717  i64 v;                 /* The new rowid */
68718  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
68719  int res;               /* Result of an sqlite3BtreeLast() */
68720  int cnt;               /* Counter to limit the number of searches */
68721  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
68722  VdbeFrame *pFrame;     /* Root frame of VDBE */
68723#endif /* local variables moved into u.bg */
68724
68725  u.bg.v = 0;
68726  u.bg.res = 0;
68727  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68728  u.bg.pC = p->apCsr[pOp->p1];
68729  assert( u.bg.pC!=0 );
68730  if( NEVER(u.bg.pC->pCursor==0) ){
68731    /* The zero initialization above is all that is needed */
68732  }else{
68733    /* The next rowid or record number (different terms for the same
68734    ** thing) is obtained in a two-step algorithm.
68735    **
68736    ** First we attempt to find the largest existing rowid and add one
68737    ** to that.  But if the largest existing rowid is already the maximum
68738    ** positive integer, we have to fall through to the second
68739    ** probabilistic algorithm
68740    **
68741    ** The second algorithm is to select a rowid at random and see if
68742    ** it already exists in the table.  If it does not exist, we have
68743    ** succeeded.  If the random rowid does exist, we select a new one
68744    ** and try again, up to 100 times.
68745    */
68746    assert( u.bg.pC->isTable );
68747
68748#ifdef SQLITE_32BIT_ROWID
68749#   define MAX_ROWID 0x7fffffff
68750#else
68751    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
68752    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
68753    ** to provide the constant while making all compilers happy.
68754    */
68755#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
68756#endif
68757
68758    if( !u.bg.pC->useRandomRowid ){
68759      u.bg.v = sqlite3BtreeGetCachedRowid(u.bg.pC->pCursor);
68760      if( u.bg.v==0 ){
68761        rc = sqlite3BtreeLast(u.bg.pC->pCursor, &u.bg.res);
68762        if( rc!=SQLITE_OK ){
68763          goto abort_due_to_error;
68764        }
68765        if( u.bg.res ){
68766          u.bg.v = 1;   /* IMP: R-61914-48074 */
68767        }else{
68768          assert( sqlite3BtreeCursorIsValid(u.bg.pC->pCursor) );
68769          rc = sqlite3BtreeKeySize(u.bg.pC->pCursor, &u.bg.v);
68770          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
68771          if( u.bg.v>=MAX_ROWID ){
68772            u.bg.pC->useRandomRowid = 1;
68773          }else{
68774            u.bg.v++;   /* IMP: R-29538-34987 */
68775          }
68776        }
68777      }
68778
68779#ifndef SQLITE_OMIT_AUTOINCREMENT
68780      if( pOp->p3 ){
68781        /* Assert that P3 is a valid memory cell. */
68782        assert( pOp->p3>0 );
68783        if( p->pFrame ){
68784          for(u.bg.pFrame=p->pFrame; u.bg.pFrame->pParent; u.bg.pFrame=u.bg.pFrame->pParent);
68785          /* Assert that P3 is a valid memory cell. */
68786          assert( pOp->p3<=u.bg.pFrame->nMem );
68787          u.bg.pMem = &u.bg.pFrame->aMem[pOp->p3];
68788        }else{
68789          /* Assert that P3 is a valid memory cell. */
68790          assert( pOp->p3<=p->nMem );
68791          u.bg.pMem = &aMem[pOp->p3];
68792          memAboutToChange(p, u.bg.pMem);
68793        }
68794        assert( memIsValid(u.bg.pMem) );
68795
68796        REGISTER_TRACE(pOp->p3, u.bg.pMem);
68797        sqlite3VdbeMemIntegerify(u.bg.pMem);
68798        assert( (u.bg.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
68799        if( u.bg.pMem->u.i==MAX_ROWID || u.bg.pC->useRandomRowid ){
68800          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
68801          goto abort_due_to_error;
68802        }
68803        if( u.bg.v<u.bg.pMem->u.i+1 ){
68804          u.bg.v = u.bg.pMem->u.i + 1;
68805        }
68806        u.bg.pMem->u.i = u.bg.v;
68807      }
68808#endif
68809
68810      sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, u.bg.v<MAX_ROWID ? u.bg.v+1 : 0);
68811    }
68812    if( u.bg.pC->useRandomRowid ){
68813      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
68814      ** largest possible integer (9223372036854775807) then the database
68815      ** engine starts picking positive candidate ROWIDs at random until
68816      ** it finds one that is not previously used. */
68817      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
68818                             ** an AUTOINCREMENT table. */
68819      /* on the first attempt, simply do one more than previous */
68820      u.bg.v = lastRowid;
68821      u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68822      u.bg.v++; /* ensure non-zero */
68823      u.bg.cnt = 0;
68824      while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bg.pC->pCursor, 0, (u64)u.bg.v,
68825                                                 0, &u.bg.res))==SQLITE_OK)
68826            && (u.bg.res==0)
68827            && (++u.bg.cnt<100)){
68828        /* collision - try another random rowid */
68829        sqlite3_randomness(sizeof(u.bg.v), &u.bg.v);
68830        if( u.bg.cnt<5 ){
68831          /* try "small" random rowids for the initial attempts */
68832          u.bg.v &= 0xffffff;
68833        }else{
68834          u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68835        }
68836        u.bg.v++; /* ensure non-zero */
68837      }
68838      if( rc==SQLITE_OK && u.bg.res==0 ){
68839        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
68840        goto abort_due_to_error;
68841      }
68842      assert( u.bg.v>0 );  /* EV: R-40812-03570 */
68843    }
68844    u.bg.pC->rowidIsValid = 0;
68845    u.bg.pC->deferredMoveto = 0;
68846    u.bg.pC->cacheStatus = CACHE_STALE;
68847  }
68848  pOut->u.i = u.bg.v;
68849  break;
68850}
68851
68852/* Opcode: Insert P1 P2 P3 P4 P5
68853**
68854** Write an entry into the table of cursor P1.  A new entry is
68855** created if it doesn't already exist or the data for an existing
68856** entry is overwritten.  The data is the value MEM_Blob stored in register
68857** number P2. The key is stored in register P3. The key must
68858** be a MEM_Int.
68859**
68860** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
68861** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
68862** then rowid is stored for subsequent return by the
68863** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
68864**
68865** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
68866** the last seek operation (OP_NotExists) was a success, then this
68867** operation will not attempt to find the appropriate row before doing
68868** the insert but will instead overwrite the row that the cursor is
68869** currently pointing to.  Presumably, the prior OP_NotExists opcode
68870** has already positioned the cursor correctly.  This is an optimization
68871** that boosts performance by avoiding redundant seeks.
68872**
68873** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
68874** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
68875** is part of an INSERT operation.  The difference is only important to
68876** the update hook.
68877**
68878** Parameter P4 may point to a string containing the table-name, or
68879** may be NULL. If it is not NULL, then the update-hook
68880** (sqlite3.xUpdateCallback) is invoked following a successful insert.
68881**
68882** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
68883** allocated, then ownership of P2 is transferred to the pseudo-cursor
68884** and register P2 becomes ephemeral.  If the cursor is changed, the
68885** value of register P2 will then change.  Make sure this does not
68886** cause any problems.)
68887**
68888** This instruction only works on tables.  The equivalent instruction
68889** for indices is OP_IdxInsert.
68890*/
68891/* Opcode: InsertInt P1 P2 P3 P4 P5
68892**
68893** This works exactly like OP_Insert except that the key is the
68894** integer value P3, not the value of the integer stored in register P3.
68895*/
68896case OP_Insert:
68897case OP_InsertInt: {
68898#if 0  /* local variables moved into u.bh */
68899  Mem *pData;       /* MEM cell holding data for the record to be inserted */
68900  Mem *pKey;        /* MEM cell holding key  for the record */
68901  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
68902  VdbeCursor *pC;   /* Cursor to table into which insert is written */
68903  int nZero;        /* Number of zero-bytes to append */
68904  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
68905  const char *zDb;  /* database name - used by the update hook */
68906  const char *zTbl; /* Table name - used by the opdate hook */
68907  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
68908#endif /* local variables moved into u.bh */
68909
68910  u.bh.pData = &aMem[pOp->p2];
68911  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68912  assert( memIsValid(u.bh.pData) );
68913  u.bh.pC = p->apCsr[pOp->p1];
68914  assert( u.bh.pC!=0 );
68915  assert( u.bh.pC->pCursor!=0 );
68916  assert( u.bh.pC->pseudoTableReg==0 );
68917  assert( u.bh.pC->isTable );
68918  REGISTER_TRACE(pOp->p2, u.bh.pData);
68919
68920  if( pOp->opcode==OP_Insert ){
68921    u.bh.pKey = &aMem[pOp->p3];
68922    assert( u.bh.pKey->flags & MEM_Int );
68923    assert( memIsValid(u.bh.pKey) );
68924    REGISTER_TRACE(pOp->p3, u.bh.pKey);
68925    u.bh.iKey = u.bh.pKey->u.i;
68926  }else{
68927    assert( pOp->opcode==OP_InsertInt );
68928    u.bh.iKey = pOp->p3;
68929  }
68930
68931  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
68932  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bh.iKey;
68933  if( u.bh.pData->flags & MEM_Null ){
68934    u.bh.pData->z = 0;
68935    u.bh.pData->n = 0;
68936  }else{
68937    assert( u.bh.pData->flags & (MEM_Blob|MEM_Str) );
68938  }
68939  u.bh.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bh.pC->seekResult : 0);
68940  if( u.bh.pData->flags & MEM_Zero ){
68941    u.bh.nZero = u.bh.pData->u.nZero;
68942  }else{
68943    u.bh.nZero = 0;
68944  }
68945  sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, 0);
68946  rc = sqlite3BtreeInsert(u.bh.pC->pCursor, 0, u.bh.iKey,
68947                          u.bh.pData->z, u.bh.pData->n, u.bh.nZero,
68948                          pOp->p5 & OPFLAG_APPEND, u.bh.seekResult
68949  );
68950  u.bh.pC->rowidIsValid = 0;
68951  u.bh.pC->deferredMoveto = 0;
68952  u.bh.pC->cacheStatus = CACHE_STALE;
68953
68954  /* Invoke the update-hook if required. */
68955  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
68956    u.bh.zDb = db->aDb[u.bh.pC->iDb].zName;
68957    u.bh.zTbl = pOp->p4.z;
68958    u.bh.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
68959    assert( u.bh.pC->isTable );
68960    db->xUpdateCallback(db->pUpdateArg, u.bh.op, u.bh.zDb, u.bh.zTbl, u.bh.iKey);
68961    assert( u.bh.pC->iDb>=0 );
68962  }
68963  break;
68964}
68965
68966/* Opcode: Delete P1 P2 * P4 *
68967**
68968** Delete the record at which the P1 cursor is currently pointing.
68969**
68970** The cursor will be left pointing at either the next or the previous
68971** record in the table. If it is left pointing at the next record, then
68972** the next Next instruction will be a no-op.  Hence it is OK to delete
68973** a record from within an Next loop.
68974**
68975** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
68976** incremented (otherwise not).
68977**
68978** P1 must not be pseudo-table.  It has to be a real table with
68979** multiple rows.
68980**
68981** If P4 is not NULL, then it is the name of the table that P1 is
68982** pointing to.  The update hook will be invoked, if it exists.
68983** If P4 is not NULL then the P1 cursor must have been positioned
68984** using OP_NotFound prior to invoking this opcode.
68985*/
68986case OP_Delete: {
68987#if 0  /* local variables moved into u.bi */
68988  i64 iKey;
68989  VdbeCursor *pC;
68990#endif /* local variables moved into u.bi */
68991
68992  u.bi.iKey = 0;
68993  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68994  u.bi.pC = p->apCsr[pOp->p1];
68995  assert( u.bi.pC!=0 );
68996  assert( u.bi.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
68997
68998  /* If the update-hook will be invoked, set u.bi.iKey to the rowid of the
68999  ** row being deleted.
69000  */
69001  if( db->xUpdateCallback && pOp->p4.z ){
69002    assert( u.bi.pC->isTable );
69003    assert( u.bi.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
69004    u.bi.iKey = u.bi.pC->lastRowid;
69005  }
69006
69007  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
69008  ** OP_Column on the same table without any intervening operations that
69009  ** might move or invalidate the cursor.  Hence cursor u.bi.pC is always pointing
69010  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
69011  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
69012  ** to guard against future changes to the code generator.
69013  **/
69014  assert( u.bi.pC->deferredMoveto==0 );
69015  rc = sqlite3VdbeCursorMoveto(u.bi.pC);
69016  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69017
69018  sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
69019  rc = sqlite3BtreeDelete(u.bi.pC->pCursor);
69020  u.bi.pC->cacheStatus = CACHE_STALE;
69021
69022  /* Invoke the update-hook if required. */
69023  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69024    const char *zDb = db->aDb[u.bi.pC->iDb].zName;
69025    const char *zTbl = pOp->p4.z;
69026    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bi.iKey);
69027    assert( u.bi.pC->iDb>=0 );
69028  }
69029  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
69030  break;
69031}
69032/* Opcode: ResetCount * * * * *
69033**
69034** The value of the change counter is copied to the database handle
69035** change counter (returned by subsequent calls to sqlite3_changes()).
69036** Then the VMs internal change counter resets to 0.
69037** This is used by trigger programs.
69038*/
69039case OP_ResetCount: {
69040  sqlite3VdbeSetChanges(db, p->nChange);
69041  p->nChange = 0;
69042  break;
69043}
69044
69045/* Opcode: SorterCompare P1 P2 P3
69046**
69047** P1 is a sorter cursor. This instruction compares the record blob in
69048** register P3 with the entry that the sorter cursor currently points to.
69049** If, excluding the rowid fields at the end, the two records are a match,
69050** fall through to the next instruction. Otherwise, jump to instruction P2.
69051*/
69052case OP_SorterCompare: {
69053#if 0  /* local variables moved into u.bj */
69054  VdbeCursor *pC;
69055  int res;
69056#endif /* local variables moved into u.bj */
69057
69058  u.bj.pC = p->apCsr[pOp->p1];
69059  assert( isSorter(u.bj.pC) );
69060  pIn3 = &aMem[pOp->p3];
69061  rc = sqlite3VdbeSorterCompare(u.bj.pC, pIn3, &u.bj.res);
69062  if( u.bj.res ){
69063    pc = pOp->p2-1;
69064  }
69065  break;
69066};
69067
69068/* Opcode: SorterData P1 P2 * * *
69069**
69070** Write into register P2 the current sorter data for sorter cursor P1.
69071*/
69072case OP_SorterData: {
69073#if 0  /* local variables moved into u.bk */
69074  VdbeCursor *pC;
69075#endif /* local variables moved into u.bk */
69076#ifndef SQLITE_OMIT_MERGE_SORT
69077  pOut = &aMem[pOp->p2];
69078  u.bk.pC = p->apCsr[pOp->p1];
69079  assert( u.bk.pC->isSorter );
69080  rc = sqlite3VdbeSorterRowkey(u.bk.pC, pOut);
69081#else
69082  pOp->opcode = OP_RowKey;
69083  pc--;
69084#endif
69085  break;
69086}
69087
69088/* Opcode: RowData P1 P2 * * *
69089**
69090** Write into register P2 the complete row data for cursor P1.
69091** There is no interpretation of the data.
69092** It is just copied onto the P2 register exactly as
69093** it is found in the database file.
69094**
69095** If the P1 cursor must be pointing to a valid row (not a NULL row)
69096** of a real table, not a pseudo-table.
69097*/
69098/* Opcode: RowKey P1 P2 * * *
69099**
69100** Write into register P2 the complete row key for cursor P1.
69101** There is no interpretation of the data.
69102** The key is copied onto the P3 register exactly as
69103** it is found in the database file.
69104**
69105** If the P1 cursor must be pointing to a valid row (not a NULL row)
69106** of a real table, not a pseudo-table.
69107*/
69108case OP_RowKey:
69109case OP_RowData: {
69110#if 0  /* local variables moved into u.bl */
69111  VdbeCursor *pC;
69112  BtCursor *pCrsr;
69113  u32 n;
69114  i64 n64;
69115#endif /* local variables moved into u.bl */
69116
69117  pOut = &aMem[pOp->p2];
69118  memAboutToChange(p, pOut);
69119
69120  /* Note that RowKey and RowData are really exactly the same instruction */
69121  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69122  u.bl.pC = p->apCsr[pOp->p1];
69123  assert( u.bl.pC->isSorter==0 );
69124  assert( u.bl.pC->isTable || pOp->opcode!=OP_RowData );
69125  assert( u.bl.pC->isIndex || pOp->opcode==OP_RowData );
69126  assert( u.bl.pC!=0 );
69127  assert( u.bl.pC->nullRow==0 );
69128  assert( u.bl.pC->pseudoTableReg==0 );
69129  assert( !u.bl.pC->isSorter );
69130  assert( u.bl.pC->pCursor!=0 );
69131  u.bl.pCrsr = u.bl.pC->pCursor;
69132  assert( sqlite3BtreeCursorIsValid(u.bl.pCrsr) );
69133
69134  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
69135  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
69136  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
69137  ** a no-op and can never fail.  But we leave it in place as a safety.
69138  */
69139  assert( u.bl.pC->deferredMoveto==0 );
69140  rc = sqlite3VdbeCursorMoveto(u.bl.pC);
69141  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69142
69143  if( u.bl.pC->isIndex ){
69144    assert( !u.bl.pC->isTable );
69145    VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bl.pCrsr, &u.bl.n64);
69146    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
69147    if( u.bl.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
69148      goto too_big;
69149    }
69150    u.bl.n = (u32)u.bl.n64;
69151  }else{
69152    VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bl.pCrsr, &u.bl.n);
69153    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
69154    if( u.bl.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
69155      goto too_big;
69156    }
69157  }
69158  if( sqlite3VdbeMemGrow(pOut, u.bl.n, 0) ){
69159    goto no_mem;
69160  }
69161  pOut->n = u.bl.n;
69162  MemSetTypeFlag(pOut, MEM_Blob);
69163  if( u.bl.pC->isIndex ){
69164    rc = sqlite3BtreeKey(u.bl.pCrsr, 0, u.bl.n, pOut->z);
69165  }else{
69166    rc = sqlite3BtreeData(u.bl.pCrsr, 0, u.bl.n, pOut->z);
69167  }
69168  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
69169  UPDATE_MAX_BLOBSIZE(pOut);
69170  break;
69171}
69172
69173/* Opcode: Rowid P1 P2 * * *
69174**
69175** Store in register P2 an integer which is the key of the table entry that
69176** P1 is currently point to.
69177**
69178** P1 can be either an ordinary table or a virtual table.  There used to
69179** be a separate OP_VRowid opcode for use with virtual tables, but this
69180** one opcode now works for both table types.
69181*/
69182case OP_Rowid: {                 /* out2-prerelease */
69183#if 0  /* local variables moved into u.bm */
69184  VdbeCursor *pC;
69185  i64 v;
69186  sqlite3_vtab *pVtab;
69187  const sqlite3_module *pModule;
69188#endif /* local variables moved into u.bm */
69189
69190  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69191  u.bm.pC = p->apCsr[pOp->p1];
69192  assert( u.bm.pC!=0 );
69193  assert( u.bm.pC->pseudoTableReg==0 );
69194  if( u.bm.pC->nullRow ){
69195    pOut->flags = MEM_Null;
69196    break;
69197  }else if( u.bm.pC->deferredMoveto ){
69198    u.bm.v = u.bm.pC->movetoTarget;
69199#ifndef SQLITE_OMIT_VIRTUALTABLE
69200  }else if( u.bm.pC->pVtabCursor ){
69201    u.bm.pVtab = u.bm.pC->pVtabCursor->pVtab;
69202    u.bm.pModule = u.bm.pVtab->pModule;
69203    assert( u.bm.pModule->xRowid );
69204    rc = u.bm.pModule->xRowid(u.bm.pC->pVtabCursor, &u.bm.v);
69205    importVtabErrMsg(p, u.bm.pVtab);
69206#endif /* SQLITE_OMIT_VIRTUALTABLE */
69207  }else{
69208    assert( u.bm.pC->pCursor!=0 );
69209    rc = sqlite3VdbeCursorMoveto(u.bm.pC);
69210    if( rc ) goto abort_due_to_error;
69211    if( u.bm.pC->rowidIsValid ){
69212      u.bm.v = u.bm.pC->lastRowid;
69213    }else{
69214      rc = sqlite3BtreeKeySize(u.bm.pC->pCursor, &u.bm.v);
69215      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
69216    }
69217  }
69218  pOut->u.i = u.bm.v;
69219  break;
69220}
69221
69222/* Opcode: NullRow P1 * * * *
69223**
69224** Move the cursor P1 to a null row.  Any OP_Column operations
69225** that occur while the cursor is on the null row will always
69226** write a NULL.
69227*/
69228case OP_NullRow: {
69229#if 0  /* local variables moved into u.bn */
69230  VdbeCursor *pC;
69231#endif /* local variables moved into u.bn */
69232
69233  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69234  u.bn.pC = p->apCsr[pOp->p1];
69235  assert( u.bn.pC!=0 );
69236  u.bn.pC->nullRow = 1;
69237  u.bn.pC->rowidIsValid = 0;
69238  assert( u.bn.pC->pCursor || u.bn.pC->pVtabCursor );
69239  if( u.bn.pC->pCursor ){
69240    sqlite3BtreeClearCursor(u.bn.pC->pCursor);
69241  }
69242  break;
69243}
69244
69245/* Opcode: Last P1 P2 * * *
69246**
69247** The next use of the Rowid or Column or Next instruction for P1
69248** will refer to the last entry in the database table or index.
69249** If the table or index is empty and P2>0, then jump immediately to P2.
69250** If P2 is 0 or if the table or index is not empty, fall through
69251** to the following instruction.
69252*/
69253case OP_Last: {        /* jump */
69254#if 0  /* local variables moved into u.bo */
69255  VdbeCursor *pC;
69256  BtCursor *pCrsr;
69257  int res;
69258#endif /* local variables moved into u.bo */
69259
69260  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69261  u.bo.pC = p->apCsr[pOp->p1];
69262  assert( u.bo.pC!=0 );
69263  u.bo.pCrsr = u.bo.pC->pCursor;
69264  u.bo.res = 0;
69265  if( ALWAYS(u.bo.pCrsr!=0) ){
69266    rc = sqlite3BtreeLast(u.bo.pCrsr, &u.bo.res);
69267  }
69268  u.bo.pC->nullRow = (u8)u.bo.res;
69269  u.bo.pC->deferredMoveto = 0;
69270  u.bo.pC->rowidIsValid = 0;
69271  u.bo.pC->cacheStatus = CACHE_STALE;
69272  if( pOp->p2>0 && u.bo.res ){
69273    pc = pOp->p2 - 1;
69274  }
69275  break;
69276}
69277
69278
69279/* Opcode: Sort P1 P2 * * *
69280**
69281** This opcode does exactly the same thing as OP_Rewind except that
69282** it increments an undocumented global variable used for testing.
69283**
69284** Sorting is accomplished by writing records into a sorting index,
69285** then rewinding that index and playing it back from beginning to
69286** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
69287** rewinding so that the global variable will be incremented and
69288** regression tests can determine whether or not the optimizer is
69289** correctly optimizing out sorts.
69290*/
69291case OP_SorterSort:    /* jump */
69292#ifdef SQLITE_OMIT_MERGE_SORT
69293  pOp->opcode = OP_Sort;
69294#endif
69295case OP_Sort: {        /* jump */
69296#ifdef SQLITE_TEST
69297  sqlite3_sort_count++;
69298  sqlite3_search_count--;
69299#endif
69300  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
69301  /* Fall through into OP_Rewind */
69302}
69303/* Opcode: Rewind P1 P2 * * *
69304**
69305** The next use of the Rowid or Column or Next instruction for P1
69306** will refer to the first entry in the database table or index.
69307** If the table or index is empty and P2>0, then jump immediately to P2.
69308** If P2 is 0 or if the table or index is not empty, fall through
69309** to the following instruction.
69310*/
69311case OP_Rewind: {        /* jump */
69312#if 0  /* local variables moved into u.bp */
69313  VdbeCursor *pC;
69314  BtCursor *pCrsr;
69315  int res;
69316#endif /* local variables moved into u.bp */
69317
69318  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69319  u.bp.pC = p->apCsr[pOp->p1];
69320  assert( u.bp.pC!=0 );
69321  assert( u.bp.pC->isSorter==(pOp->opcode==OP_SorterSort) );
69322  u.bp.res = 1;
69323  if( isSorter(u.bp.pC) ){
69324    rc = sqlite3VdbeSorterRewind(db, u.bp.pC, &u.bp.res);
69325  }else{
69326    u.bp.pCrsr = u.bp.pC->pCursor;
69327    assert( u.bp.pCrsr );
69328    rc = sqlite3BtreeFirst(u.bp.pCrsr, &u.bp.res);
69329    u.bp.pC->atFirst = u.bp.res==0 ?1:0;
69330    u.bp.pC->deferredMoveto = 0;
69331    u.bp.pC->cacheStatus = CACHE_STALE;
69332    u.bp.pC->rowidIsValid = 0;
69333  }
69334  u.bp.pC->nullRow = (u8)u.bp.res;
69335  assert( pOp->p2>0 && pOp->p2<p->nOp );
69336  if( u.bp.res ){
69337    pc = pOp->p2 - 1;
69338  }
69339  break;
69340}
69341
69342/* Opcode: Next P1 P2 * P4 P5
69343**
69344** Advance cursor P1 so that it points to the next key/data pair in its
69345** table or index.  If there are no more key/value pairs then fall through
69346** to the following instruction.  But if the cursor advance was successful,
69347** jump immediately to P2.
69348**
69349** The P1 cursor must be for a real table, not a pseudo-table.
69350**
69351** P4 is always of type P4_ADVANCE. The function pointer points to
69352** sqlite3BtreeNext().
69353**
69354** If P5 is positive and the jump is taken, then event counter
69355** number P5-1 in the prepared statement is incremented.
69356**
69357** See also: Prev
69358*/
69359/* Opcode: Prev P1 P2 * * P5
69360**
69361** Back up cursor P1 so that it points to the previous key/data pair in its
69362** table or index.  If there is no previous key/value pairs then fall through
69363** to the following instruction.  But if the cursor backup was successful,
69364** jump immediately to P2.
69365**
69366** The P1 cursor must be for a real table, not a pseudo-table.
69367**
69368** P4 is always of type P4_ADVANCE. The function pointer points to
69369** sqlite3BtreePrevious().
69370**
69371** If P5 is positive and the jump is taken, then event counter
69372** number P5-1 in the prepared statement is incremented.
69373*/
69374case OP_SorterNext:    /* jump */
69375#ifdef SQLITE_OMIT_MERGE_SORT
69376  pOp->opcode = OP_Next;
69377#endif
69378case OP_Prev:          /* jump */
69379case OP_Next: {        /* jump */
69380#if 0  /* local variables moved into u.bq */
69381  VdbeCursor *pC;
69382  int res;
69383#endif /* local variables moved into u.bq */
69384
69385  CHECK_FOR_INTERRUPT;
69386  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69387  assert( pOp->p5<=ArraySize(p->aCounter) );
69388  u.bq.pC = p->apCsr[pOp->p1];
69389  if( u.bq.pC==0 ){
69390    break;  /* See ticket #2273 */
69391  }
69392  assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterNext) );
69393  if( isSorter(u.bq.pC) ){
69394    assert( pOp->opcode==OP_SorterNext );
69395    rc = sqlite3VdbeSorterNext(db, u.bq.pC, &u.bq.res);
69396  }else{
69397    u.bq.res = 1;
69398    assert( u.bq.pC->deferredMoveto==0 );
69399    assert( u.bq.pC->pCursor );
69400    assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
69401    assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
69402    rc = pOp->p4.xAdvance(u.bq.pC->pCursor, &u.bq.res);
69403  }
69404  u.bq.pC->nullRow = (u8)u.bq.res;
69405  u.bq.pC->cacheStatus = CACHE_STALE;
69406  if( u.bq.res==0 ){
69407    pc = pOp->p2 - 1;
69408    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
69409#ifdef SQLITE_TEST
69410    sqlite3_search_count++;
69411#endif
69412  }
69413  u.bq.pC->rowidIsValid = 0;
69414  break;
69415}
69416
69417/* Opcode: IdxInsert P1 P2 P3 * P5
69418**
69419** Register P2 holds an SQL index key made using the
69420** MakeRecord instructions.  This opcode writes that key
69421** into the index P1.  Data for the entry is nil.
69422**
69423** P3 is a flag that provides a hint to the b-tree layer that this
69424** insert is likely to be an append.
69425**
69426** This instruction only works for indices.  The equivalent instruction
69427** for tables is OP_Insert.
69428*/
69429case OP_SorterInsert:       /* in2 */
69430#ifdef SQLITE_OMIT_MERGE_SORT
69431  pOp->opcode = OP_IdxInsert;
69432#endif
69433case OP_IdxInsert: {        /* in2 */
69434#if 0  /* local variables moved into u.br */
69435  VdbeCursor *pC;
69436  BtCursor *pCrsr;
69437  int nKey;
69438  const char *zKey;
69439#endif /* local variables moved into u.br */
69440
69441  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69442  u.br.pC = p->apCsr[pOp->p1];
69443  assert( u.br.pC!=0 );
69444  assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
69445  pIn2 = &aMem[pOp->p2];
69446  assert( pIn2->flags & MEM_Blob );
69447  u.br.pCrsr = u.br.pC->pCursor;
69448  if( ALWAYS(u.br.pCrsr!=0) ){
69449    assert( u.br.pC->isTable==0 );
69450    rc = ExpandBlob(pIn2);
69451    if( rc==SQLITE_OK ){
69452      if( isSorter(u.br.pC) ){
69453        rc = sqlite3VdbeSorterWrite(db, u.br.pC, pIn2);
69454      }else{
69455        u.br.nKey = pIn2->n;
69456        u.br.zKey = pIn2->z;
69457        rc = sqlite3BtreeInsert(u.br.pCrsr, u.br.zKey, u.br.nKey, "", 0, 0, pOp->p3,
69458            ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.br.pC->seekResult : 0)
69459            );
69460        assert( u.br.pC->deferredMoveto==0 );
69461        u.br.pC->cacheStatus = CACHE_STALE;
69462      }
69463    }
69464  }
69465  break;
69466}
69467
69468/* Opcode: IdxDelete P1 P2 P3 * *
69469**
69470** The content of P3 registers starting at register P2 form
69471** an unpacked index key. This opcode removes that entry from the
69472** index opened by cursor P1.
69473*/
69474case OP_IdxDelete: {
69475#if 0  /* local variables moved into u.bs */
69476  VdbeCursor *pC;
69477  BtCursor *pCrsr;
69478  int res;
69479  UnpackedRecord r;
69480#endif /* local variables moved into u.bs */
69481
69482  assert( pOp->p3>0 );
69483  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
69484  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69485  u.bs.pC = p->apCsr[pOp->p1];
69486  assert( u.bs.pC!=0 );
69487  u.bs.pCrsr = u.bs.pC->pCursor;
69488  if( ALWAYS(u.bs.pCrsr!=0) ){
69489    u.bs.r.pKeyInfo = u.bs.pC->pKeyInfo;
69490    u.bs.r.nField = (u16)pOp->p3;
69491    u.bs.r.flags = 0;
69492    u.bs.r.aMem = &aMem[pOp->p2];
69493#ifdef SQLITE_DEBUG
69494    { int i; for(i=0; i<u.bs.r.nField; i++) assert( memIsValid(&u.bs.r.aMem[i]) ); }
69495#endif
69496    rc = sqlite3BtreeMovetoUnpacked(u.bs.pCrsr, &u.bs.r, 0, 0, &u.bs.res);
69497    if( rc==SQLITE_OK && u.bs.res==0 ){
69498      rc = sqlite3BtreeDelete(u.bs.pCrsr);
69499    }
69500    assert( u.bs.pC->deferredMoveto==0 );
69501    u.bs.pC->cacheStatus = CACHE_STALE;
69502  }
69503  break;
69504}
69505
69506/* Opcode: IdxRowid P1 P2 * * *
69507**
69508** Write into register P2 an integer which is the last entry in the record at
69509** the end of the index key pointed to by cursor P1.  This integer should be
69510** the rowid of the table entry to which this index entry points.
69511**
69512** See also: Rowid, MakeRecord.
69513*/
69514case OP_IdxRowid: {              /* out2-prerelease */
69515#if 0  /* local variables moved into u.bt */
69516  BtCursor *pCrsr;
69517  VdbeCursor *pC;
69518  i64 rowid;
69519#endif /* local variables moved into u.bt */
69520
69521  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69522  u.bt.pC = p->apCsr[pOp->p1];
69523  assert( u.bt.pC!=0 );
69524  u.bt.pCrsr = u.bt.pC->pCursor;
69525  pOut->flags = MEM_Null;
69526  if( ALWAYS(u.bt.pCrsr!=0) ){
69527    rc = sqlite3VdbeCursorMoveto(u.bt.pC);
69528    if( NEVER(rc) ) goto abort_due_to_error;
69529    assert( u.bt.pC->deferredMoveto==0 );
69530    assert( u.bt.pC->isTable==0 );
69531    if( !u.bt.pC->nullRow ){
69532      rc = sqlite3VdbeIdxRowid(db, u.bt.pCrsr, &u.bt.rowid);
69533      if( rc!=SQLITE_OK ){
69534        goto abort_due_to_error;
69535      }
69536      pOut->u.i = u.bt.rowid;
69537      pOut->flags = MEM_Int;
69538    }
69539  }
69540  break;
69541}
69542
69543/* Opcode: IdxGE P1 P2 P3 P4 P5
69544**
69545** The P4 register values beginning with P3 form an unpacked index
69546** key that omits the ROWID.  Compare this key value against the index
69547** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
69548**
69549** If the P1 index entry is greater than or equal to the key value
69550** then jump to P2.  Otherwise fall through to the next instruction.
69551**
69552** If P5 is non-zero then the key value is increased by an epsilon
69553** prior to the comparison.  This make the opcode work like IdxGT except
69554** that if the key from register P3 is a prefix of the key in the cursor,
69555** the result is false whereas it would be true with IdxGT.
69556*/
69557/* Opcode: IdxLT P1 P2 P3 P4 P5
69558**
69559** The P4 register values beginning with P3 form an unpacked index
69560** key that omits the ROWID.  Compare this key value against the index
69561** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
69562**
69563** If the P1 index entry is less than the key value then jump to P2.
69564** Otherwise fall through to the next instruction.
69565**
69566** If P5 is non-zero then the key value is increased by an epsilon prior
69567** to the comparison.  This makes the opcode work like IdxLE.
69568*/
69569case OP_IdxLT:          /* jump */
69570case OP_IdxGE: {        /* jump */
69571#if 0  /* local variables moved into u.bu */
69572  VdbeCursor *pC;
69573  int res;
69574  UnpackedRecord r;
69575#endif /* local variables moved into u.bu */
69576
69577  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69578  u.bu.pC = p->apCsr[pOp->p1];
69579  assert( u.bu.pC!=0 );
69580  assert( u.bu.pC->isOrdered );
69581  if( ALWAYS(u.bu.pC->pCursor!=0) ){
69582    assert( u.bu.pC->deferredMoveto==0 );
69583    assert( pOp->p5==0 || pOp->p5==1 );
69584    assert( pOp->p4type==P4_INT32 );
69585    u.bu.r.pKeyInfo = u.bu.pC->pKeyInfo;
69586    u.bu.r.nField = (u16)pOp->p4.i;
69587    if( pOp->p5 ){
69588      u.bu.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
69589    }else{
69590      u.bu.r.flags = UNPACKED_PREFIX_MATCH;
69591    }
69592    u.bu.r.aMem = &aMem[pOp->p3];
69593#ifdef SQLITE_DEBUG
69594    { int i; for(i=0; i<u.bu.r.nField; i++) assert( memIsValid(&u.bu.r.aMem[i]) ); }
69595#endif
69596    rc = sqlite3VdbeIdxKeyCompare(u.bu.pC, &u.bu.r, &u.bu.res);
69597    if( pOp->opcode==OP_IdxLT ){
69598      u.bu.res = -u.bu.res;
69599    }else{
69600      assert( pOp->opcode==OP_IdxGE );
69601      u.bu.res++;
69602    }
69603    if( u.bu.res>0 ){
69604      pc = pOp->p2 - 1 ;
69605    }
69606  }
69607  break;
69608}
69609
69610/* Opcode: Destroy P1 P2 P3 * *
69611**
69612** Delete an entire database table or index whose root page in the database
69613** file is given by P1.
69614**
69615** The table being destroyed is in the main database file if P3==0.  If
69616** P3==1 then the table to be clear is in the auxiliary database file
69617** that is used to store tables create using CREATE TEMPORARY TABLE.
69618**
69619** If AUTOVACUUM is enabled then it is possible that another root page
69620** might be moved into the newly deleted root page in order to keep all
69621** root pages contiguous at the beginning of the database.  The former
69622** value of the root page that moved - its value before the move occurred -
69623** is stored in register P2.  If no page
69624** movement was required (because the table being dropped was already
69625** the last one in the database) then a zero is stored in register P2.
69626** If AUTOVACUUM is disabled then a zero is stored in register P2.
69627**
69628** See also: Clear
69629*/
69630case OP_Destroy: {     /* out2-prerelease */
69631#if 0  /* local variables moved into u.bv */
69632  int iMoved;
69633  int iCnt;
69634  Vdbe *pVdbe;
69635  int iDb;
69636#endif /* local variables moved into u.bv */
69637#ifndef SQLITE_OMIT_VIRTUALTABLE
69638  u.bv.iCnt = 0;
69639  for(u.bv.pVdbe=db->pVdbe; u.bv.pVdbe; u.bv.pVdbe = u.bv.pVdbe->pNext){
69640    if( u.bv.pVdbe->magic==VDBE_MAGIC_RUN && u.bv.pVdbe->inVtabMethod<2 && u.bv.pVdbe->pc>=0 ){
69641      u.bv.iCnt++;
69642    }
69643  }
69644#else
69645  u.bv.iCnt = db->activeVdbeCnt;
69646#endif
69647  pOut->flags = MEM_Null;
69648  if( u.bv.iCnt>1 ){
69649    rc = SQLITE_LOCKED;
69650    p->errorAction = OE_Abort;
69651  }else{
69652    u.bv.iDb = pOp->p3;
69653    assert( u.bv.iCnt==1 );
69654    assert( (p->btreeMask & (((yDbMask)1)<<u.bv.iDb))!=0 );
69655    rc = sqlite3BtreeDropTable(db->aDb[u.bv.iDb].pBt, pOp->p1, &u.bv.iMoved);
69656    pOut->flags = MEM_Int;
69657    pOut->u.i = u.bv.iMoved;
69658#ifndef SQLITE_OMIT_AUTOVACUUM
69659    if( rc==SQLITE_OK && u.bv.iMoved!=0 ){
69660      sqlite3RootPageMoved(db, u.bv.iDb, u.bv.iMoved, pOp->p1);
69661      /* All OP_Destroy operations occur on the same btree */
69662      assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bv.iDb+1 );
69663      resetSchemaOnFault = u.bv.iDb+1;
69664    }
69665#endif
69666  }
69667  break;
69668}
69669
69670/* Opcode: Clear P1 P2 P3
69671**
69672** Delete all contents of the database table or index whose root page
69673** in the database file is given by P1.  But, unlike Destroy, do not
69674** remove the table or index from the database file.
69675**
69676** The table being clear is in the main database file if P2==0.  If
69677** P2==1 then the table to be clear is in the auxiliary database file
69678** that is used to store tables create using CREATE TEMPORARY TABLE.
69679**
69680** If the P3 value is non-zero, then the table referred to must be an
69681** intkey table (an SQL table, not an index). In this case the row change
69682** count is incremented by the number of rows in the table being cleared.
69683** If P3 is greater than zero, then the value stored in register P3 is
69684** also incremented by the number of rows in the table being cleared.
69685**
69686** See also: Destroy
69687*/
69688case OP_Clear: {
69689#if 0  /* local variables moved into u.bw */
69690  int nChange;
69691#endif /* local variables moved into u.bw */
69692
69693  u.bw.nChange = 0;
69694  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
69695  rc = sqlite3BtreeClearTable(
69696      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bw.nChange : 0)
69697  );
69698  if( pOp->p3 ){
69699    p->nChange += u.bw.nChange;
69700    if( pOp->p3>0 ){
69701      assert( memIsValid(&aMem[pOp->p3]) );
69702      memAboutToChange(p, &aMem[pOp->p3]);
69703      aMem[pOp->p3].u.i += u.bw.nChange;
69704    }
69705  }
69706  break;
69707}
69708
69709/* Opcode: CreateTable P1 P2 * * *
69710**
69711** Allocate a new table in the main database file if P1==0 or in the
69712** auxiliary database file if P1==1 or in an attached database if
69713** P1>1.  Write the root page number of the new table into
69714** register P2
69715**
69716** The difference between a table and an index is this:  A table must
69717** have a 4-byte integer key and can have arbitrary data.  An index
69718** has an arbitrary key but no data.
69719**
69720** See also: CreateIndex
69721*/
69722/* Opcode: CreateIndex P1 P2 * * *
69723**
69724** Allocate a new index in the main database file if P1==0 or in the
69725** auxiliary database file if P1==1 or in an attached database if
69726** P1>1.  Write the root page number of the new table into
69727** register P2.
69728**
69729** See documentation on OP_CreateTable for additional information.
69730*/
69731case OP_CreateIndex:            /* out2-prerelease */
69732case OP_CreateTable: {          /* out2-prerelease */
69733#if 0  /* local variables moved into u.bx */
69734  int pgno;
69735  int flags;
69736  Db *pDb;
69737#endif /* local variables moved into u.bx */
69738
69739  u.bx.pgno = 0;
69740  assert( pOp->p1>=0 && pOp->p1<db->nDb );
69741  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69742  u.bx.pDb = &db->aDb[pOp->p1];
69743  assert( u.bx.pDb->pBt!=0 );
69744  if( pOp->opcode==OP_CreateTable ){
69745    /* u.bx.flags = BTREE_INTKEY; */
69746    u.bx.flags = BTREE_INTKEY;
69747  }else{
69748    u.bx.flags = BTREE_BLOBKEY;
69749  }
69750  rc = sqlite3BtreeCreateTable(u.bx.pDb->pBt, &u.bx.pgno, u.bx.flags);
69751  pOut->u.i = u.bx.pgno;
69752  break;
69753}
69754
69755/* Opcode: ParseSchema P1 * * P4 *
69756**
69757** Read and parse all entries from the SQLITE_MASTER table of database P1
69758** that match the WHERE clause P4.
69759**
69760** This opcode invokes the parser to create a new virtual machine,
69761** then runs the new virtual machine.  It is thus a re-entrant opcode.
69762*/
69763case OP_ParseSchema: {
69764#if 0  /* local variables moved into u.by */
69765  int iDb;
69766  const char *zMaster;
69767  char *zSql;
69768  InitData initData;
69769#endif /* local variables moved into u.by */
69770
69771  /* Any prepared statement that invokes this opcode will hold mutexes
69772  ** on every btree.  This is a prerequisite for invoking
69773  ** sqlite3InitCallback().
69774  */
69775#ifdef SQLITE_DEBUG
69776  for(u.by.iDb=0; u.by.iDb<db->nDb; u.by.iDb++){
69777    assert( u.by.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.by.iDb].pBt) );
69778  }
69779#endif
69780
69781  u.by.iDb = pOp->p1;
69782  assert( u.by.iDb>=0 && u.by.iDb<db->nDb );
69783  assert( DbHasProperty(db, u.by.iDb, DB_SchemaLoaded) );
69784  /* Used to be a conditional */ {
69785    u.by.zMaster = SCHEMA_TABLE(u.by.iDb);
69786    u.by.initData.db = db;
69787    u.by.initData.iDb = pOp->p1;
69788    u.by.initData.pzErrMsg = &p->zErrMsg;
69789    u.by.zSql = sqlite3MPrintf(db,
69790       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
69791       db->aDb[u.by.iDb].zName, u.by.zMaster, pOp->p4.z);
69792    if( u.by.zSql==0 ){
69793      rc = SQLITE_NOMEM;
69794    }else{
69795      assert( db->init.busy==0 );
69796      db->init.busy = 1;
69797      u.by.initData.rc = SQLITE_OK;
69798      assert( !db->mallocFailed );
69799      rc = sqlite3_exec(db, u.by.zSql, sqlite3InitCallback, &u.by.initData, 0);
69800      if( rc==SQLITE_OK ) rc = u.by.initData.rc;
69801      sqlite3DbFree(db, u.by.zSql);
69802      db->init.busy = 0;
69803    }
69804  }
69805  if( rc ) sqlite3ResetInternalSchema(db, -1);
69806  if( rc==SQLITE_NOMEM ){
69807    goto no_mem;
69808  }
69809  break;
69810}
69811
69812#if !defined(SQLITE_OMIT_ANALYZE)
69813/* Opcode: LoadAnalysis P1 * * * *
69814**
69815** Read the sqlite_stat1 table for database P1 and load the content
69816** of that table into the internal index hash table.  This will cause
69817** the analysis to be used when preparing all subsequent queries.
69818*/
69819case OP_LoadAnalysis: {
69820  assert( pOp->p1>=0 && pOp->p1<db->nDb );
69821  rc = sqlite3AnalysisLoad(db, pOp->p1);
69822  break;
69823}
69824#endif /* !defined(SQLITE_OMIT_ANALYZE) */
69825
69826/* Opcode: DropTable P1 * * P4 *
69827**
69828** Remove the internal (in-memory) data structures that describe
69829** the table named P4 in database P1.  This is called after a table
69830** is dropped in order to keep the internal representation of the
69831** schema consistent with what is on disk.
69832*/
69833case OP_DropTable: {
69834  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
69835  break;
69836}
69837
69838/* Opcode: DropIndex P1 * * P4 *
69839**
69840** Remove the internal (in-memory) data structures that describe
69841** the index named P4 in database P1.  This is called after an index
69842** is dropped in order to keep the internal representation of the
69843** schema consistent with what is on disk.
69844*/
69845case OP_DropIndex: {
69846  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
69847  break;
69848}
69849
69850/* Opcode: DropTrigger P1 * * P4 *
69851**
69852** Remove the internal (in-memory) data structures that describe
69853** the trigger named P4 in database P1.  This is called after a trigger
69854** is dropped in order to keep the internal representation of the
69855** schema consistent with what is on disk.
69856*/
69857case OP_DropTrigger: {
69858  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
69859  break;
69860}
69861
69862
69863#ifndef SQLITE_OMIT_INTEGRITY_CHECK
69864/* Opcode: IntegrityCk P1 P2 P3 * P5
69865**
69866** Do an analysis of the currently open database.  Store in
69867** register P1 the text of an error message describing any problems.
69868** If no problems are found, store a NULL in register P1.
69869**
69870** The register P3 contains the maximum number of allowed errors.
69871** At most reg(P3) errors will be reported.
69872** In other words, the analysis stops as soon as reg(P1) errors are
69873** seen.  Reg(P1) is updated with the number of errors remaining.
69874**
69875** The root page numbers of all tables in the database are integer
69876** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
69877** total.
69878**
69879** If P5 is not zero, the check is done on the auxiliary database
69880** file, not the main database file.
69881**
69882** This opcode is used to implement the integrity_check pragma.
69883*/
69884case OP_IntegrityCk: {
69885#if 0  /* local variables moved into u.bz */
69886  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
69887  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
69888  int j;          /* Loop counter */
69889  int nErr;       /* Number of errors reported */
69890  char *z;        /* Text of the error report */
69891  Mem *pnErr;     /* Register keeping track of errors remaining */
69892#endif /* local variables moved into u.bz */
69893
69894  u.bz.nRoot = pOp->p2;
69895  assert( u.bz.nRoot>0 );
69896  u.bz.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bz.nRoot+1) );
69897  if( u.bz.aRoot==0 ) goto no_mem;
69898  assert( pOp->p3>0 && pOp->p3<=p->nMem );
69899  u.bz.pnErr = &aMem[pOp->p3];
69900  assert( (u.bz.pnErr->flags & MEM_Int)!=0 );
69901  assert( (u.bz.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
69902  pIn1 = &aMem[pOp->p1];
69903  for(u.bz.j=0; u.bz.j<u.bz.nRoot; u.bz.j++){
69904    u.bz.aRoot[u.bz.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bz.j]);
69905  }
69906  u.bz.aRoot[u.bz.j] = 0;
69907  assert( pOp->p5<db->nDb );
69908  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
69909  u.bz.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bz.aRoot, u.bz.nRoot,
69910                                 (int)u.bz.pnErr->u.i, &u.bz.nErr);
69911  sqlite3DbFree(db, u.bz.aRoot);
69912  u.bz.pnErr->u.i -= u.bz.nErr;
69913  sqlite3VdbeMemSetNull(pIn1);
69914  if( u.bz.nErr==0 ){
69915    assert( u.bz.z==0 );
69916  }else if( u.bz.z==0 ){
69917    goto no_mem;
69918  }else{
69919    sqlite3VdbeMemSetStr(pIn1, u.bz.z, -1, SQLITE_UTF8, sqlite3_free);
69920  }
69921  UPDATE_MAX_BLOBSIZE(pIn1);
69922  sqlite3VdbeChangeEncoding(pIn1, encoding);
69923  break;
69924}
69925#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
69926
69927/* Opcode: RowSetAdd P1 P2 * * *
69928**
69929** Insert the integer value held by register P2 into a boolean index
69930** held in register P1.
69931**
69932** An assertion fails if P2 is not an integer.
69933*/
69934case OP_RowSetAdd: {       /* in1, in2 */
69935  pIn1 = &aMem[pOp->p1];
69936  pIn2 = &aMem[pOp->p2];
69937  assert( (pIn2->flags & MEM_Int)!=0 );
69938  if( (pIn1->flags & MEM_RowSet)==0 ){
69939    sqlite3VdbeMemSetRowSet(pIn1);
69940    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69941  }
69942  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
69943  break;
69944}
69945
69946/* Opcode: RowSetRead P1 P2 P3 * *
69947**
69948** Extract the smallest value from boolean index P1 and put that value into
69949** register P3.  Or, if boolean index P1 is initially empty, leave P3
69950** unchanged and jump to instruction P2.
69951*/
69952case OP_RowSetRead: {       /* jump, in1, out3 */
69953#if 0  /* local variables moved into u.ca */
69954  i64 val;
69955#endif /* local variables moved into u.ca */
69956  CHECK_FOR_INTERRUPT;
69957  pIn1 = &aMem[pOp->p1];
69958  if( (pIn1->flags & MEM_RowSet)==0
69959   || sqlite3RowSetNext(pIn1->u.pRowSet, &u.ca.val)==0
69960  ){
69961    /* The boolean index is empty */
69962    sqlite3VdbeMemSetNull(pIn1);
69963    pc = pOp->p2 - 1;
69964  }else{
69965    /* A value was pulled from the index */
69966    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.ca.val);
69967  }
69968  break;
69969}
69970
69971/* Opcode: RowSetTest P1 P2 P3 P4
69972**
69973** Register P3 is assumed to hold a 64-bit integer value. If register P1
69974** contains a RowSet object and that RowSet object contains
69975** the value held in P3, jump to register P2. Otherwise, insert the
69976** integer in P3 into the RowSet and continue on to the
69977** next opcode.
69978**
69979** The RowSet object is optimized for the case where successive sets
69980** of integers, where each set contains no duplicates. Each set
69981** of values is identified by a unique P4 value. The first set
69982** must have P4==0, the final set P4=-1.  P4 must be either -1 or
69983** non-negative.  For non-negative values of P4 only the lower 4
69984** bits are significant.
69985**
69986** This allows optimizations: (a) when P4==0 there is no need to test
69987** the rowset object for P3, as it is guaranteed not to contain it,
69988** (b) when P4==-1 there is no need to insert the value, as it will
69989** never be tested for, and (c) when a value that is part of set X is
69990** inserted, there is no need to search to see if the same value was
69991** previously inserted as part of set X (only if it was previously
69992** inserted as part of some other set).
69993*/
69994case OP_RowSetTest: {                     /* jump, in1, in3 */
69995#if 0  /* local variables moved into u.cb */
69996  int iSet;
69997  int exists;
69998#endif /* local variables moved into u.cb */
69999
70000  pIn1 = &aMem[pOp->p1];
70001  pIn3 = &aMem[pOp->p3];
70002  u.cb.iSet = pOp->p4.i;
70003  assert( pIn3->flags&MEM_Int );
70004
70005  /* If there is anything other than a rowset object in memory cell P1,
70006  ** delete it now and initialize P1 with an empty rowset
70007  */
70008  if( (pIn1->flags & MEM_RowSet)==0 ){
70009    sqlite3VdbeMemSetRowSet(pIn1);
70010    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
70011  }
70012
70013  assert( pOp->p4type==P4_INT32 );
70014  assert( u.cb.iSet==-1 || u.cb.iSet>=0 );
70015  if( u.cb.iSet ){
70016    u.cb.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
70017                               (u8)(u.cb.iSet>=0 ? u.cb.iSet & 0xf : 0xff),
70018                               pIn3->u.i);
70019    if( u.cb.exists ){
70020      pc = pOp->p2 - 1;
70021      break;
70022    }
70023  }
70024  if( u.cb.iSet>=0 ){
70025    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
70026  }
70027  break;
70028}
70029
70030
70031#ifndef SQLITE_OMIT_TRIGGER
70032
70033/* Opcode: Program P1 P2 P3 P4 *
70034**
70035** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
70036**
70037** P1 contains the address of the memory cell that contains the first memory
70038** cell in an array of values used as arguments to the sub-program. P2
70039** contains the address to jump to if the sub-program throws an IGNORE
70040** exception using the RAISE() function. Register P3 contains the address
70041** of a memory cell in this (the parent) VM that is used to allocate the
70042** memory required by the sub-vdbe at runtime.
70043**
70044** P4 is a pointer to the VM containing the trigger program.
70045*/
70046case OP_Program: {        /* jump */
70047#if 0  /* local variables moved into u.cc */
70048  int nMem;               /* Number of memory registers for sub-program */
70049  int nByte;              /* Bytes of runtime space required for sub-program */
70050  Mem *pRt;               /* Register to allocate runtime space */
70051  Mem *pMem;              /* Used to iterate through memory cells */
70052  Mem *pEnd;              /* Last memory cell in new array */
70053  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
70054  SubProgram *pProgram;   /* Sub-program to execute */
70055  void *t;                /* Token identifying trigger */
70056#endif /* local variables moved into u.cc */
70057
70058  u.cc.pProgram = pOp->p4.pProgram;
70059  u.cc.pRt = &aMem[pOp->p3];
70060  assert( u.cc.pProgram->nOp>0 );
70061
70062  /* If the p5 flag is clear, then recursive invocation of triggers is
70063  ** disabled for backwards compatibility (p5 is set if this sub-program
70064  ** is really a trigger, not a foreign key action, and the flag set
70065  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
70066  **
70067  ** It is recursive invocation of triggers, at the SQL level, that is
70068  ** disabled. In some cases a single trigger may generate more than one
70069  ** SubProgram (if the trigger may be executed with more than one different
70070  ** ON CONFLICT algorithm). SubProgram structures associated with a
70071  ** single trigger all have the same value for the SubProgram.token
70072  ** variable.  */
70073  if( pOp->p5 ){
70074    u.cc.t = u.cc.pProgram->token;
70075    for(u.cc.pFrame=p->pFrame; u.cc.pFrame && u.cc.pFrame->token!=u.cc.t; u.cc.pFrame=u.cc.pFrame->pParent);
70076    if( u.cc.pFrame ) break;
70077  }
70078
70079  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
70080    rc = SQLITE_ERROR;
70081    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
70082    break;
70083  }
70084
70085  /* Register u.cc.pRt is used to store the memory required to save the state
70086  ** of the current program, and the memory required at runtime to execute
70087  ** the trigger program. If this trigger has been fired before, then u.cc.pRt
70088  ** is already allocated. Otherwise, it must be initialized.  */
70089  if( (u.cc.pRt->flags&MEM_Frame)==0 ){
70090    /* SubProgram.nMem is set to the number of memory cells used by the
70091    ** program stored in SubProgram.aOp. As well as these, one memory
70092    ** cell is required for each cursor used by the program. Set local
70093    ** variable u.cc.nMem (and later, VdbeFrame.nChildMem) to this value.
70094    */
70095    u.cc.nMem = u.cc.pProgram->nMem + u.cc.pProgram->nCsr;
70096    u.cc.nByte = ROUND8(sizeof(VdbeFrame))
70097              + u.cc.nMem * sizeof(Mem)
70098              + u.cc.pProgram->nCsr * sizeof(VdbeCursor *)
70099              + u.cc.pProgram->nOnce * sizeof(u8);
70100    u.cc.pFrame = sqlite3DbMallocZero(db, u.cc.nByte);
70101    if( !u.cc.pFrame ){
70102      goto no_mem;
70103    }
70104    sqlite3VdbeMemRelease(u.cc.pRt);
70105    u.cc.pRt->flags = MEM_Frame;
70106    u.cc.pRt->u.pFrame = u.cc.pFrame;
70107
70108    u.cc.pFrame->v = p;
70109    u.cc.pFrame->nChildMem = u.cc.nMem;
70110    u.cc.pFrame->nChildCsr = u.cc.pProgram->nCsr;
70111    u.cc.pFrame->pc = pc;
70112    u.cc.pFrame->aMem = p->aMem;
70113    u.cc.pFrame->nMem = p->nMem;
70114    u.cc.pFrame->apCsr = p->apCsr;
70115    u.cc.pFrame->nCursor = p->nCursor;
70116    u.cc.pFrame->aOp = p->aOp;
70117    u.cc.pFrame->nOp = p->nOp;
70118    u.cc.pFrame->token = u.cc.pProgram->token;
70119    u.cc.pFrame->aOnceFlag = p->aOnceFlag;
70120    u.cc.pFrame->nOnceFlag = p->nOnceFlag;
70121
70122    u.cc.pEnd = &VdbeFrameMem(u.cc.pFrame)[u.cc.pFrame->nChildMem];
70123    for(u.cc.pMem=VdbeFrameMem(u.cc.pFrame); u.cc.pMem!=u.cc.pEnd; u.cc.pMem++){
70124      u.cc.pMem->flags = MEM_Invalid;
70125      u.cc.pMem->db = db;
70126    }
70127  }else{
70128    u.cc.pFrame = u.cc.pRt->u.pFrame;
70129    assert( u.cc.pProgram->nMem+u.cc.pProgram->nCsr==u.cc.pFrame->nChildMem );
70130    assert( u.cc.pProgram->nCsr==u.cc.pFrame->nChildCsr );
70131    assert( pc==u.cc.pFrame->pc );
70132  }
70133
70134  p->nFrame++;
70135  u.cc.pFrame->pParent = p->pFrame;
70136  u.cc.pFrame->lastRowid = lastRowid;
70137  u.cc.pFrame->nChange = p->nChange;
70138  p->nChange = 0;
70139  p->pFrame = u.cc.pFrame;
70140  p->aMem = aMem = &VdbeFrameMem(u.cc.pFrame)[-1];
70141  p->nMem = u.cc.pFrame->nChildMem;
70142  p->nCursor = (u16)u.cc.pFrame->nChildCsr;
70143  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
70144  p->aOp = aOp = u.cc.pProgram->aOp;
70145  p->nOp = u.cc.pProgram->nOp;
70146  p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
70147  p->nOnceFlag = u.cc.pProgram->nOnce;
70148  pc = -1;
70149  memset(p->aOnceFlag, 0, p->nOnceFlag);
70150
70151  break;
70152}
70153
70154/* Opcode: Param P1 P2 * * *
70155**
70156** This opcode is only ever present in sub-programs called via the
70157** OP_Program instruction. Copy a value currently stored in a memory
70158** cell of the calling (parent) frame to cell P2 in the current frames
70159** address space. This is used by trigger programs to access the new.*
70160** and old.* values.
70161**
70162** The address of the cell in the parent frame is determined by adding
70163** the value of the P1 argument to the value of the P1 argument to the
70164** calling OP_Program instruction.
70165*/
70166case OP_Param: {           /* out2-prerelease */
70167#if 0  /* local variables moved into u.cd */
70168  VdbeFrame *pFrame;
70169  Mem *pIn;
70170#endif /* local variables moved into u.cd */
70171  u.cd.pFrame = p->pFrame;
70172  u.cd.pIn = &u.cd.pFrame->aMem[pOp->p1 + u.cd.pFrame->aOp[u.cd.pFrame->pc].p1];
70173  sqlite3VdbeMemShallowCopy(pOut, u.cd.pIn, MEM_Ephem);
70174  break;
70175}
70176
70177#endif /* #ifndef SQLITE_OMIT_TRIGGER */
70178
70179#ifndef SQLITE_OMIT_FOREIGN_KEY
70180/* Opcode: FkCounter P1 P2 * * *
70181**
70182** Increment a "constraint counter" by P2 (P2 may be negative or positive).
70183** If P1 is non-zero, the database constraint counter is incremented
70184** (deferred foreign key constraints). Otherwise, if P1 is zero, the
70185** statement counter is incremented (immediate foreign key constraints).
70186*/
70187case OP_FkCounter: {
70188  if( pOp->p1 ){
70189    db->nDeferredCons += pOp->p2;
70190  }else{
70191    p->nFkConstraint += pOp->p2;
70192  }
70193  break;
70194}
70195
70196/* Opcode: FkIfZero P1 P2 * * *
70197**
70198** This opcode tests if a foreign key constraint-counter is currently zero.
70199** If so, jump to instruction P2. Otherwise, fall through to the next
70200** instruction.
70201**
70202** If P1 is non-zero, then the jump is taken if the database constraint-counter
70203** is zero (the one that counts deferred constraint violations). If P1 is
70204** zero, the jump is taken if the statement constraint-counter is zero
70205** (immediate foreign key constraint violations).
70206*/
70207case OP_FkIfZero: {         /* jump */
70208  if( pOp->p1 ){
70209    if( db->nDeferredCons==0 ) pc = pOp->p2-1;
70210  }else{
70211    if( p->nFkConstraint==0 ) pc = pOp->p2-1;
70212  }
70213  break;
70214}
70215#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
70216
70217#ifndef SQLITE_OMIT_AUTOINCREMENT
70218/* Opcode: MemMax P1 P2 * * *
70219**
70220** P1 is a register in the root frame of this VM (the root frame is
70221** different from the current frame if this instruction is being executed
70222** within a sub-program). Set the value of register P1 to the maximum of
70223** its current value and the value in register P2.
70224**
70225** This instruction throws an error if the memory cell is not initially
70226** an integer.
70227*/
70228case OP_MemMax: {        /* in2 */
70229#if 0  /* local variables moved into u.ce */
70230  Mem *pIn1;
70231  VdbeFrame *pFrame;
70232#endif /* local variables moved into u.ce */
70233  if( p->pFrame ){
70234    for(u.ce.pFrame=p->pFrame; u.ce.pFrame->pParent; u.ce.pFrame=u.ce.pFrame->pParent);
70235    u.ce.pIn1 = &u.ce.pFrame->aMem[pOp->p1];
70236  }else{
70237    u.ce.pIn1 = &aMem[pOp->p1];
70238  }
70239  assert( memIsValid(u.ce.pIn1) );
70240  sqlite3VdbeMemIntegerify(u.ce.pIn1);
70241  pIn2 = &aMem[pOp->p2];
70242  sqlite3VdbeMemIntegerify(pIn2);
70243  if( u.ce.pIn1->u.i<pIn2->u.i){
70244    u.ce.pIn1->u.i = pIn2->u.i;
70245  }
70246  break;
70247}
70248#endif /* SQLITE_OMIT_AUTOINCREMENT */
70249
70250/* Opcode: IfPos P1 P2 * * *
70251**
70252** If the value of register P1 is 1 or greater, jump to P2.
70253**
70254** It is illegal to use this instruction on a register that does
70255** not contain an integer.  An assertion fault will result if you try.
70256*/
70257case OP_IfPos: {        /* jump, in1 */
70258  pIn1 = &aMem[pOp->p1];
70259  assert( pIn1->flags&MEM_Int );
70260  if( pIn1->u.i>0 ){
70261     pc = pOp->p2 - 1;
70262  }
70263  break;
70264}
70265
70266/* Opcode: IfNeg P1 P2 * * *
70267**
70268** If the value of register P1 is less than zero, jump to P2.
70269**
70270** It is illegal to use this instruction on a register that does
70271** not contain an integer.  An assertion fault will result if you try.
70272*/
70273case OP_IfNeg: {        /* jump, in1 */
70274  pIn1 = &aMem[pOp->p1];
70275  assert( pIn1->flags&MEM_Int );
70276  if( pIn1->u.i<0 ){
70277     pc = pOp->p2 - 1;
70278  }
70279  break;
70280}
70281
70282/* Opcode: IfZero P1 P2 P3 * *
70283**
70284** The register P1 must contain an integer.  Add literal P3 to the
70285** value in register P1.  If the result is exactly 0, jump to P2.
70286**
70287** It is illegal to use this instruction on a register that does
70288** not contain an integer.  An assertion fault will result if you try.
70289*/
70290case OP_IfZero: {        /* jump, in1 */
70291  pIn1 = &aMem[pOp->p1];
70292  assert( pIn1->flags&MEM_Int );
70293  pIn1->u.i += pOp->p3;
70294  if( pIn1->u.i==0 ){
70295     pc = pOp->p2 - 1;
70296  }
70297  break;
70298}
70299
70300/* Opcode: AggStep * P2 P3 P4 P5
70301**
70302** Execute the step function for an aggregate.  The
70303** function has P5 arguments.   P4 is a pointer to the FuncDef
70304** structure that specifies the function.  Use register
70305** P3 as the accumulator.
70306**
70307** The P5 arguments are taken from register P2 and its
70308** successors.
70309*/
70310case OP_AggStep: {
70311#if 0  /* local variables moved into u.cf */
70312  int n;
70313  int i;
70314  Mem *pMem;
70315  Mem *pRec;
70316  sqlite3_context ctx;
70317  sqlite3_value **apVal;
70318#endif /* local variables moved into u.cf */
70319
70320  u.cf.n = pOp->p5;
70321  assert( u.cf.n>=0 );
70322  u.cf.pRec = &aMem[pOp->p2];
70323  u.cf.apVal = p->apArg;
70324  assert( u.cf.apVal || u.cf.n==0 );
70325  for(u.cf.i=0; u.cf.i<u.cf.n; u.cf.i++, u.cf.pRec++){
70326    assert( memIsValid(u.cf.pRec) );
70327    u.cf.apVal[u.cf.i] = u.cf.pRec;
70328    memAboutToChange(p, u.cf.pRec);
70329    sqlite3VdbeMemStoreType(u.cf.pRec);
70330  }
70331  u.cf.ctx.pFunc = pOp->p4.pFunc;
70332  assert( pOp->p3>0 && pOp->p3<=p->nMem );
70333  u.cf.ctx.pMem = u.cf.pMem = &aMem[pOp->p3];
70334  u.cf.pMem->n++;
70335  u.cf.ctx.s.flags = MEM_Null;
70336  u.cf.ctx.s.z = 0;
70337  u.cf.ctx.s.zMalloc = 0;
70338  u.cf.ctx.s.xDel = 0;
70339  u.cf.ctx.s.db = db;
70340  u.cf.ctx.isError = 0;
70341  u.cf.ctx.pColl = 0;
70342  u.cf.ctx.skipFlag = 0;
70343  if( u.cf.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
70344    assert( pOp>p->aOp );
70345    assert( pOp[-1].p4type==P4_COLLSEQ );
70346    assert( pOp[-1].opcode==OP_CollSeq );
70347    u.cf.ctx.pColl = pOp[-1].p4.pColl;
70348  }
70349  (u.cf.ctx.pFunc->xStep)(&u.cf.ctx, u.cf.n, u.cf.apVal); /* IMP: R-24505-23230 */
70350  if( u.cf.ctx.isError ){
70351    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cf.ctx.s));
70352    rc = u.cf.ctx.isError;
70353  }
70354  if( u.cf.ctx.skipFlag ){
70355    assert( pOp[-1].opcode==OP_CollSeq );
70356    u.cf.i = pOp[-1].p1;
70357    if( u.cf.i ) sqlite3VdbeMemSetInt64(&aMem[u.cf.i], 1);
70358  }
70359
70360  sqlite3VdbeMemRelease(&u.cf.ctx.s);
70361
70362  break;
70363}
70364
70365/* Opcode: AggFinal P1 P2 * P4 *
70366**
70367** Execute the finalizer function for an aggregate.  P1 is
70368** the memory location that is the accumulator for the aggregate.
70369**
70370** P2 is the number of arguments that the step function takes and
70371** P4 is a pointer to the FuncDef for this function.  The P2
70372** argument is not used by this opcode.  It is only there to disambiguate
70373** functions that can take varying numbers of arguments.  The
70374** P4 argument is only needed for the degenerate case where
70375** the step function was not previously called.
70376*/
70377case OP_AggFinal: {
70378#if 0  /* local variables moved into u.cg */
70379  Mem *pMem;
70380#endif /* local variables moved into u.cg */
70381  assert( pOp->p1>0 && pOp->p1<=p->nMem );
70382  u.cg.pMem = &aMem[pOp->p1];
70383  assert( (u.cg.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
70384  rc = sqlite3VdbeMemFinalize(u.cg.pMem, pOp->p4.pFunc);
70385  if( rc ){
70386    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cg.pMem));
70387  }
70388  sqlite3VdbeChangeEncoding(u.cg.pMem, encoding);
70389  UPDATE_MAX_BLOBSIZE(u.cg.pMem);
70390  if( sqlite3VdbeMemTooBig(u.cg.pMem) ){
70391    goto too_big;
70392  }
70393  break;
70394}
70395
70396#ifndef SQLITE_OMIT_WAL
70397/* Opcode: Checkpoint P1 P2 P3 * *
70398**
70399** Checkpoint database P1. This is a no-op if P1 is not currently in
70400** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
70401** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
70402** SQLITE_BUSY or not, respectively.  Write the number of pages in the
70403** WAL after the checkpoint into mem[P3+1] and the number of pages
70404** in the WAL that have been checkpointed after the checkpoint
70405** completes into mem[P3+2].  However on an error, mem[P3+1] and
70406** mem[P3+2] are initialized to -1.
70407*/
70408case OP_Checkpoint: {
70409#if 0  /* local variables moved into u.ch */
70410  int i;                          /* Loop counter */
70411  int aRes[3];                    /* Results */
70412  Mem *pMem;                      /* Write results here */
70413#endif /* local variables moved into u.ch */
70414
70415  u.ch.aRes[0] = 0;
70416  u.ch.aRes[1] = u.ch.aRes[2] = -1;
70417  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
70418       || pOp->p2==SQLITE_CHECKPOINT_FULL
70419       || pOp->p2==SQLITE_CHECKPOINT_RESTART
70420  );
70421  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ch.aRes[1], &u.ch.aRes[2]);
70422  if( rc==SQLITE_BUSY ){
70423    rc = SQLITE_OK;
70424    u.ch.aRes[0] = 1;
70425  }
70426  for(u.ch.i=0, u.ch.pMem = &aMem[pOp->p3]; u.ch.i<3; u.ch.i++, u.ch.pMem++){
70427    sqlite3VdbeMemSetInt64(u.ch.pMem, (i64)u.ch.aRes[u.ch.i]);
70428  }
70429  break;
70430};
70431#endif
70432
70433#ifndef SQLITE_OMIT_PRAGMA
70434/* Opcode: JournalMode P1 P2 P3 * P5
70435**
70436** Change the journal mode of database P1 to P3. P3 must be one of the
70437** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
70438** modes (delete, truncate, persist, off and memory), this is a simple
70439** operation. No IO is required.
70440**
70441** If changing into or out of WAL mode the procedure is more complicated.
70442**
70443** Write a string containing the final journal-mode to register P2.
70444*/
70445case OP_JournalMode: {    /* out2-prerelease */
70446#if 0  /* local variables moved into u.ci */
70447  Btree *pBt;                     /* Btree to change journal mode of */
70448  Pager *pPager;                  /* Pager associated with pBt */
70449  int eNew;                       /* New journal mode */
70450  int eOld;                       /* The old journal mode */
70451  const char *zFilename;          /* Name of database file for pPager */
70452#endif /* local variables moved into u.ci */
70453
70454  u.ci.eNew = pOp->p3;
70455  assert( u.ci.eNew==PAGER_JOURNALMODE_DELETE
70456       || u.ci.eNew==PAGER_JOURNALMODE_TRUNCATE
70457       || u.ci.eNew==PAGER_JOURNALMODE_PERSIST
70458       || u.ci.eNew==PAGER_JOURNALMODE_OFF
70459       || u.ci.eNew==PAGER_JOURNALMODE_MEMORY
70460       || u.ci.eNew==PAGER_JOURNALMODE_WAL
70461       || u.ci.eNew==PAGER_JOURNALMODE_QUERY
70462  );
70463  assert( pOp->p1>=0 && pOp->p1<db->nDb );
70464
70465  u.ci.pBt = db->aDb[pOp->p1].pBt;
70466  u.ci.pPager = sqlite3BtreePager(u.ci.pBt);
70467  u.ci.eOld = sqlite3PagerGetJournalMode(u.ci.pPager);
70468  if( u.ci.eNew==PAGER_JOURNALMODE_QUERY ) u.ci.eNew = u.ci.eOld;
70469  if( !sqlite3PagerOkToChangeJournalMode(u.ci.pPager) ) u.ci.eNew = u.ci.eOld;
70470
70471#ifndef SQLITE_OMIT_WAL
70472  u.ci.zFilename = sqlite3PagerFilename(u.ci.pPager);
70473
70474  /* Do not allow a transition to journal_mode=WAL for a database
70475  ** in temporary storage or if the VFS does not support shared memory
70476  */
70477  if( u.ci.eNew==PAGER_JOURNALMODE_WAL
70478   && (sqlite3Strlen30(u.ci.zFilename)==0           /* Temp file */
70479       || !sqlite3PagerWalSupported(u.ci.pPager))   /* No shared-memory support */
70480  ){
70481    u.ci.eNew = u.ci.eOld;
70482  }
70483
70484  if( (u.ci.eNew!=u.ci.eOld)
70485   && (u.ci.eOld==PAGER_JOURNALMODE_WAL || u.ci.eNew==PAGER_JOURNALMODE_WAL)
70486  ){
70487    if( !db->autoCommit || db->activeVdbeCnt>1 ){
70488      rc = SQLITE_ERROR;
70489      sqlite3SetString(&p->zErrMsg, db,
70490          "cannot change %s wal mode from within a transaction",
70491          (u.ci.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
70492      );
70493      break;
70494    }else{
70495
70496      if( u.ci.eOld==PAGER_JOURNALMODE_WAL ){
70497        /* If leaving WAL mode, close the log file. If successful, the call
70498        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
70499        ** file. An EXCLUSIVE lock may still be held on the database file
70500        ** after a successful return.
70501        */
70502        rc = sqlite3PagerCloseWal(u.ci.pPager);
70503        if( rc==SQLITE_OK ){
70504          sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
70505        }
70506      }else if( u.ci.eOld==PAGER_JOURNALMODE_MEMORY ){
70507        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
70508        ** as an intermediate */
70509        sqlite3PagerSetJournalMode(u.ci.pPager, PAGER_JOURNALMODE_OFF);
70510      }
70511
70512      /* Open a transaction on the database file. Regardless of the journal
70513      ** mode, this transaction always uses a rollback journal.
70514      */
70515      assert( sqlite3BtreeIsInTrans(u.ci.pBt)==0 );
70516      if( rc==SQLITE_OK ){
70517        rc = sqlite3BtreeSetVersion(u.ci.pBt, (u.ci.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
70518      }
70519    }
70520  }
70521#endif /* ifndef SQLITE_OMIT_WAL */
70522
70523  if( rc ){
70524    u.ci.eNew = u.ci.eOld;
70525  }
70526  u.ci.eNew = sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
70527
70528  pOut = &aMem[pOp->p2];
70529  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
70530  pOut->z = (char *)sqlite3JournalModename(u.ci.eNew);
70531  pOut->n = sqlite3Strlen30(pOut->z);
70532  pOut->enc = SQLITE_UTF8;
70533  sqlite3VdbeChangeEncoding(pOut, encoding);
70534  break;
70535};
70536#endif /* SQLITE_OMIT_PRAGMA */
70537
70538#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
70539/* Opcode: Vacuum * * * * *
70540**
70541** Vacuum the entire database.  This opcode will cause other virtual
70542** machines to be created and run.  It may not be called from within
70543** a transaction.
70544*/
70545case OP_Vacuum: {
70546  rc = sqlite3RunVacuum(&p->zErrMsg, db);
70547  break;
70548}
70549#endif
70550
70551#if !defined(SQLITE_OMIT_AUTOVACUUM)
70552/* Opcode: IncrVacuum P1 P2 * * *
70553**
70554** Perform a single step of the incremental vacuum procedure on
70555** the P1 database. If the vacuum has finished, jump to instruction
70556** P2. Otherwise, fall through to the next instruction.
70557*/
70558case OP_IncrVacuum: {        /* jump */
70559#if 0  /* local variables moved into u.cj */
70560  Btree *pBt;
70561#endif /* local variables moved into u.cj */
70562
70563  assert( pOp->p1>=0 && pOp->p1<db->nDb );
70564  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
70565  u.cj.pBt = db->aDb[pOp->p1].pBt;
70566  rc = sqlite3BtreeIncrVacuum(u.cj.pBt);
70567  if( rc==SQLITE_DONE ){
70568    pc = pOp->p2 - 1;
70569    rc = SQLITE_OK;
70570  }
70571  break;
70572}
70573#endif
70574
70575/* Opcode: Expire P1 * * * *
70576**
70577** Cause precompiled statements to become expired. An expired statement
70578** fails with an error code of SQLITE_SCHEMA if it is ever executed
70579** (via sqlite3_step()).
70580**
70581** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
70582** then only the currently executing statement is affected.
70583*/
70584case OP_Expire: {
70585  if( !pOp->p1 ){
70586    sqlite3ExpirePreparedStatements(db);
70587  }else{
70588    p->expired = 1;
70589  }
70590  break;
70591}
70592
70593#ifndef SQLITE_OMIT_SHARED_CACHE
70594/* Opcode: TableLock P1 P2 P3 P4 *
70595**
70596** Obtain a lock on a particular table. This instruction is only used when
70597** the shared-cache feature is enabled.
70598**
70599** P1 is the index of the database in sqlite3.aDb[] of the database
70600** on which the lock is acquired.  A readlock is obtained if P3==0 or
70601** a write lock if P3==1.
70602**
70603** P2 contains the root-page of the table to lock.
70604**
70605** P4 contains a pointer to the name of the table being locked. This is only
70606** used to generate an error message if the lock cannot be obtained.
70607*/
70608case OP_TableLock: {
70609  u8 isWriteLock = (u8)pOp->p3;
70610  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
70611    int p1 = pOp->p1;
70612    assert( p1>=0 && p1<db->nDb );
70613    assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
70614    assert( isWriteLock==0 || isWriteLock==1 );
70615    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
70616    if( (rc&0xFF)==SQLITE_LOCKED ){
70617      const char *z = pOp->p4.z;
70618      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
70619    }
70620  }
70621  break;
70622}
70623#endif /* SQLITE_OMIT_SHARED_CACHE */
70624
70625#ifndef SQLITE_OMIT_VIRTUALTABLE
70626/* Opcode: VBegin * * * P4 *
70627**
70628** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
70629** xBegin method for that table.
70630**
70631** Also, whether or not P4 is set, check that this is not being called from
70632** within a callback to a virtual table xSync() method. If it is, the error
70633** code will be set to SQLITE_LOCKED.
70634*/
70635case OP_VBegin: {
70636#if 0  /* local variables moved into u.ck */
70637  VTable *pVTab;
70638#endif /* local variables moved into u.ck */
70639  u.ck.pVTab = pOp->p4.pVtab;
70640  rc = sqlite3VtabBegin(db, u.ck.pVTab);
70641  if( u.ck.pVTab ) importVtabErrMsg(p, u.ck.pVTab->pVtab);
70642  break;
70643}
70644#endif /* SQLITE_OMIT_VIRTUALTABLE */
70645
70646#ifndef SQLITE_OMIT_VIRTUALTABLE
70647/* Opcode: VCreate P1 * * P4 *
70648**
70649** P4 is the name of a virtual table in database P1. Call the xCreate method
70650** for that table.
70651*/
70652case OP_VCreate: {
70653  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
70654  break;
70655}
70656#endif /* SQLITE_OMIT_VIRTUALTABLE */
70657
70658#ifndef SQLITE_OMIT_VIRTUALTABLE
70659/* Opcode: VDestroy P1 * * P4 *
70660**
70661** P4 is the name of a virtual table in database P1.  Call the xDestroy method
70662** of that table.
70663*/
70664case OP_VDestroy: {
70665  p->inVtabMethod = 2;
70666  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
70667  p->inVtabMethod = 0;
70668  break;
70669}
70670#endif /* SQLITE_OMIT_VIRTUALTABLE */
70671
70672#ifndef SQLITE_OMIT_VIRTUALTABLE
70673/* Opcode: VOpen P1 * * P4 *
70674**
70675** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70676** P1 is a cursor number.  This opcode opens a cursor to the virtual
70677** table and stores that cursor in P1.
70678*/
70679case OP_VOpen: {
70680#if 0  /* local variables moved into u.cl */
70681  VdbeCursor *pCur;
70682  sqlite3_vtab_cursor *pVtabCursor;
70683  sqlite3_vtab *pVtab;
70684  sqlite3_module *pModule;
70685#endif /* local variables moved into u.cl */
70686
70687  u.cl.pCur = 0;
70688  u.cl.pVtabCursor = 0;
70689  u.cl.pVtab = pOp->p4.pVtab->pVtab;
70690  u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
70691  assert(u.cl.pVtab && u.cl.pModule);
70692  rc = u.cl.pModule->xOpen(u.cl.pVtab, &u.cl.pVtabCursor);
70693  importVtabErrMsg(p, u.cl.pVtab);
70694  if( SQLITE_OK==rc ){
70695    /* Initialize sqlite3_vtab_cursor base class */
70696    u.cl.pVtabCursor->pVtab = u.cl.pVtab;
70697
70698    /* Initialise vdbe cursor object */
70699    u.cl.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
70700    if( u.cl.pCur ){
70701      u.cl.pCur->pVtabCursor = u.cl.pVtabCursor;
70702      u.cl.pCur->pModule = u.cl.pVtabCursor->pVtab->pModule;
70703    }else{
70704      db->mallocFailed = 1;
70705      u.cl.pModule->xClose(u.cl.pVtabCursor);
70706    }
70707  }
70708  break;
70709}
70710#endif /* SQLITE_OMIT_VIRTUALTABLE */
70711
70712#ifndef SQLITE_OMIT_VIRTUALTABLE
70713/* Opcode: VFilter P1 P2 P3 P4 *
70714**
70715** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
70716** the filtered result set is empty.
70717**
70718** P4 is either NULL or a string that was generated by the xBestIndex
70719** method of the module.  The interpretation of the P4 string is left
70720** to the module implementation.
70721**
70722** This opcode invokes the xFilter method on the virtual table specified
70723** by P1.  The integer query plan parameter to xFilter is stored in register
70724** P3. Register P3+1 stores the argc parameter to be passed to the
70725** xFilter method. Registers P3+2..P3+1+argc are the argc
70726** additional parameters which are passed to
70727** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
70728**
70729** A jump is made to P2 if the result set after filtering would be empty.
70730*/
70731case OP_VFilter: {   /* jump */
70732#if 0  /* local variables moved into u.cm */
70733  int nArg;
70734  int iQuery;
70735  const sqlite3_module *pModule;
70736  Mem *pQuery;
70737  Mem *pArgc;
70738  sqlite3_vtab_cursor *pVtabCursor;
70739  sqlite3_vtab *pVtab;
70740  VdbeCursor *pCur;
70741  int res;
70742  int i;
70743  Mem **apArg;
70744#endif /* local variables moved into u.cm */
70745
70746  u.cm.pQuery = &aMem[pOp->p3];
70747  u.cm.pArgc = &u.cm.pQuery[1];
70748  u.cm.pCur = p->apCsr[pOp->p1];
70749  assert( memIsValid(u.cm.pQuery) );
70750  REGISTER_TRACE(pOp->p3, u.cm.pQuery);
70751  assert( u.cm.pCur->pVtabCursor );
70752  u.cm.pVtabCursor = u.cm.pCur->pVtabCursor;
70753  u.cm.pVtab = u.cm.pVtabCursor->pVtab;
70754  u.cm.pModule = u.cm.pVtab->pModule;
70755
70756  /* Grab the index number and argc parameters */
70757  assert( (u.cm.pQuery->flags&MEM_Int)!=0 && u.cm.pArgc->flags==MEM_Int );
70758  u.cm.nArg = (int)u.cm.pArgc->u.i;
70759  u.cm.iQuery = (int)u.cm.pQuery->u.i;
70760
70761  /* Invoke the xFilter method */
70762  {
70763    u.cm.res = 0;
70764    u.cm.apArg = p->apArg;
70765    for(u.cm.i = 0; u.cm.i<u.cm.nArg; u.cm.i++){
70766      u.cm.apArg[u.cm.i] = &u.cm.pArgc[u.cm.i+1];
70767      sqlite3VdbeMemStoreType(u.cm.apArg[u.cm.i]);
70768    }
70769
70770    p->inVtabMethod = 1;
70771    rc = u.cm.pModule->xFilter(u.cm.pVtabCursor, u.cm.iQuery, pOp->p4.z, u.cm.nArg, u.cm.apArg);
70772    p->inVtabMethod = 0;
70773    importVtabErrMsg(p, u.cm.pVtab);
70774    if( rc==SQLITE_OK ){
70775      u.cm.res = u.cm.pModule->xEof(u.cm.pVtabCursor);
70776    }
70777
70778    if( u.cm.res ){
70779      pc = pOp->p2 - 1;
70780    }
70781  }
70782  u.cm.pCur->nullRow = 0;
70783
70784  break;
70785}
70786#endif /* SQLITE_OMIT_VIRTUALTABLE */
70787
70788#ifndef SQLITE_OMIT_VIRTUALTABLE
70789/* Opcode: VColumn P1 P2 P3 * *
70790**
70791** Store the value of the P2-th column of
70792** the row of the virtual-table that the
70793** P1 cursor is pointing to into register P3.
70794*/
70795case OP_VColumn: {
70796#if 0  /* local variables moved into u.cn */
70797  sqlite3_vtab *pVtab;
70798  const sqlite3_module *pModule;
70799  Mem *pDest;
70800  sqlite3_context sContext;
70801#endif /* local variables moved into u.cn */
70802
70803  VdbeCursor *pCur = p->apCsr[pOp->p1];
70804  assert( pCur->pVtabCursor );
70805  assert( pOp->p3>0 && pOp->p3<=p->nMem );
70806  u.cn.pDest = &aMem[pOp->p3];
70807  memAboutToChange(p, u.cn.pDest);
70808  if( pCur->nullRow ){
70809    sqlite3VdbeMemSetNull(u.cn.pDest);
70810    break;
70811  }
70812  u.cn.pVtab = pCur->pVtabCursor->pVtab;
70813  u.cn.pModule = u.cn.pVtab->pModule;
70814  assert( u.cn.pModule->xColumn );
70815  memset(&u.cn.sContext, 0, sizeof(u.cn.sContext));
70816
70817  /* The output cell may already have a buffer allocated. Move
70818  ** the current contents to u.cn.sContext.s so in case the user-function
70819  ** can use the already allocated buffer instead of allocating a
70820  ** new one.
70821  */
70822  sqlite3VdbeMemMove(&u.cn.sContext.s, u.cn.pDest);
70823  MemSetTypeFlag(&u.cn.sContext.s, MEM_Null);
70824
70825  rc = u.cn.pModule->xColumn(pCur->pVtabCursor, &u.cn.sContext, pOp->p2);
70826  importVtabErrMsg(p, u.cn.pVtab);
70827  if( u.cn.sContext.isError ){
70828    rc = u.cn.sContext.isError;
70829  }
70830
70831  /* Copy the result of the function to the P3 register. We
70832  ** do this regardless of whether or not an error occurred to ensure any
70833  ** dynamic allocation in u.cn.sContext.s (a Mem struct) is  released.
70834  */
70835  sqlite3VdbeChangeEncoding(&u.cn.sContext.s, encoding);
70836  sqlite3VdbeMemMove(u.cn.pDest, &u.cn.sContext.s);
70837  REGISTER_TRACE(pOp->p3, u.cn.pDest);
70838  UPDATE_MAX_BLOBSIZE(u.cn.pDest);
70839
70840  if( sqlite3VdbeMemTooBig(u.cn.pDest) ){
70841    goto too_big;
70842  }
70843  break;
70844}
70845#endif /* SQLITE_OMIT_VIRTUALTABLE */
70846
70847#ifndef SQLITE_OMIT_VIRTUALTABLE
70848/* Opcode: VNext P1 P2 * * *
70849**
70850** Advance virtual table P1 to the next row in its result set and
70851** jump to instruction P2.  Or, if the virtual table has reached
70852** the end of its result set, then fall through to the next instruction.
70853*/
70854case OP_VNext: {   /* jump */
70855#if 0  /* local variables moved into u.co */
70856  sqlite3_vtab *pVtab;
70857  const sqlite3_module *pModule;
70858  int res;
70859  VdbeCursor *pCur;
70860#endif /* local variables moved into u.co */
70861
70862  u.co.res = 0;
70863  u.co.pCur = p->apCsr[pOp->p1];
70864  assert( u.co.pCur->pVtabCursor );
70865  if( u.co.pCur->nullRow ){
70866    break;
70867  }
70868  u.co.pVtab = u.co.pCur->pVtabCursor->pVtab;
70869  u.co.pModule = u.co.pVtab->pModule;
70870  assert( u.co.pModule->xNext );
70871
70872  /* Invoke the xNext() method of the module. There is no way for the
70873  ** underlying implementation to return an error if one occurs during
70874  ** xNext(). Instead, if an error occurs, true is returned (indicating that
70875  ** data is available) and the error code returned when xColumn or
70876  ** some other method is next invoked on the save virtual table cursor.
70877  */
70878  p->inVtabMethod = 1;
70879  rc = u.co.pModule->xNext(u.co.pCur->pVtabCursor);
70880  p->inVtabMethod = 0;
70881  importVtabErrMsg(p, u.co.pVtab);
70882  if( rc==SQLITE_OK ){
70883    u.co.res = u.co.pModule->xEof(u.co.pCur->pVtabCursor);
70884  }
70885
70886  if( !u.co.res ){
70887    /* If there is data, jump to P2 */
70888    pc = pOp->p2 - 1;
70889  }
70890  break;
70891}
70892#endif /* SQLITE_OMIT_VIRTUALTABLE */
70893
70894#ifndef SQLITE_OMIT_VIRTUALTABLE
70895/* Opcode: VRename P1 * * P4 *
70896**
70897** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70898** This opcode invokes the corresponding xRename method. The value
70899** in register P1 is passed as the zName argument to the xRename method.
70900*/
70901case OP_VRename: {
70902#if 0  /* local variables moved into u.cp */
70903  sqlite3_vtab *pVtab;
70904  Mem *pName;
70905#endif /* local variables moved into u.cp */
70906
70907  u.cp.pVtab = pOp->p4.pVtab->pVtab;
70908  u.cp.pName = &aMem[pOp->p1];
70909  assert( u.cp.pVtab->pModule->xRename );
70910  assert( memIsValid(u.cp.pName) );
70911  REGISTER_TRACE(pOp->p1, u.cp.pName);
70912  assert( u.cp.pName->flags & MEM_Str );
70913  testcase( u.cp.pName->enc==SQLITE_UTF8 );
70914  testcase( u.cp.pName->enc==SQLITE_UTF16BE );
70915  testcase( u.cp.pName->enc==SQLITE_UTF16LE );
70916  rc = sqlite3VdbeChangeEncoding(u.cp.pName, SQLITE_UTF8);
70917  if( rc==SQLITE_OK ){
70918    rc = u.cp.pVtab->pModule->xRename(u.cp.pVtab, u.cp.pName->z);
70919    importVtabErrMsg(p, u.cp.pVtab);
70920    p->expired = 0;
70921  }
70922  break;
70923}
70924#endif
70925
70926#ifndef SQLITE_OMIT_VIRTUALTABLE
70927/* Opcode: VUpdate P1 P2 P3 P4 *
70928**
70929** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70930** This opcode invokes the corresponding xUpdate method. P2 values
70931** are contiguous memory cells starting at P3 to pass to the xUpdate
70932** invocation. The value in register (P3+P2-1) corresponds to the
70933** p2th element of the argv array passed to xUpdate.
70934**
70935** The xUpdate method will do a DELETE or an INSERT or both.
70936** The argv[0] element (which corresponds to memory cell P3)
70937** is the rowid of a row to delete.  If argv[0] is NULL then no
70938** deletion occurs.  The argv[1] element is the rowid of the new
70939** row.  This can be NULL to have the virtual table select the new
70940** rowid for itself.  The subsequent elements in the array are
70941** the values of columns in the new row.
70942**
70943** If P2==1 then no insert is performed.  argv[0] is the rowid of
70944** a row to delete.
70945**
70946** P1 is a boolean flag. If it is set to true and the xUpdate call
70947** is successful, then the value returned by sqlite3_last_insert_rowid()
70948** is set to the value of the rowid for the row just inserted.
70949*/
70950case OP_VUpdate: {
70951#if 0  /* local variables moved into u.cq */
70952  sqlite3_vtab *pVtab;
70953  sqlite3_module *pModule;
70954  int nArg;
70955  int i;
70956  sqlite_int64 rowid;
70957  Mem **apArg;
70958  Mem *pX;
70959#endif /* local variables moved into u.cq */
70960
70961  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
70962       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
70963  );
70964  u.cq.pVtab = pOp->p4.pVtab->pVtab;
70965  u.cq.pModule = (sqlite3_module *)u.cq.pVtab->pModule;
70966  u.cq.nArg = pOp->p2;
70967  assert( pOp->p4type==P4_VTAB );
70968  if( ALWAYS(u.cq.pModule->xUpdate) ){
70969    u8 vtabOnConflict = db->vtabOnConflict;
70970    u.cq.apArg = p->apArg;
70971    u.cq.pX = &aMem[pOp->p3];
70972    for(u.cq.i=0; u.cq.i<u.cq.nArg; u.cq.i++){
70973      assert( memIsValid(u.cq.pX) );
70974      memAboutToChange(p, u.cq.pX);
70975      sqlite3VdbeMemStoreType(u.cq.pX);
70976      u.cq.apArg[u.cq.i] = u.cq.pX;
70977      u.cq.pX++;
70978    }
70979    db->vtabOnConflict = pOp->p5;
70980    rc = u.cq.pModule->xUpdate(u.cq.pVtab, u.cq.nArg, u.cq.apArg, &u.cq.rowid);
70981    db->vtabOnConflict = vtabOnConflict;
70982    importVtabErrMsg(p, u.cq.pVtab);
70983    if( rc==SQLITE_OK && pOp->p1 ){
70984      assert( u.cq.nArg>1 && u.cq.apArg[0] && (u.cq.apArg[0]->flags&MEM_Null) );
70985      db->lastRowid = lastRowid = u.cq.rowid;
70986    }
70987    if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
70988      if( pOp->p5==OE_Ignore ){
70989        rc = SQLITE_OK;
70990      }else{
70991        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
70992      }
70993    }else{
70994      p->nChange++;
70995    }
70996  }
70997  break;
70998}
70999#endif /* SQLITE_OMIT_VIRTUALTABLE */
71000
71001#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
71002/* Opcode: Pagecount P1 P2 * * *
71003**
71004** Write the current number of pages in database P1 to memory cell P2.
71005*/
71006case OP_Pagecount: {            /* out2-prerelease */
71007  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
71008  break;
71009}
71010#endif
71011
71012
71013#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
71014/* Opcode: MaxPgcnt P1 P2 P3 * *
71015**
71016** Try to set the maximum page count for database P1 to the value in P3.
71017** Do not let the maximum page count fall below the current page count and
71018** do not change the maximum page count value if P3==0.
71019**
71020** Store the maximum page count after the change in register P2.
71021*/
71022case OP_MaxPgcnt: {            /* out2-prerelease */
71023  unsigned int newMax;
71024  Btree *pBt;
71025
71026  pBt = db->aDb[pOp->p1].pBt;
71027  newMax = 0;
71028  if( pOp->p3 ){
71029    newMax = sqlite3BtreeLastPage(pBt);
71030    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
71031  }
71032  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
71033  break;
71034}
71035#endif
71036
71037
71038#ifndef SQLITE_OMIT_TRACE
71039/* Opcode: Trace * * * P4 *
71040**
71041** If tracing is enabled (by the sqlite3_trace()) interface, then
71042** the UTF-8 string contained in P4 is emitted on the trace callback.
71043*/
71044case OP_Trace: {
71045#if 0  /* local variables moved into u.cr */
71046  char *zTrace;
71047  char *z;
71048#endif /* local variables moved into u.cr */
71049
71050  if( db->xTrace && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){
71051    u.cr.z = sqlite3VdbeExpandSql(p, u.cr.zTrace);
71052    db->xTrace(db->pTraceArg, u.cr.z);
71053    sqlite3DbFree(db, u.cr.z);
71054  }
71055#ifdef SQLITE_DEBUG
71056  if( (db->flags & SQLITE_SqlTrace)!=0
71057   && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71058  ){
71059    sqlite3DebugPrintf("SQL-trace: %s\n", u.cr.zTrace);
71060  }
71061#endif /* SQLITE_DEBUG */
71062  break;
71063}
71064#endif
71065
71066
71067/* Opcode: Noop * * * * *
71068**
71069** Do nothing.  This instruction is often useful as a jump
71070** destination.
71071*/
71072/*
71073** The magic Explain opcode are only inserted when explain==2 (which
71074** is to say when the EXPLAIN QUERY PLAN syntax is used.)
71075** This opcode records information from the optimizer.  It is the
71076** the same as a no-op.  This opcodesnever appears in a real VM program.
71077*/
71078default: {          /* This is really OP_Noop and OP_Explain */
71079  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
71080  break;
71081}
71082
71083/*****************************************************************************
71084** The cases of the switch statement above this line should all be indented
71085** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
71086** readability.  From this point on down, the normal indentation rules are
71087** restored.
71088*****************************************************************************/
71089    }
71090
71091#ifdef VDBE_PROFILE
71092    {
71093      u64 elapsed = sqlite3Hwtime() - start;
71094      pOp->cycles += elapsed;
71095      pOp->cnt++;
71096#if 0
71097        fprintf(stdout, "%10llu ", elapsed);
71098        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
71099#endif
71100    }
71101#endif
71102
71103    /* The following code adds nothing to the actual functionality
71104    ** of the program.  It is only here for testing and debugging.
71105    ** On the other hand, it does burn CPU cycles every time through
71106    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
71107    */
71108#ifndef NDEBUG
71109    assert( pc>=-1 && pc<p->nOp );
71110
71111#ifdef SQLITE_DEBUG
71112    if( p->trace ){
71113      if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
71114      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
71115        registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
71116      }
71117      if( pOp->opflags & OPFLG_OUT3 ){
71118        registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
71119      }
71120    }
71121#endif  /* SQLITE_DEBUG */
71122#endif  /* NDEBUG */
71123  }  /* The end of the for(;;) loop the loops through opcodes */
71124
71125  /* If we reach this point, it means that execution is finished with
71126  ** an error of some kind.
71127  */
71128vdbe_error_halt:
71129  assert( rc );
71130  p->rc = rc;
71131  testcase( sqlite3GlobalConfig.xLog!=0 );
71132  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
71133                   pc, p->zSql, p->zErrMsg);
71134  sqlite3VdbeHalt(p);
71135  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
71136  rc = SQLITE_ERROR;
71137  if( resetSchemaOnFault>0 ){
71138    sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
71139  }
71140
71141  /* This is the only way out of this procedure.  We have to
71142  ** release the mutexes on btrees that were acquired at the
71143  ** top. */
71144vdbe_return:
71145  db->lastRowid = lastRowid;
71146  sqlite3VdbeLeave(p);
71147  return rc;
71148
71149  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
71150  ** is encountered.
71151  */
71152too_big:
71153  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
71154  rc = SQLITE_TOOBIG;
71155  goto vdbe_error_halt;
71156
71157  /* Jump to here if a malloc() fails.
71158  */
71159no_mem:
71160  db->mallocFailed = 1;
71161  sqlite3SetString(&p->zErrMsg, db, "out of memory");
71162  rc = SQLITE_NOMEM;
71163  goto vdbe_error_halt;
71164
71165  /* Jump to here for any other kind of fatal error.  The "rc" variable
71166  ** should hold the error number.
71167  */
71168abort_due_to_error:
71169  assert( p->zErrMsg==0 );
71170  if( db->mallocFailed ) rc = SQLITE_NOMEM;
71171  if( rc!=SQLITE_IOERR_NOMEM ){
71172    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
71173  }
71174  goto vdbe_error_halt;
71175
71176  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
71177  ** flag.
71178  */
71179abort_due_to_interrupt:
71180  assert( db->u1.isInterrupted );
71181  rc = SQLITE_INTERRUPT;
71182  p->rc = rc;
71183  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
71184  goto vdbe_error_halt;
71185}
71186
71187/************** End of vdbe.c ************************************************/
71188/************** Begin file vdbeblob.c ****************************************/
71189/*
71190** 2007 May 1
71191**
71192** The author disclaims copyright to this source code.  In place of
71193** a legal notice, here is a blessing:
71194**
71195**    May you do good and not evil.
71196**    May you find forgiveness for yourself and forgive others.
71197**    May you share freely, never taking more than you give.
71198**
71199*************************************************************************
71200**
71201** This file contains code used to implement incremental BLOB I/O.
71202*/
71203
71204
71205#ifndef SQLITE_OMIT_INCRBLOB
71206
71207/*
71208** Valid sqlite3_blob* handles point to Incrblob structures.
71209*/
71210typedef struct Incrblob Incrblob;
71211struct Incrblob {
71212  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
71213  int nByte;              /* Size of open blob, in bytes */
71214  int iOffset;            /* Byte offset of blob in cursor data */
71215  int iCol;               /* Table column this handle is open on */
71216  BtCursor *pCsr;         /* Cursor pointing at blob row */
71217  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
71218  sqlite3 *db;            /* The associated database */
71219};
71220
71221
71222/*
71223** This function is used by both blob_open() and blob_reopen(). It seeks
71224** the b-tree cursor associated with blob handle p to point to row iRow.
71225** If successful, SQLITE_OK is returned and subsequent calls to
71226** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
71227**
71228** If an error occurs, or if the specified row does not exist or does not
71229** contain a value of type TEXT or BLOB in the column nominated when the
71230** blob handle was opened, then an error code is returned and *pzErr may
71231** be set to point to a buffer containing an error message. It is the
71232** responsibility of the caller to free the error message buffer using
71233** sqlite3DbFree().
71234**
71235** If an error does occur, then the b-tree cursor is closed. All subsequent
71236** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
71237** immediately return SQLITE_ABORT.
71238*/
71239static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
71240  int rc;                         /* Error code */
71241  char *zErr = 0;                 /* Error message */
71242  Vdbe *v = (Vdbe *)p->pStmt;
71243
71244  /* Set the value of the SQL statements only variable to integer iRow.
71245  ** This is done directly instead of using sqlite3_bind_int64() to avoid
71246  ** triggering asserts related to mutexes.
71247  */
71248  assert( v->aVar[0].flags&MEM_Int );
71249  v->aVar[0].u.i = iRow;
71250
71251  rc = sqlite3_step(p->pStmt);
71252  if( rc==SQLITE_ROW ){
71253    u32 type = v->apCsr[0]->aType[p->iCol];
71254    if( type<12 ){
71255      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
71256          type==0?"null": type==7?"real": "integer"
71257      );
71258      rc = SQLITE_ERROR;
71259      sqlite3_finalize(p->pStmt);
71260      p->pStmt = 0;
71261    }else{
71262      p->iOffset = v->apCsr[0]->aOffset[p->iCol];
71263      p->nByte = sqlite3VdbeSerialTypeLen(type);
71264      p->pCsr =  v->apCsr[0]->pCursor;
71265      sqlite3BtreeEnterCursor(p->pCsr);
71266      sqlite3BtreeCacheOverflow(p->pCsr);
71267      sqlite3BtreeLeaveCursor(p->pCsr);
71268    }
71269  }
71270
71271  if( rc==SQLITE_ROW ){
71272    rc = SQLITE_OK;
71273  }else if( p->pStmt ){
71274    rc = sqlite3_finalize(p->pStmt);
71275    p->pStmt = 0;
71276    if( rc==SQLITE_OK ){
71277      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
71278      rc = SQLITE_ERROR;
71279    }else{
71280      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
71281    }
71282  }
71283
71284  assert( rc!=SQLITE_OK || zErr==0 );
71285  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
71286
71287  *pzErr = zErr;
71288  return rc;
71289}
71290
71291/*
71292** Open a blob handle.
71293*/
71294SQLITE_API int sqlite3_blob_open(
71295  sqlite3* db,            /* The database connection */
71296  const char *zDb,        /* The attached database containing the blob */
71297  const char *zTable,     /* The table containing the blob */
71298  const char *zColumn,    /* The column containing the blob */
71299  sqlite_int64 iRow,      /* The row containing the glob */
71300  int flags,              /* True -> read/write access, false -> read-only */
71301  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
71302){
71303  int nAttempt = 0;
71304  int iCol;               /* Index of zColumn in row-record */
71305
71306  /* This VDBE program seeks a btree cursor to the identified
71307  ** db/table/row entry. The reason for using a vdbe program instead
71308  ** of writing code to use the b-tree layer directly is that the
71309  ** vdbe program will take advantage of the various transaction,
71310  ** locking and error handling infrastructure built into the vdbe.
71311  **
71312  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
71313  ** Code external to the Vdbe then "borrows" the b-tree cursor and
71314  ** uses it to implement the blob_read(), blob_write() and
71315  ** blob_bytes() functions.
71316  **
71317  ** The sqlite3_blob_close() function finalizes the vdbe program,
71318  ** which closes the b-tree cursor and (possibly) commits the
71319  ** transaction.
71320  */
71321  static const VdbeOpList openBlob[] = {
71322    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
71323    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
71324    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
71325
71326    /* One of the following two instructions is replaced by an OP_Noop. */
71327    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
71328    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
71329
71330    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
71331    {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
71332    {OP_Column, 0, 0, 1},          /* 7  */
71333    {OP_ResultRow, 1, 0, 0},       /* 8  */
71334    {OP_Goto, 0, 5, 0},            /* 9  */
71335    {OP_Close, 0, 0, 0},           /* 10 */
71336    {OP_Halt, 0, 0, 0},            /* 11 */
71337  };
71338
71339  int rc = SQLITE_OK;
71340  char *zErr = 0;
71341  Table *pTab;
71342  Parse *pParse = 0;
71343  Incrblob *pBlob = 0;
71344
71345  flags = !!flags;                /* flags = (flags ? 1 : 0); */
71346  *ppBlob = 0;
71347
71348  sqlite3_mutex_enter(db->mutex);
71349
71350  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
71351  if( !pBlob ) goto blob_open_out;
71352  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
71353  if( !pParse ) goto blob_open_out;
71354
71355  do {
71356    memset(pParse, 0, sizeof(Parse));
71357    pParse->db = db;
71358    sqlite3DbFree(db, zErr);
71359    zErr = 0;
71360
71361    sqlite3BtreeEnterAll(db);
71362    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
71363    if( pTab && IsVirtual(pTab) ){
71364      pTab = 0;
71365      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
71366    }
71367#ifndef SQLITE_OMIT_VIEW
71368    if( pTab && pTab->pSelect ){
71369      pTab = 0;
71370      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
71371    }
71372#endif
71373    if( !pTab ){
71374      if( pParse->zErrMsg ){
71375        sqlite3DbFree(db, zErr);
71376        zErr = pParse->zErrMsg;
71377        pParse->zErrMsg = 0;
71378      }
71379      rc = SQLITE_ERROR;
71380      sqlite3BtreeLeaveAll(db);
71381      goto blob_open_out;
71382    }
71383
71384    /* Now search pTab for the exact column. */
71385    for(iCol=0; iCol<pTab->nCol; iCol++) {
71386      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
71387        break;
71388      }
71389    }
71390    if( iCol==pTab->nCol ){
71391      sqlite3DbFree(db, zErr);
71392      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
71393      rc = SQLITE_ERROR;
71394      sqlite3BtreeLeaveAll(db);
71395      goto blob_open_out;
71396    }
71397
71398    /* If the value is being opened for writing, check that the
71399    ** column is not indexed, and that it is not part of a foreign key.
71400    ** It is against the rules to open a column to which either of these
71401    ** descriptions applies for writing.  */
71402    if( flags ){
71403      const char *zFault = 0;
71404      Index *pIdx;
71405#ifndef SQLITE_OMIT_FOREIGN_KEY
71406      if( db->flags&SQLITE_ForeignKeys ){
71407        /* Check that the column is not part of an FK child key definition. It
71408        ** is not necessary to check if it is part of a parent key, as parent
71409        ** key columns must be indexed. The check below will pick up this
71410        ** case.  */
71411        FKey *pFKey;
71412        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
71413          int j;
71414          for(j=0; j<pFKey->nCol; j++){
71415            if( pFKey->aCol[j].iFrom==iCol ){
71416              zFault = "foreign key";
71417            }
71418          }
71419        }
71420      }
71421#endif
71422      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
71423        int j;
71424        for(j=0; j<pIdx->nColumn; j++){
71425          if( pIdx->aiColumn[j]==iCol ){
71426            zFault = "indexed";
71427          }
71428        }
71429      }
71430      if( zFault ){
71431        sqlite3DbFree(db, zErr);
71432        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
71433        rc = SQLITE_ERROR;
71434        sqlite3BtreeLeaveAll(db);
71435        goto blob_open_out;
71436      }
71437    }
71438
71439    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
71440    assert( pBlob->pStmt || db->mallocFailed );
71441    if( pBlob->pStmt ){
71442      Vdbe *v = (Vdbe *)pBlob->pStmt;
71443      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71444
71445      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
71446
71447
71448      /* Configure the OP_Transaction */
71449      sqlite3VdbeChangeP1(v, 0, iDb);
71450      sqlite3VdbeChangeP2(v, 0, flags);
71451
71452      /* Configure the OP_VerifyCookie */
71453      sqlite3VdbeChangeP1(v, 1, iDb);
71454      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
71455      sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
71456
71457      /* Make sure a mutex is held on the table to be accessed */
71458      sqlite3VdbeUsesBtree(v, iDb);
71459
71460      /* Configure the OP_TableLock instruction */
71461#ifdef SQLITE_OMIT_SHARED_CACHE
71462      sqlite3VdbeChangeToNoop(v, 2);
71463#else
71464      sqlite3VdbeChangeP1(v, 2, iDb);
71465      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
71466      sqlite3VdbeChangeP3(v, 2, flags);
71467      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
71468#endif
71469
71470      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
71471      ** parameter of the other to pTab->tnum.  */
71472      sqlite3VdbeChangeToNoop(v, 4 - flags);
71473      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
71474      sqlite3VdbeChangeP3(v, 3 + flags, iDb);
71475
71476      /* Configure the number of columns. Configure the cursor to
71477      ** think that the table has one more column than it really
71478      ** does. An OP_Column to retrieve this imaginary column will
71479      ** always return an SQL NULL. This is useful because it means
71480      ** we can invoke OP_Column to fill in the vdbe cursors type
71481      ** and offset cache without causing any IO.
71482      */
71483      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
71484      sqlite3VdbeChangeP2(v, 7, pTab->nCol);
71485      if( !db->mallocFailed ){
71486        pParse->nVar = 1;
71487        pParse->nMem = 1;
71488        pParse->nTab = 1;
71489        sqlite3VdbeMakeReady(v, pParse);
71490      }
71491    }
71492
71493    pBlob->flags = flags;
71494    pBlob->iCol = iCol;
71495    pBlob->db = db;
71496    sqlite3BtreeLeaveAll(db);
71497    if( db->mallocFailed ){
71498      goto blob_open_out;
71499    }
71500    sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
71501    rc = blobSeekToRow(pBlob, iRow, &zErr);
71502  } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
71503
71504blob_open_out:
71505  if( rc==SQLITE_OK && db->mallocFailed==0 ){
71506    *ppBlob = (sqlite3_blob *)pBlob;
71507  }else{
71508    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
71509    sqlite3DbFree(db, pBlob);
71510  }
71511  sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
71512  sqlite3DbFree(db, zErr);
71513  sqlite3StackFree(db, pParse);
71514  rc = sqlite3ApiExit(db, rc);
71515  sqlite3_mutex_leave(db->mutex);
71516  return rc;
71517}
71518
71519/*
71520** Close a blob handle that was previously created using
71521** sqlite3_blob_open().
71522*/
71523SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
71524  Incrblob *p = (Incrblob *)pBlob;
71525  int rc;
71526  sqlite3 *db;
71527
71528  if( p ){
71529    db = p->db;
71530    sqlite3_mutex_enter(db->mutex);
71531    rc = sqlite3_finalize(p->pStmt);
71532    sqlite3DbFree(db, p);
71533    sqlite3_mutex_leave(db->mutex);
71534  }else{
71535    rc = SQLITE_OK;
71536  }
71537  return rc;
71538}
71539
71540/*
71541** Perform a read or write operation on a blob
71542*/
71543static int blobReadWrite(
71544  sqlite3_blob *pBlob,
71545  void *z,
71546  int n,
71547  int iOffset,
71548  int (*xCall)(BtCursor*, u32, u32, void*)
71549){
71550  int rc;
71551  Incrblob *p = (Incrblob *)pBlob;
71552  Vdbe *v;
71553  sqlite3 *db;
71554
71555  if( p==0 ) return SQLITE_MISUSE_BKPT;
71556  db = p->db;
71557  sqlite3_mutex_enter(db->mutex);
71558  v = (Vdbe*)p->pStmt;
71559
71560  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
71561    /* Request is out of range. Return a transient error. */
71562    rc = SQLITE_ERROR;
71563    sqlite3Error(db, SQLITE_ERROR, 0);
71564  }else if( v==0 ){
71565    /* If there is no statement handle, then the blob-handle has
71566    ** already been invalidated. Return SQLITE_ABORT in this case.
71567    */
71568    rc = SQLITE_ABORT;
71569  }else{
71570    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
71571    ** returned, clean-up the statement handle.
71572    */
71573    assert( db == v->db );
71574    sqlite3BtreeEnterCursor(p->pCsr);
71575    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
71576    sqlite3BtreeLeaveCursor(p->pCsr);
71577    if( rc==SQLITE_ABORT ){
71578      sqlite3VdbeFinalize(v);
71579      p->pStmt = 0;
71580    }else{
71581      db->errCode = rc;
71582      v->rc = rc;
71583    }
71584  }
71585  rc = sqlite3ApiExit(db, rc);
71586  sqlite3_mutex_leave(db->mutex);
71587  return rc;
71588}
71589
71590/*
71591** Read data from a blob handle.
71592*/
71593SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
71594  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
71595}
71596
71597/*
71598** Write data to a blob handle.
71599*/
71600SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
71601  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
71602}
71603
71604/*
71605** Query a blob handle for the size of the data.
71606**
71607** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
71608** so no mutex is required for access.
71609*/
71610SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
71611  Incrblob *p = (Incrblob *)pBlob;
71612  return (p && p->pStmt) ? p->nByte : 0;
71613}
71614
71615/*
71616** Move an existing blob handle to point to a different row of the same
71617** database table.
71618**
71619** If an error occurs, or if the specified row does not exist or does not
71620** contain a blob or text value, then an error code is returned and the
71621** database handle error code and message set. If this happens, then all
71622** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
71623** immediately return SQLITE_ABORT.
71624*/
71625SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
71626  int rc;
71627  Incrblob *p = (Incrblob *)pBlob;
71628  sqlite3 *db;
71629
71630  if( p==0 ) return SQLITE_MISUSE_BKPT;
71631  db = p->db;
71632  sqlite3_mutex_enter(db->mutex);
71633
71634  if( p->pStmt==0 ){
71635    /* If there is no statement handle, then the blob-handle has
71636    ** already been invalidated. Return SQLITE_ABORT in this case.
71637    */
71638    rc = SQLITE_ABORT;
71639  }else{
71640    char *zErr;
71641    rc = blobSeekToRow(p, iRow, &zErr);
71642    if( rc!=SQLITE_OK ){
71643      sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
71644      sqlite3DbFree(db, zErr);
71645    }
71646    assert( rc!=SQLITE_SCHEMA );
71647  }
71648
71649  rc = sqlite3ApiExit(db, rc);
71650  assert( rc==SQLITE_OK || p->pStmt==0 );
71651  sqlite3_mutex_leave(db->mutex);
71652  return rc;
71653}
71654
71655#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
71656
71657/************** End of vdbeblob.c ********************************************/
71658/************** Begin file vdbesort.c ****************************************/
71659/*
71660** 2011 July 9
71661**
71662** The author disclaims copyright to this source code.  In place of
71663** a legal notice, here is a blessing:
71664**
71665**    May you do good and not evil.
71666**    May you find forgiveness for yourself and forgive others.
71667**    May you share freely, never taking more than you give.
71668**
71669*************************************************************************
71670** This file contains code for the VdbeSorter object, used in concert with
71671** a VdbeCursor to sort large numbers of keys (as may be required, for
71672** example, by CREATE INDEX statements on tables too large to fit in main
71673** memory).
71674*/
71675
71676
71677#ifndef SQLITE_OMIT_MERGE_SORT
71678
71679typedef struct VdbeSorterIter VdbeSorterIter;
71680typedef struct SorterRecord SorterRecord;
71681
71682/*
71683** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
71684**
71685** As keys are added to the sorter, they are written to disk in a series
71686** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
71687** the same as the cache-size allowed for temporary databases. In order
71688** to allow the caller to extract keys from the sorter in sorted order,
71689** all PMAs currently stored on disk must be merged together. This comment
71690** describes the data structure used to do so. The structure supports
71691** merging any number of arrays in a single pass with no redundant comparison
71692** operations.
71693**
71694** The aIter[] array contains an iterator for each of the PMAs being merged.
71695** An aIter[] iterator either points to a valid key or else is at EOF. For
71696** the purposes of the paragraphs below, we assume that the array is actually
71697** N elements in size, where N is the smallest power of 2 greater to or equal
71698** to the number of iterators being merged. The extra aIter[] elements are
71699** treated as if they are empty (always at EOF).
71700**
71701** The aTree[] array is also N elements in size. The value of N is stored in
71702** the VdbeSorter.nTree variable.
71703**
71704** The final (N/2) elements of aTree[] contain the results of comparing
71705** pairs of iterator keys together. Element i contains the result of
71706** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
71707** aTree element is set to the index of it.
71708**
71709** For the purposes of this comparison, EOF is considered greater than any
71710** other key value. If the keys are equal (only possible with two EOF
71711** values), it doesn't matter which index is stored.
71712**
71713** The (N/4) elements of aTree[] that preceed the final (N/2) described
71714** above contains the index of the smallest of each block of 4 iterators.
71715** And so on. So that aTree[1] contains the index of the iterator that
71716** currently points to the smallest key value. aTree[0] is unused.
71717**
71718** Example:
71719**
71720**     aIter[0] -> Banana
71721**     aIter[1] -> Feijoa
71722**     aIter[2] -> Elderberry
71723**     aIter[3] -> Currant
71724**     aIter[4] -> Grapefruit
71725**     aIter[5] -> Apple
71726**     aIter[6] -> Durian
71727**     aIter[7] -> EOF
71728**
71729**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
71730**
71731** The current element is "Apple" (the value of the key indicated by
71732** iterator 5). When the Next() operation is invoked, iterator 5 will
71733** be advanced to the next key in its segment. Say the next key is
71734** "Eggplant":
71735**
71736**     aIter[5] -> Eggplant
71737**
71738** The contents of aTree[] are updated first by comparing the new iterator
71739** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
71740** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
71741** The value of iterator 6 - "Durian" - is now smaller than that of iterator
71742** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
71743** so the value written into element 1 of the array is 0. As follows:
71744**
71745**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
71746**
71747** In other words, each time we advance to the next sorter element, log2(N)
71748** key comparison operations are required, where N is the number of segments
71749** being merged (rounded up to the next power of 2).
71750*/
71751struct VdbeSorter {
71752  i64 iWriteOff;                  /* Current write offset within file pTemp1 */
71753  i64 iReadOff;                   /* Current read offset within file pTemp1 */
71754  int nInMemory;                  /* Current size of pRecord list as PMA */
71755  int nTree;                      /* Used size of aTree/aIter (power of 2) */
71756  int nPMA;                       /* Number of PMAs stored in pTemp1 */
71757  int mnPmaSize;                  /* Minimum PMA size, in bytes */
71758  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
71759  VdbeSorterIter *aIter;          /* Array of iterators to merge */
71760  int *aTree;                     /* Current state of incremental merge */
71761  sqlite3_file *pTemp1;           /* PMA file 1 */
71762  SorterRecord *pRecord;          /* Head of in-memory record list */
71763  UnpackedRecord *pUnpacked;      /* Used to unpack keys */
71764};
71765
71766/*
71767** The following type is an iterator for a PMA. It caches the current key in
71768** variables nKey/aKey. If the iterator is at EOF, pFile==0.
71769*/
71770struct VdbeSorterIter {
71771  i64 iReadOff;                   /* Current read offset */
71772  i64 iEof;                       /* 1 byte past EOF for this iterator */
71773  int nAlloc;                     /* Bytes of space at aAlloc */
71774  int nKey;                       /* Number of bytes in key */
71775  sqlite3_file *pFile;            /* File iterator is reading from */
71776  u8 *aAlloc;                     /* Allocated space */
71777  u8 *aKey;                       /* Pointer to current key */
71778};
71779
71780/*
71781** A structure to store a single record. All in-memory records are connected
71782** together into a linked list headed at VdbeSorter.pRecord using the
71783** SorterRecord.pNext pointer.
71784*/
71785struct SorterRecord {
71786  void *pVal;
71787  int nVal;
71788  SorterRecord *pNext;
71789};
71790
71791/* Minimum allowable value for the VdbeSorter.nWorking variable */
71792#define SORTER_MIN_WORKING 10
71793
71794/* Maximum number of segments to merge in a single pass. */
71795#define SORTER_MAX_MERGE_COUNT 16
71796
71797/*
71798** Free all memory belonging to the VdbeSorterIter object passed as the second
71799** argument. All structure fields are set to zero before returning.
71800*/
71801static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
71802  sqlite3DbFree(db, pIter->aAlloc);
71803  memset(pIter, 0, sizeof(VdbeSorterIter));
71804}
71805
71806/*
71807** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
71808** no error occurs, or an SQLite error code if one does.
71809*/
71810static int vdbeSorterIterNext(
71811  sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
71812  VdbeSorterIter *pIter           /* Iterator to advance */
71813){
71814  int rc;                         /* Return Code */
71815  int nRead;                      /* Number of bytes read */
71816  int nRec = 0;                   /* Size of record in bytes */
71817  int iOff = 0;                   /* Size of serialized size varint in bytes */
71818
71819  assert( pIter->iEof>=pIter->iReadOff );
71820  if( pIter->iEof-pIter->iReadOff>5 ){
71821    nRead = 5;
71822  }else{
71823    nRead = (int)(pIter->iEof - pIter->iReadOff);
71824  }
71825  if( nRead<=0 ){
71826    /* This is an EOF condition */
71827    vdbeSorterIterZero(db, pIter);
71828    return SQLITE_OK;
71829  }
71830
71831  rc = sqlite3OsRead(pIter->pFile, pIter->aAlloc, nRead, pIter->iReadOff);
71832  if( rc==SQLITE_OK ){
71833    iOff = getVarint32(pIter->aAlloc, nRec);
71834    if( (iOff+nRec)>nRead ){
71835      int nRead2;                   /* Number of extra bytes to read */
71836      if( (iOff+nRec)>pIter->nAlloc ){
71837        int nNew = pIter->nAlloc*2;
71838        while( (iOff+nRec)>nNew ) nNew = nNew*2;
71839        pIter->aAlloc = sqlite3DbReallocOrFree(db, pIter->aAlloc, nNew);
71840        if( !pIter->aAlloc ) return SQLITE_NOMEM;
71841        pIter->nAlloc = nNew;
71842      }
71843
71844      nRead2 = iOff + nRec - nRead;
71845      rc = sqlite3OsRead(
71846          pIter->pFile, &pIter->aAlloc[nRead], nRead2, pIter->iReadOff+nRead
71847      );
71848    }
71849  }
71850
71851  assert( rc!=SQLITE_OK || nRec>0 );
71852  pIter->iReadOff += iOff+nRec;
71853  pIter->nKey = nRec;
71854  pIter->aKey = &pIter->aAlloc[iOff];
71855  return rc;
71856}
71857
71858/*
71859** Write a single varint, value iVal, to file-descriptor pFile. Return
71860** SQLITE_OK if successful, or an SQLite error code if some error occurs.
71861**
71862** The value of *piOffset when this function is called is used as the byte
71863** offset in file pFile to write to. Before returning, *piOffset is
71864** incremented by the number of bytes written.
71865*/
71866static int vdbeSorterWriteVarint(
71867  sqlite3_file *pFile,            /* File to write to */
71868  i64 iVal,                       /* Value to write as a varint */
71869  i64 *piOffset                   /* IN/OUT: Write offset in file pFile */
71870){
71871  u8 aVarint[9];                  /* Buffer large enough for a varint */
71872  int nVarint;                    /* Number of used bytes in varint */
71873  int rc;                         /* Result of write() call */
71874
71875  nVarint = sqlite3PutVarint(aVarint, iVal);
71876  rc = sqlite3OsWrite(pFile, aVarint, nVarint, *piOffset);
71877  *piOffset += nVarint;
71878
71879  return rc;
71880}
71881
71882/*
71883** Read a single varint from file-descriptor pFile. Return SQLITE_OK if
71884** successful, or an SQLite error code if some error occurs.
71885**
71886** The value of *piOffset when this function is called is used as the
71887** byte offset in file pFile from whence to read the varint. If successful
71888** (i.e. if no IO error occurs), then *piOffset is set to the offset of
71889** the first byte past the end of the varint before returning. *piVal is
71890** set to the integer value read. If an error occurs, the final values of
71891** both *piOffset and *piVal are undefined.
71892*/
71893static int vdbeSorterReadVarint(
71894  sqlite3_file *pFile,            /* File to read from */
71895  i64 *piOffset,                  /* IN/OUT: Read offset in pFile */
71896  i64 *piVal                      /* OUT: Value read from file */
71897){
71898  u8 aVarint[9];                  /* Buffer large enough for a varint */
71899  i64 iOff = *piOffset;           /* Offset in file to read from */
71900  int rc;                         /* Return code */
71901
71902  rc = sqlite3OsRead(pFile, aVarint, 9, iOff);
71903  if( rc==SQLITE_OK ){
71904    *piOffset += getVarint(aVarint, (u64 *)piVal);
71905  }
71906
71907  return rc;
71908}
71909
71910/*
71911** Initialize iterator pIter to scan through the PMA stored in file pFile
71912** starting at offset iStart and ending at offset iEof-1. This function
71913** leaves the iterator pointing to the first key in the PMA (or EOF if the
71914** PMA is empty).
71915*/
71916static int vdbeSorterIterInit(
71917  sqlite3 *db,                    /* Database handle */
71918  VdbeSorter *pSorter,            /* Sorter object */
71919  i64 iStart,                     /* Start offset in pFile */
71920  VdbeSorterIter *pIter,          /* Iterator to populate */
71921  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
71922){
71923  int rc;
71924
71925  assert( pSorter->iWriteOff>iStart );
71926  assert( pIter->aAlloc==0 );
71927  pIter->pFile = pSorter->pTemp1;
71928  pIter->iReadOff = iStart;
71929  pIter->nAlloc = 128;
71930  pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
71931  if( !pIter->aAlloc ){
71932    rc = SQLITE_NOMEM;
71933  }else{
71934    i64 nByte;                         /* Total size of PMA in bytes */
71935    rc = vdbeSorterReadVarint(pSorter->pTemp1, &pIter->iReadOff, &nByte);
71936    *pnByte += nByte;
71937    pIter->iEof = pIter->iReadOff + nByte;
71938  }
71939  if( rc==SQLITE_OK ){
71940    rc = vdbeSorterIterNext(db, pIter);
71941  }
71942  return rc;
71943}
71944
71945
71946/*
71947** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
71948** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
71949** used by the comparison. If an error occurs, return an SQLite error code.
71950** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
71951** value, depending on whether key1 is smaller, equal to or larger than key2.
71952**
71953** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
71954** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
71955** is true and key1 contains even a single NULL value, it is considered to
71956** be less than key2. Even if key2 also contains NULL values.
71957**
71958** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
71959** has been allocated and contains an unpacked record that is used as key2.
71960*/
71961static void vdbeSorterCompare(
71962  VdbeCursor *pCsr,               /* Cursor object (for pKeyInfo) */
71963  int bOmitRowid,                 /* Ignore rowid field at end of keys */
71964  void *pKey1, int nKey1,         /* Left side of comparison */
71965  void *pKey2, int nKey2,         /* Right side of comparison */
71966  int *pRes                       /* OUT: Result of comparison */
71967){
71968  KeyInfo *pKeyInfo = pCsr->pKeyInfo;
71969  VdbeSorter *pSorter = pCsr->pSorter;
71970  UnpackedRecord *r2 = pSorter->pUnpacked;
71971  int i;
71972
71973  if( pKey2 ){
71974    sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
71975  }
71976
71977  if( bOmitRowid ){
71978    r2->nField = pKeyInfo->nField;
71979    assert( r2->nField>0 );
71980    for(i=0; i<r2->nField; i++){
71981      if( r2->aMem[i].flags & MEM_Null ){
71982        *pRes = -1;
71983        return;
71984      }
71985    }
71986    r2->flags |= UNPACKED_PREFIX_MATCH;
71987  }
71988
71989  *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
71990}
71991
71992/*
71993** This function is called to compare two iterator keys when merging
71994** multiple b-tree segments. Parameter iOut is the index of the aTree[]
71995** value to recalculate.
71996*/
71997static int vdbeSorterDoCompare(VdbeCursor *pCsr, int iOut){
71998  VdbeSorter *pSorter = pCsr->pSorter;
71999  int i1;
72000  int i2;
72001  int iRes;
72002  VdbeSorterIter *p1;
72003  VdbeSorterIter *p2;
72004
72005  assert( iOut<pSorter->nTree && iOut>0 );
72006
72007  if( iOut>=(pSorter->nTree/2) ){
72008    i1 = (iOut - pSorter->nTree/2) * 2;
72009    i2 = i1 + 1;
72010  }else{
72011    i1 = pSorter->aTree[iOut*2];
72012    i2 = pSorter->aTree[iOut*2+1];
72013  }
72014
72015  p1 = &pSorter->aIter[i1];
72016  p2 = &pSorter->aIter[i2];
72017
72018  if( p1->pFile==0 ){
72019    iRes = i2;
72020  }else if( p2->pFile==0 ){
72021    iRes = i1;
72022  }else{
72023    int res;
72024    assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
72025    vdbeSorterCompare(
72026        pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
72027    );
72028    if( res<=0 ){
72029      iRes = i1;
72030    }else{
72031      iRes = i2;
72032    }
72033  }
72034
72035  pSorter->aTree[iOut] = iRes;
72036  return SQLITE_OK;
72037}
72038
72039/*
72040** Initialize the temporary index cursor just opened as a sorter cursor.
72041*/
72042SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
72043  int pgsz;                       /* Page size of main database */
72044  int mxCache;                    /* Cache size */
72045  VdbeSorter *pSorter;            /* The new sorter */
72046  char *d;                        /* Dummy */
72047
72048  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
72049  pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
72050  if( pSorter==0 ){
72051    return SQLITE_NOMEM;
72052  }
72053
72054  pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
72055  if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
72056  assert( pSorter->pUnpacked==(UnpackedRecord *)d );
72057
72058  if( !sqlite3TempInMemory(db) ){
72059    pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72060    pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
72061    mxCache = db->aDb[0].pSchema->cache_size;
72062    if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
72063    pSorter->mxPmaSize = mxCache * pgsz;
72064  }
72065
72066  return SQLITE_OK;
72067}
72068
72069/*
72070** Free the list of sorted records starting at pRecord.
72071*/
72072static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
72073  SorterRecord *p;
72074  SorterRecord *pNext;
72075  for(p=pRecord; p; p=pNext){
72076    pNext = p->pNext;
72077    sqlite3DbFree(db, p);
72078  }
72079}
72080
72081/*
72082** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
72083*/
72084SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
72085  VdbeSorter *pSorter = pCsr->pSorter;
72086  if( pSorter ){
72087    if( pSorter->aIter ){
72088      int i;
72089      for(i=0; i<pSorter->nTree; i++){
72090        vdbeSorterIterZero(db, &pSorter->aIter[i]);
72091      }
72092      sqlite3DbFree(db, pSorter->aIter);
72093    }
72094    if( pSorter->pTemp1 ){
72095      sqlite3OsCloseFree(pSorter->pTemp1);
72096    }
72097    vdbeSorterRecordFree(db, pSorter->pRecord);
72098    sqlite3DbFree(db, pSorter->pUnpacked);
72099    sqlite3DbFree(db, pSorter);
72100    pCsr->pSorter = 0;
72101  }
72102}
72103
72104/*
72105** Allocate space for a file-handle and open a temporary file. If successful,
72106** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
72107** Otherwise, set *ppFile to 0 and return an SQLite error code.
72108*/
72109static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
72110  int dummy;
72111  return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
72112      SQLITE_OPEN_TEMP_JOURNAL |
72113      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
72114      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
72115  );
72116}
72117
72118/*
72119** Merge the two sorted lists p1 and p2 into a single list.
72120** Set *ppOut to the head of the new list.
72121*/
72122static void vdbeSorterMerge(
72123  VdbeCursor *pCsr,               /* For pKeyInfo */
72124  SorterRecord *p1,               /* First list to merge */
72125  SorterRecord *p2,               /* Second list to merge */
72126  SorterRecord **ppOut            /* OUT: Head of merged list */
72127){
72128  SorterRecord *pFinal = 0;
72129  SorterRecord **pp = &pFinal;
72130  void *pVal2 = p2 ? p2->pVal : 0;
72131
72132  while( p1 && p2 ){
72133    int res;
72134    vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
72135    if( res<=0 ){
72136      *pp = p1;
72137      pp = &p1->pNext;
72138      p1 = p1->pNext;
72139      pVal2 = 0;
72140    }else{
72141      *pp = p2;
72142       pp = &p2->pNext;
72143      p2 = p2->pNext;
72144      if( p2==0 ) break;
72145      pVal2 = p2->pVal;
72146    }
72147  }
72148  *pp = p1 ? p1 : p2;
72149  *ppOut = pFinal;
72150}
72151
72152/*
72153** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
72154** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
72155** occurs.
72156*/
72157static int vdbeSorterSort(VdbeCursor *pCsr){
72158  int i;
72159  SorterRecord **aSlot;
72160  SorterRecord *p;
72161  VdbeSorter *pSorter = pCsr->pSorter;
72162
72163  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
72164  if( !aSlot ){
72165    return SQLITE_NOMEM;
72166  }
72167
72168  p = pSorter->pRecord;
72169  while( p ){
72170    SorterRecord *pNext = p->pNext;
72171    p->pNext = 0;
72172    for(i=0; aSlot[i]; i++){
72173      vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72174      aSlot[i] = 0;
72175    }
72176    aSlot[i] = p;
72177    p = pNext;
72178  }
72179
72180  p = 0;
72181  for(i=0; i<64; i++){
72182    vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72183  }
72184  pSorter->pRecord = p;
72185
72186  sqlite3_free(aSlot);
72187  return SQLITE_OK;
72188}
72189
72190
72191/*
72192** Write the current contents of the in-memory linked-list to a PMA. Return
72193** SQLITE_OK if successful, or an SQLite error code otherwise.
72194**
72195** The format of a PMA is:
72196**
72197**     * A varint. This varint contains the total number of bytes of content
72198**       in the PMA (not including the varint itself).
72199**
72200**     * One or more records packed end-to-end in order of ascending keys.
72201**       Each record consists of a varint followed by a blob of data (the
72202**       key). The varint is the number of bytes in the blob of data.
72203*/
72204static int vdbeSorterListToPMA(sqlite3 *db, VdbeCursor *pCsr){
72205  int rc = SQLITE_OK;             /* Return code */
72206  VdbeSorter *pSorter = pCsr->pSorter;
72207
72208  if( pSorter->nInMemory==0 ){
72209    assert( pSorter->pRecord==0 );
72210    return rc;
72211  }
72212
72213  rc = vdbeSorterSort(pCsr);
72214
72215  /* If the first temporary PMA file has not been opened, open it now. */
72216  if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
72217    rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
72218    assert( rc!=SQLITE_OK || pSorter->pTemp1 );
72219    assert( pSorter->iWriteOff==0 );
72220    assert( pSorter->nPMA==0 );
72221  }
72222
72223  if( rc==SQLITE_OK ){
72224    i64 iOff = pSorter->iWriteOff;
72225    SorterRecord *p;
72226    SorterRecord *pNext = 0;
72227    static const char eightZeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
72228
72229    pSorter->nPMA++;
72230    rc = vdbeSorterWriteVarint(pSorter->pTemp1, pSorter->nInMemory, &iOff);
72231    for(p=pSorter->pRecord; rc==SQLITE_OK && p; p=pNext){
72232      pNext = p->pNext;
72233      rc = vdbeSorterWriteVarint(pSorter->pTemp1, p->nVal, &iOff);
72234
72235      if( rc==SQLITE_OK ){
72236        rc = sqlite3OsWrite(pSorter->pTemp1, p->pVal, p->nVal, iOff);
72237        iOff += p->nVal;
72238      }
72239
72240      sqlite3DbFree(db, p);
72241    }
72242
72243    /* This assert verifies that unless an error has occurred, the size of
72244    ** the PMA on disk is the same as the expected size stored in
72245    ** pSorter->nInMemory. */
72246    assert( rc!=SQLITE_OK || pSorter->nInMemory==(
72247          iOff-pSorter->iWriteOff-sqlite3VarintLen(pSorter->nInMemory)
72248    ));
72249
72250    pSorter->iWriteOff = iOff;
72251    if( rc==SQLITE_OK ){
72252      /* Terminate each file with 8 extra bytes so that from any offset
72253      ** in the file we can always read 9 bytes without a SHORT_READ error */
72254      rc = sqlite3OsWrite(pSorter->pTemp1, eightZeros, 8, iOff);
72255    }
72256    pSorter->pRecord = p;
72257  }
72258
72259  return rc;
72260}
72261
72262/*
72263** Add a record to the sorter.
72264*/
72265SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
72266  sqlite3 *db,                    /* Database handle */
72267  VdbeCursor *pCsr,               /* Sorter cursor */
72268  Mem *pVal                       /* Memory cell containing record */
72269){
72270  VdbeSorter *pSorter = pCsr->pSorter;
72271  int rc = SQLITE_OK;             /* Return Code */
72272  SorterRecord *pNew;             /* New list element */
72273
72274  assert( pSorter );
72275  pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
72276
72277  pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
72278  if( pNew==0 ){
72279    rc = SQLITE_NOMEM;
72280  }else{
72281    pNew->pVal = (void *)&pNew[1];
72282    memcpy(pNew->pVal, pVal->z, pVal->n);
72283    pNew->nVal = pVal->n;
72284    pNew->pNext = pSorter->pRecord;
72285    pSorter->pRecord = pNew;
72286  }
72287
72288  /* See if the contents of the sorter should now be written out. They
72289  ** are written out when either of the following are true:
72290  **
72291  **   * The total memory allocated for the in-memory list is greater
72292  **     than (page-size * cache-size), or
72293  **
72294  **   * The total memory allocated for the in-memory list is greater
72295  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
72296  */
72297  if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
72298        (pSorter->nInMemory>pSorter->mxPmaSize)
72299     || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
72300  )){
72301    rc = vdbeSorterListToPMA(db, pCsr);
72302    pSorter->nInMemory = 0;
72303  }
72304
72305  return rc;
72306}
72307
72308/*
72309** Helper function for sqlite3VdbeSorterRewind().
72310*/
72311static int vdbeSorterInitMerge(
72312  sqlite3 *db,                    /* Database handle */
72313  VdbeCursor *pCsr,               /* Cursor handle for this sorter */
72314  i64 *pnByte                     /* Sum of bytes in all opened PMAs */
72315){
72316  VdbeSorter *pSorter = pCsr->pSorter;
72317  int rc = SQLITE_OK;             /* Return code */
72318  int i;                          /* Used to iterator through aIter[] */
72319  i64 nByte = 0;                  /* Total bytes in all opened PMAs */
72320
72321  /* Initialize the iterators. */
72322  for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
72323    VdbeSorterIter *pIter = &pSorter->aIter[i];
72324    rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
72325    pSorter->iReadOff = pIter->iEof;
72326    assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
72327    if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
72328  }
72329
72330  /* Initialize the aTree[] array. */
72331  for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
72332    rc = vdbeSorterDoCompare(pCsr, i);
72333  }
72334
72335  *pnByte = nByte;
72336  return rc;
72337}
72338
72339/*
72340** Once the sorter has been populated, this function is called to prepare
72341** for iterating through its contents in sorted order.
72342*/
72343SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
72344  VdbeSorter *pSorter = pCsr->pSorter;
72345  int rc;                         /* Return code */
72346  sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
72347  i64 iWrite2 = 0;                /* Write offset for pTemp2 */
72348  int nIter;                      /* Number of iterators used */
72349  int nByte;                      /* Bytes of space required for aIter/aTree */
72350  int N = 2;                      /* Power of 2 >= nIter */
72351
72352  assert( pSorter );
72353
72354  /* If no data has been written to disk, then do not do so now. Instead,
72355  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
72356  ** from the in-memory list.  */
72357  if( pSorter->nPMA==0 ){
72358    *pbEof = !pSorter->pRecord;
72359    assert( pSorter->aTree==0 );
72360    return vdbeSorterSort(pCsr);
72361  }
72362
72363  /* Write the current b-tree to a PMA. Close the b-tree cursor. */
72364  rc = vdbeSorterListToPMA(db, pCsr);
72365  if( rc!=SQLITE_OK ) return rc;
72366
72367  /* Allocate space for aIter[] and aTree[]. */
72368  nIter = pSorter->nPMA;
72369  if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
72370  assert( nIter>0 );
72371  while( N<nIter ) N += N;
72372  nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
72373  pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
72374  if( !pSorter->aIter ) return SQLITE_NOMEM;
72375  pSorter->aTree = (int *)&pSorter->aIter[N];
72376  pSorter->nTree = N;
72377
72378  do {
72379    int iNew;                     /* Index of new, merged, PMA */
72380
72381    for(iNew=0;
72382        rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
72383        iNew++
72384    ){
72385      i64 nWrite;                 /* Number of bytes in new PMA */
72386
72387      /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
72388      ** initialize an iterator for each of them and break out of the loop.
72389      ** These iterators will be incrementally merged as the VDBE layer calls
72390      ** sqlite3VdbeSorterNext().
72391      **
72392      ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
72393      ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
72394      ** are merged into a single PMA that is written to file pTemp2.
72395      */
72396      rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
72397      assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
72398      if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
72399        break;
72400      }
72401
72402      /* Open the second temp file, if it is not already open. */
72403      if( pTemp2==0 ){
72404        assert( iWrite2==0 );
72405        rc = vdbeSorterOpenTempFile(db, &pTemp2);
72406      }
72407
72408      if( rc==SQLITE_OK ){
72409        rc = vdbeSorterWriteVarint(pTemp2, nWrite, &iWrite2);
72410      }
72411
72412      if( rc==SQLITE_OK ){
72413        int bEof = 0;
72414        while( rc==SQLITE_OK && bEof==0 ){
72415          int nToWrite;
72416          VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
72417          assert( pIter->pFile );
72418          nToWrite = pIter->nKey + sqlite3VarintLen(pIter->nKey);
72419          rc = sqlite3OsWrite(pTemp2, pIter->aAlloc, nToWrite, iWrite2);
72420          iWrite2 += nToWrite;
72421          if( rc==SQLITE_OK ){
72422            rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
72423          }
72424        }
72425      }
72426    }
72427
72428    if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
72429      break;
72430    }else{
72431      sqlite3_file *pTmp = pSorter->pTemp1;
72432      pSorter->nPMA = iNew;
72433      pSorter->pTemp1 = pTemp2;
72434      pTemp2 = pTmp;
72435      pSorter->iWriteOff = iWrite2;
72436      pSorter->iReadOff = 0;
72437      iWrite2 = 0;
72438    }
72439  }while( rc==SQLITE_OK );
72440
72441  if( pTemp2 ){
72442    sqlite3OsCloseFree(pTemp2);
72443  }
72444  *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
72445  return rc;
72446}
72447
72448/*
72449** Advance to the next element in the sorter.
72450*/
72451SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
72452  VdbeSorter *pSorter = pCsr->pSorter;
72453  int rc;                         /* Return code */
72454
72455  if( pSorter->aTree ){
72456    int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
72457    int i;                        /* Index of aTree[] to recalculate */
72458
72459    rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
72460    for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
72461      rc = vdbeSorterDoCompare(pCsr, i);
72462    }
72463
72464    *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
72465  }else{
72466    SorterRecord *pFree = pSorter->pRecord;
72467    pSorter->pRecord = pFree->pNext;
72468    pFree->pNext = 0;
72469    vdbeSorterRecordFree(db, pFree);
72470    *pbEof = !pSorter->pRecord;
72471    rc = SQLITE_OK;
72472  }
72473  return rc;
72474}
72475
72476/*
72477** Return a pointer to a buffer owned by the sorter that contains the
72478** current key.
72479*/
72480static void *vdbeSorterRowkey(
72481  VdbeSorter *pSorter,            /* Sorter object */
72482  int *pnKey                      /* OUT: Size of current key in bytes */
72483){
72484  void *pKey;
72485  if( pSorter->aTree ){
72486    VdbeSorterIter *pIter;
72487    pIter = &pSorter->aIter[ pSorter->aTree[1] ];
72488    *pnKey = pIter->nKey;
72489    pKey = pIter->aKey;
72490  }else{
72491    *pnKey = pSorter->pRecord->nVal;
72492    pKey = pSorter->pRecord->pVal;
72493  }
72494  return pKey;
72495}
72496
72497/*
72498** Copy the current sorter key into the memory cell pOut.
72499*/
72500SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *pCsr, Mem *pOut){
72501  VdbeSorter *pSorter = pCsr->pSorter;
72502  void *pKey; int nKey;           /* Sorter key to copy into pOut */
72503
72504  pKey = vdbeSorterRowkey(pSorter, &nKey);
72505  if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
72506    return SQLITE_NOMEM;
72507  }
72508  pOut->n = nKey;
72509  MemSetTypeFlag(pOut, MEM_Blob);
72510  memcpy(pOut->z, pKey, nKey);
72511
72512  return SQLITE_OK;
72513}
72514
72515/*
72516** Compare the key in memory cell pVal with the key that the sorter cursor
72517** passed as the first argument currently points to. For the purposes of
72518** the comparison, ignore the rowid field at the end of each record.
72519**
72520** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
72521** Otherwise, set *pRes to a negative, zero or positive value if the
72522** key in pVal is smaller than, equal to or larger than the current sorter
72523** key.
72524*/
72525SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
72526  VdbeCursor *pCsr,               /* Sorter cursor */
72527  Mem *pVal,                      /* Value to compare to current sorter key */
72528  int *pRes                       /* OUT: Result of comparison */
72529){
72530  VdbeSorter *pSorter = pCsr->pSorter;
72531  void *pKey; int nKey;           /* Sorter key to compare pVal with */
72532
72533  pKey = vdbeSorterRowkey(pSorter, &nKey);
72534  vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
72535  return SQLITE_OK;
72536}
72537
72538#endif /* #ifndef SQLITE_OMIT_MERGE_SORT */
72539
72540/************** End of vdbesort.c ********************************************/
72541/************** Begin file journal.c *****************************************/
72542/*
72543** 2007 August 22
72544**
72545** The author disclaims copyright to this source code.  In place of
72546** a legal notice, here is a blessing:
72547**
72548**    May you do good and not evil.
72549**    May you find forgiveness for yourself and forgive others.
72550**    May you share freely, never taking more than you give.
72551**
72552*************************************************************************
72553**
72554** This file implements a special kind of sqlite3_file object used
72555** by SQLite to create journal files if the atomic-write optimization
72556** is enabled.
72557**
72558** The distinctive characteristic of this sqlite3_file is that the
72559** actual on disk file is created lazily. When the file is created,
72560** the caller specifies a buffer size for an in-memory buffer to
72561** be used to service read() and write() requests. The actual file
72562** on disk is not created or populated until either:
72563**
72564**   1) The in-memory representation grows too large for the allocated
72565**      buffer, or
72566**   2) The sqlite3JournalCreate() function is called.
72567*/
72568#ifdef SQLITE_ENABLE_ATOMIC_WRITE
72569
72570
72571/*
72572** A JournalFile object is a subclass of sqlite3_file used by
72573** as an open file handle for journal files.
72574*/
72575struct JournalFile {
72576  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
72577  int nBuf;                       /* Size of zBuf[] in bytes */
72578  char *zBuf;                     /* Space to buffer journal writes */
72579  int iSize;                      /* Amount of zBuf[] currently used */
72580  int flags;                      /* xOpen flags */
72581  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
72582  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
72583  const char *zJournal;           /* Name of the journal file */
72584};
72585typedef struct JournalFile JournalFile;
72586
72587/*
72588** If it does not already exists, create and populate the on-disk file
72589** for JournalFile p.
72590*/
72591static int createFile(JournalFile *p){
72592  int rc = SQLITE_OK;
72593  if( !p->pReal ){
72594    sqlite3_file *pReal = (sqlite3_file *)&p[1];
72595    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
72596    if( rc==SQLITE_OK ){
72597      p->pReal = pReal;
72598      if( p->iSize>0 ){
72599        assert(p->iSize<=p->nBuf);
72600        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
72601      }
72602    }
72603  }
72604  return rc;
72605}
72606
72607/*
72608** Close the file.
72609*/
72610static int jrnlClose(sqlite3_file *pJfd){
72611  JournalFile *p = (JournalFile *)pJfd;
72612  if( p->pReal ){
72613    sqlite3OsClose(p->pReal);
72614  }
72615  sqlite3_free(p->zBuf);
72616  return SQLITE_OK;
72617}
72618
72619/*
72620** Read data from the file.
72621*/
72622static int jrnlRead(
72623  sqlite3_file *pJfd,    /* The journal file from which to read */
72624  void *zBuf,            /* Put the results here */
72625  int iAmt,              /* Number of bytes to read */
72626  sqlite_int64 iOfst     /* Begin reading at this offset */
72627){
72628  int rc = SQLITE_OK;
72629  JournalFile *p = (JournalFile *)pJfd;
72630  if( p->pReal ){
72631    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
72632  }else if( (iAmt+iOfst)>p->iSize ){
72633    rc = SQLITE_IOERR_SHORT_READ;
72634  }else{
72635    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
72636  }
72637  return rc;
72638}
72639
72640/*
72641** Write data to the file.
72642*/
72643static int jrnlWrite(
72644  sqlite3_file *pJfd,    /* The journal file into which to write */
72645  const void *zBuf,      /* Take data to be written from here */
72646  int iAmt,              /* Number of bytes to write */
72647  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
72648){
72649  int rc = SQLITE_OK;
72650  JournalFile *p = (JournalFile *)pJfd;
72651  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
72652    rc = createFile(p);
72653  }
72654  if( rc==SQLITE_OK ){
72655    if( p->pReal ){
72656      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
72657    }else{
72658      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
72659      if( p->iSize<(iOfst+iAmt) ){
72660        p->iSize = (iOfst+iAmt);
72661      }
72662    }
72663  }
72664  return rc;
72665}
72666
72667/*
72668** Truncate the file.
72669*/
72670static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
72671  int rc = SQLITE_OK;
72672  JournalFile *p = (JournalFile *)pJfd;
72673  if( p->pReal ){
72674    rc = sqlite3OsTruncate(p->pReal, size);
72675  }else if( size<p->iSize ){
72676    p->iSize = size;
72677  }
72678  return rc;
72679}
72680
72681/*
72682** Sync the file.
72683*/
72684static int jrnlSync(sqlite3_file *pJfd, int flags){
72685  int rc;
72686  JournalFile *p = (JournalFile *)pJfd;
72687  if( p->pReal ){
72688    rc = sqlite3OsSync(p->pReal, flags);
72689  }else{
72690    rc = SQLITE_OK;
72691  }
72692  return rc;
72693}
72694
72695/*
72696** Query the size of the file in bytes.
72697*/
72698static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
72699  int rc = SQLITE_OK;
72700  JournalFile *p = (JournalFile *)pJfd;
72701  if( p->pReal ){
72702    rc = sqlite3OsFileSize(p->pReal, pSize);
72703  }else{
72704    *pSize = (sqlite_int64) p->iSize;
72705  }
72706  return rc;
72707}
72708
72709/*
72710** Table of methods for JournalFile sqlite3_file object.
72711*/
72712static struct sqlite3_io_methods JournalFileMethods = {
72713  1,             /* iVersion */
72714  jrnlClose,     /* xClose */
72715  jrnlRead,      /* xRead */
72716  jrnlWrite,     /* xWrite */
72717  jrnlTruncate,  /* xTruncate */
72718  jrnlSync,      /* xSync */
72719  jrnlFileSize,  /* xFileSize */
72720  0,             /* xLock */
72721  0,             /* xUnlock */
72722  0,             /* xCheckReservedLock */
72723  0,             /* xFileControl */
72724  0,             /* xSectorSize */
72725  0,             /* xDeviceCharacteristics */
72726  0,             /* xShmMap */
72727  0,             /* xShmLock */
72728  0,             /* xShmBarrier */
72729  0              /* xShmUnmap */
72730};
72731
72732/*
72733** Open a journal file.
72734*/
72735SQLITE_PRIVATE int sqlite3JournalOpen(
72736  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
72737  const char *zName,         /* Name of the journal file */
72738  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
72739  int flags,                 /* Opening flags */
72740  int nBuf                   /* Bytes buffered before opening the file */
72741){
72742  JournalFile *p = (JournalFile *)pJfd;
72743  memset(p, 0, sqlite3JournalSize(pVfs));
72744  if( nBuf>0 ){
72745    p->zBuf = sqlite3MallocZero(nBuf);
72746    if( !p->zBuf ){
72747      return SQLITE_NOMEM;
72748    }
72749  }else{
72750    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
72751  }
72752  p->pMethod = &JournalFileMethods;
72753  p->nBuf = nBuf;
72754  p->flags = flags;
72755  p->zJournal = zName;
72756  p->pVfs = pVfs;
72757  return SQLITE_OK;
72758}
72759
72760/*
72761** If the argument p points to a JournalFile structure, and the underlying
72762** file has not yet been created, create it now.
72763*/
72764SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
72765  if( p->pMethods!=&JournalFileMethods ){
72766    return SQLITE_OK;
72767  }
72768  return createFile((JournalFile *)p);
72769}
72770
72771/*
72772** Return the number of bytes required to store a JournalFile that uses vfs
72773** pVfs to create the underlying on-disk files.
72774*/
72775SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
72776  return (pVfs->szOsFile+sizeof(JournalFile));
72777}
72778#endif
72779
72780/************** End of journal.c *********************************************/
72781/************** Begin file memjournal.c **************************************/
72782/*
72783** 2008 October 7
72784**
72785** The author disclaims copyright to this source code.  In place of
72786** a legal notice, here is a blessing:
72787**
72788**    May you do good and not evil.
72789**    May you find forgiveness for yourself and forgive others.
72790**    May you share freely, never taking more than you give.
72791**
72792*************************************************************************
72793**
72794** This file contains code use to implement an in-memory rollback journal.
72795** The in-memory rollback journal is used to journal transactions for
72796** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
72797*/
72798
72799/* Forward references to internal structures */
72800typedef struct MemJournal MemJournal;
72801typedef struct FilePoint FilePoint;
72802typedef struct FileChunk FileChunk;
72803
72804/* Space to hold the rollback journal is allocated in increments of
72805** this many bytes.
72806**
72807** The size chosen is a little less than a power of two.  That way,
72808** the FileChunk object will have a size that almost exactly fills
72809** a power-of-two allocation.  This mimimizes wasted space in power-of-two
72810** memory allocators.
72811*/
72812#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
72813
72814/* Macro to find the minimum of two numeric values.
72815*/
72816#ifndef MIN
72817# define MIN(x,y) ((x)<(y)?(x):(y))
72818#endif
72819
72820/*
72821** The rollback journal is composed of a linked list of these structures.
72822*/
72823struct FileChunk {
72824  FileChunk *pNext;               /* Next chunk in the journal */
72825  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
72826};
72827
72828/*
72829** An instance of this object serves as a cursor into the rollback journal.
72830** The cursor can be either for reading or writing.
72831*/
72832struct FilePoint {
72833  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
72834  FileChunk *pChunk;              /* Specific chunk into which cursor points */
72835};
72836
72837/*
72838** This subclass is a subclass of sqlite3_file.  Each open memory-journal
72839** is an instance of this class.
72840*/
72841struct MemJournal {
72842  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
72843  FileChunk *pFirst;              /* Head of in-memory chunk-list */
72844  FilePoint endpoint;             /* Pointer to the end of the file */
72845  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
72846};
72847
72848/*
72849** Read data from the in-memory journal file.  This is the implementation
72850** of the sqlite3_vfs.xRead method.
72851*/
72852static int memjrnlRead(
72853  sqlite3_file *pJfd,    /* The journal file from which to read */
72854  void *zBuf,            /* Put the results here */
72855  int iAmt,              /* Number of bytes to read */
72856  sqlite_int64 iOfst     /* Begin reading at this offset */
72857){
72858  MemJournal *p = (MemJournal *)pJfd;
72859  u8 *zOut = zBuf;
72860  int nRead = iAmt;
72861  int iChunkOffset;
72862  FileChunk *pChunk;
72863
72864  /* SQLite never tries to read past the end of a rollback journal file */
72865  assert( iOfst+iAmt<=p->endpoint.iOffset );
72866
72867  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
72868    sqlite3_int64 iOff = 0;
72869    for(pChunk=p->pFirst;
72870        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
72871        pChunk=pChunk->pNext
72872    ){
72873      iOff += JOURNAL_CHUNKSIZE;
72874    }
72875  }else{
72876    pChunk = p->readpoint.pChunk;
72877  }
72878
72879  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
72880  do {
72881    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
72882    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
72883    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
72884    zOut += nCopy;
72885    nRead -= iSpace;
72886    iChunkOffset = 0;
72887  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
72888  p->readpoint.iOffset = iOfst+iAmt;
72889  p->readpoint.pChunk = pChunk;
72890
72891  return SQLITE_OK;
72892}
72893
72894/*
72895** Write data to the file.
72896*/
72897static int memjrnlWrite(
72898  sqlite3_file *pJfd,    /* The journal file into which to write */
72899  const void *zBuf,      /* Take data to be written from here */
72900  int iAmt,              /* Number of bytes to write */
72901  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
72902){
72903  MemJournal *p = (MemJournal *)pJfd;
72904  int nWrite = iAmt;
72905  u8 *zWrite = (u8 *)zBuf;
72906
72907  /* An in-memory journal file should only ever be appended to. Random
72908  ** access writes are not required by sqlite.
72909  */
72910  assert( iOfst==p->endpoint.iOffset );
72911  UNUSED_PARAMETER(iOfst);
72912
72913  while( nWrite>0 ){
72914    FileChunk *pChunk = p->endpoint.pChunk;
72915    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
72916    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
72917
72918    if( iChunkOffset==0 ){
72919      /* New chunk is required to extend the file. */
72920      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
72921      if( !pNew ){
72922        return SQLITE_IOERR_NOMEM;
72923      }
72924      pNew->pNext = 0;
72925      if( pChunk ){
72926        assert( p->pFirst );
72927        pChunk->pNext = pNew;
72928      }else{
72929        assert( !p->pFirst );
72930        p->pFirst = pNew;
72931      }
72932      p->endpoint.pChunk = pNew;
72933    }
72934
72935    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
72936    zWrite += iSpace;
72937    nWrite -= iSpace;
72938    p->endpoint.iOffset += iSpace;
72939  }
72940
72941  return SQLITE_OK;
72942}
72943
72944/*
72945** Truncate the file.
72946*/
72947static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
72948  MemJournal *p = (MemJournal *)pJfd;
72949  FileChunk *pChunk;
72950  assert(size==0);
72951  UNUSED_PARAMETER(size);
72952  pChunk = p->pFirst;
72953  while( pChunk ){
72954    FileChunk *pTmp = pChunk;
72955    pChunk = pChunk->pNext;
72956    sqlite3_free(pTmp);
72957  }
72958  sqlite3MemJournalOpen(pJfd);
72959  return SQLITE_OK;
72960}
72961
72962/*
72963** Close the file.
72964*/
72965static int memjrnlClose(sqlite3_file *pJfd){
72966  memjrnlTruncate(pJfd, 0);
72967  return SQLITE_OK;
72968}
72969
72970
72971/*
72972** Sync the file.
72973**
72974** Syncing an in-memory journal is a no-op.  And, in fact, this routine
72975** is never called in a working implementation.  This implementation
72976** exists purely as a contingency, in case some malfunction in some other
72977** part of SQLite causes Sync to be called by mistake.
72978*/
72979static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
72980  UNUSED_PARAMETER2(NotUsed, NotUsed2);
72981  return SQLITE_OK;
72982}
72983
72984/*
72985** Query the size of the file in bytes.
72986*/
72987static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
72988  MemJournal *p = (MemJournal *)pJfd;
72989  *pSize = (sqlite_int64) p->endpoint.iOffset;
72990  return SQLITE_OK;
72991}
72992
72993/*
72994** Table of methods for MemJournal sqlite3_file object.
72995*/
72996static const struct sqlite3_io_methods MemJournalMethods = {
72997  1,                /* iVersion */
72998  memjrnlClose,     /* xClose */
72999  memjrnlRead,      /* xRead */
73000  memjrnlWrite,     /* xWrite */
73001  memjrnlTruncate,  /* xTruncate */
73002  memjrnlSync,      /* xSync */
73003  memjrnlFileSize,  /* xFileSize */
73004  0,                /* xLock */
73005  0,                /* xUnlock */
73006  0,                /* xCheckReservedLock */
73007  0,                /* xFileControl */
73008  0,                /* xSectorSize */
73009  0,                /* xDeviceCharacteristics */
73010  0,                /* xShmMap */
73011  0,                /* xShmLock */
73012  0,                /* xShmBarrier */
73013  0                 /* xShmUnlock */
73014};
73015
73016/*
73017** Open a journal file.
73018*/
73019SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
73020  MemJournal *p = (MemJournal *)pJfd;
73021  assert( EIGHT_BYTE_ALIGNMENT(p) );
73022  memset(p, 0, sqlite3MemJournalSize());
73023  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
73024}
73025
73026/*
73027** Return true if the file-handle passed as an argument is
73028** an in-memory journal
73029*/
73030SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
73031  return pJfd->pMethods==&MemJournalMethods;
73032}
73033
73034/*
73035** Return the number of bytes required to store a MemJournal file descriptor.
73036*/
73037SQLITE_PRIVATE int sqlite3MemJournalSize(void){
73038  return sizeof(MemJournal);
73039}
73040
73041/************** End of memjournal.c ******************************************/
73042/************** Begin file walker.c ******************************************/
73043/*
73044** 2008 August 16
73045**
73046** The author disclaims copyright to this source code.  In place of
73047** a legal notice, here is a blessing:
73048**
73049**    May you do good and not evil.
73050**    May you find forgiveness for yourself and forgive others.
73051**    May you share freely, never taking more than you give.
73052**
73053*************************************************************************
73054** This file contains routines used for walking the parser tree for
73055** an SQL statement.
73056*/
73057/* #include <stdlib.h> */
73058/* #include <string.h> */
73059
73060
73061/*
73062** Walk an expression tree.  Invoke the callback once for each node
73063** of the expression, while decending.  (In other words, the callback
73064** is invoked before visiting children.)
73065**
73066** The return value from the callback should be one of the WRC_*
73067** constants to specify how to proceed with the walk.
73068**
73069**    WRC_Continue      Continue descending down the tree.
73070**
73071**    WRC_Prune         Do not descend into child nodes.  But allow
73072**                      the walk to continue with sibling nodes.
73073**
73074**    WRC_Abort         Do no more callbacks.  Unwind the stack and
73075**                      return the top-level walk call.
73076**
73077** The return value from this routine is WRC_Abort to abandon the tree walk
73078** and WRC_Continue to continue.
73079*/
73080SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
73081  int rc;
73082  if( pExpr==0 ) return WRC_Continue;
73083  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
73084  testcase( ExprHasProperty(pExpr, EP_Reduced) );
73085  rc = pWalker->xExprCallback(pWalker, pExpr);
73086  if( rc==WRC_Continue
73087              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
73088    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
73089    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
73090    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73091      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
73092    }else{
73093      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
73094    }
73095  }
73096  return rc & WRC_Abort;
73097}
73098
73099/*
73100** Call sqlite3WalkExpr() for every expression in list p or until
73101** an abort request is seen.
73102*/
73103SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
73104  int i;
73105  struct ExprList_item *pItem;
73106  if( p ){
73107    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
73108      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
73109    }
73110  }
73111  return WRC_Continue;
73112}
73113
73114/*
73115** Walk all expressions associated with SELECT statement p.  Do
73116** not invoke the SELECT callback on p, but do (of course) invoke
73117** any expr callbacks and SELECT callbacks that come from subqueries.
73118** Return WRC_Abort or WRC_Continue.
73119*/
73120SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
73121  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
73122  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
73123  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
73124  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
73125  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
73126  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
73127  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
73128  return WRC_Continue;
73129}
73130
73131/*
73132** Walk the parse trees associated with all subqueries in the
73133** FROM clause of SELECT statement p.  Do not invoke the select
73134** callback on p, but do invoke it on each FROM clause subquery
73135** and on any subqueries further down in the tree.  Return
73136** WRC_Abort or WRC_Continue;
73137*/
73138SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
73139  SrcList *pSrc;
73140  int i;
73141  struct SrcList_item *pItem;
73142
73143  pSrc = p->pSrc;
73144  if( ALWAYS(pSrc) ){
73145    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
73146      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
73147        return WRC_Abort;
73148      }
73149    }
73150  }
73151  return WRC_Continue;
73152}
73153
73154/*
73155** Call sqlite3WalkExpr() for every expression in Select statement p.
73156** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
73157** on the compound select chain, p->pPrior.
73158**
73159** Return WRC_Continue under normal conditions.  Return WRC_Abort if
73160** there is an abort request.
73161**
73162** If the Walker does not have an xSelectCallback() then this routine
73163** is a no-op returning WRC_Continue.
73164*/
73165SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
73166  int rc;
73167  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
73168  rc = WRC_Continue;
73169  while( p  ){
73170    rc = pWalker->xSelectCallback(pWalker, p);
73171    if( rc ) break;
73172    if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
73173    if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
73174    p = p->pPrior;
73175  }
73176  return rc & WRC_Abort;
73177}
73178
73179/************** End of walker.c **********************************************/
73180/************** Begin file resolve.c *****************************************/
73181/*
73182** 2008 August 18
73183**
73184** The author disclaims copyright to this source code.  In place of
73185** a legal notice, here is a blessing:
73186**
73187**    May you do good and not evil.
73188**    May you find forgiveness for yourself and forgive others.
73189**    May you share freely, never taking more than you give.
73190**
73191*************************************************************************
73192**
73193** This file contains routines used for walking the parser tree and
73194** resolve all identifiers by associating them with a particular
73195** table and column.
73196*/
73197/* #include <stdlib.h> */
73198/* #include <string.h> */
73199
73200/*
73201** Turn the pExpr expression into an alias for the iCol-th column of the
73202** result set in pEList.
73203**
73204** If the result set column is a simple column reference, then this routine
73205** makes an exact copy.  But for any other kind of expression, this
73206** routine make a copy of the result set column as the argument to the
73207** TK_AS operator.  The TK_AS operator causes the expression to be
73208** evaluated just once and then reused for each alias.
73209**
73210** The reason for suppressing the TK_AS term when the expression is a simple
73211** column reference is so that the column reference will be recognized as
73212** usable by indices within the WHERE clause processing logic.
73213**
73214** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
73215** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
73216**
73217**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
73218**
73219** Is equivalent to:
73220**
73221**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
73222**
73223** The result of random()%5 in the GROUP BY clause is probably different
73224** from the result in the result-set.  We might fix this someday.  Or
73225** then again, we might not...
73226*/
73227static void resolveAlias(
73228  Parse *pParse,         /* Parsing context */
73229  ExprList *pEList,      /* A result set */
73230  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
73231  Expr *pExpr,           /* Transform this into an alias to the result set */
73232  const char *zType      /* "GROUP" or "ORDER" or "" */
73233){
73234  Expr *pOrig;           /* The iCol-th column of the result set */
73235  Expr *pDup;            /* Copy of pOrig */
73236  sqlite3 *db;           /* The database connection */
73237
73238  assert( iCol>=0 && iCol<pEList->nExpr );
73239  pOrig = pEList->a[iCol].pExpr;
73240  assert( pOrig!=0 );
73241  assert( pOrig->flags & EP_Resolved );
73242  db = pParse->db;
73243  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
73244    pDup = sqlite3ExprDup(db, pOrig, 0);
73245    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
73246    if( pDup==0 ) return;
73247    if( pEList->a[iCol].iAlias==0 ){
73248      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
73249    }
73250    pDup->iTable = pEList->a[iCol].iAlias;
73251  }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
73252    pDup = sqlite3ExprDup(db, pOrig, 0);
73253    if( pDup==0 ) return;
73254  }else{
73255    char *zToken = pOrig->u.zToken;
73256    assert( zToken!=0 );
73257    pOrig->u.zToken = 0;
73258    pDup = sqlite3ExprDup(db, pOrig, 0);
73259    pOrig->u.zToken = zToken;
73260    if( pDup==0 ) return;
73261    assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
73262    pDup->flags2 |= EP2_MallocedToken;
73263    pDup->u.zToken = sqlite3DbStrDup(db, zToken);
73264  }
73265  if( pExpr->flags & EP_ExpCollate ){
73266    pDup->pColl = pExpr->pColl;
73267    pDup->flags |= EP_ExpCollate;
73268  }
73269
73270  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
73271  ** prevents ExprDelete() from deleting the Expr structure itself,
73272  ** allowing it to be repopulated by the memcpy() on the following line.
73273  */
73274  ExprSetProperty(pExpr, EP_Static);
73275  sqlite3ExprDelete(db, pExpr);
73276  memcpy(pExpr, pDup, sizeof(*pExpr));
73277  sqlite3DbFree(db, pDup);
73278}
73279
73280
73281/*
73282** Return TRUE if the name zCol occurs anywhere in the USING clause.
73283**
73284** Return FALSE if the USING clause is NULL or if it does not contain
73285** zCol.
73286*/
73287static int nameInUsingClause(IdList *pUsing, const char *zCol){
73288  if( pUsing ){
73289    int k;
73290    for(k=0; k<pUsing->nId; k++){
73291      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
73292    }
73293  }
73294  return 0;
73295}
73296
73297
73298/*
73299** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
73300** that name in the set of source tables in pSrcList and make the pExpr
73301** expression node refer back to that source column.  The following changes
73302** are made to pExpr:
73303**
73304**    pExpr->iDb           Set the index in db->aDb[] of the database X
73305**                         (even if X is implied).
73306**    pExpr->iTable        Set to the cursor number for the table obtained
73307**                         from pSrcList.
73308**    pExpr->pTab          Points to the Table structure of X.Y (even if
73309**                         X and/or Y are implied.)
73310**    pExpr->iColumn       Set to the column number within the table.
73311**    pExpr->op            Set to TK_COLUMN.
73312**    pExpr->pLeft         Any expression this points to is deleted
73313**    pExpr->pRight        Any expression this points to is deleted.
73314**
73315** The zDb variable is the name of the database (the "X").  This value may be
73316** NULL meaning that name is of the form Y.Z or Z.  Any available database
73317** can be used.  The zTable variable is the name of the table (the "Y").  This
73318** value can be NULL if zDb is also NULL.  If zTable is NULL it
73319** means that the form of the name is Z and that columns from any table
73320** can be used.
73321**
73322** If the name cannot be resolved unambiguously, leave an error message
73323** in pParse and return WRC_Abort.  Return WRC_Prune on success.
73324*/
73325static int lookupName(
73326  Parse *pParse,       /* The parsing context */
73327  const char *zDb,     /* Name of the database containing table, or NULL */
73328  const char *zTab,    /* Name of table containing column, or NULL */
73329  const char *zCol,    /* Name of the column. */
73330  NameContext *pNC,    /* The name context used to resolve the name */
73331  Expr *pExpr          /* Make this EXPR node point to the selected column */
73332){
73333  int i, j;            /* Loop counters */
73334  int cnt = 0;                      /* Number of matching column names */
73335  int cntTab = 0;                   /* Number of matching table names */
73336  sqlite3 *db = pParse->db;         /* The database connection */
73337  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
73338  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
73339  NameContext *pTopNC = pNC;        /* First namecontext in the list */
73340  Schema *pSchema = 0;              /* Schema of the expression */
73341  int isTrigger = 0;
73342
73343  assert( pNC );     /* the name context cannot be NULL. */
73344  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
73345  assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
73346
73347  /* Initialize the node to no-match */
73348  pExpr->iTable = -1;
73349  pExpr->pTab = 0;
73350  ExprSetIrreducible(pExpr);
73351
73352  /* Start at the inner-most context and move outward until a match is found */
73353  while( pNC && cnt==0 ){
73354    ExprList *pEList;
73355    SrcList *pSrcList = pNC->pSrcList;
73356
73357    if( pSrcList ){
73358      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
73359        Table *pTab;
73360        int iDb;
73361        Column *pCol;
73362
73363        pTab = pItem->pTab;
73364        assert( pTab!=0 && pTab->zName!=0 );
73365        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73366        assert( pTab->nCol>0 );
73367        if( zTab ){
73368          if( pItem->zAlias ){
73369            char *zTabName = pItem->zAlias;
73370            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
73371          }else{
73372            char *zTabName = pTab->zName;
73373            if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
73374              continue;
73375            }
73376            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
73377              continue;
73378            }
73379          }
73380        }
73381        if( 0==(cntTab++) ){
73382          pExpr->iTable = pItem->iCursor;
73383          pExpr->pTab = pTab;
73384          pSchema = pTab->pSchema;
73385          pMatch = pItem;
73386        }
73387        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
73388          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
73389            /* If there has been exactly one prior match and this match
73390            ** is for the right-hand table of a NATURAL JOIN or is in a
73391            ** USING clause, then skip this match.
73392            */
73393            if( cnt==1 ){
73394              if( pItem->jointype & JT_NATURAL ) continue;
73395              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
73396            }
73397            cnt++;
73398            pExpr->iTable = pItem->iCursor;
73399            pExpr->pTab = pTab;
73400            pMatch = pItem;
73401            pSchema = pTab->pSchema;
73402            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
73403            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
73404            break;
73405          }
73406        }
73407      }
73408    }
73409
73410#ifndef SQLITE_OMIT_TRIGGER
73411    /* If we have not already resolved the name, then maybe
73412    ** it is a new.* or old.* trigger argument reference
73413    */
73414    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
73415      int op = pParse->eTriggerOp;
73416      Table *pTab = 0;
73417      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
73418      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
73419        pExpr->iTable = 1;
73420        pTab = pParse->pTriggerTab;
73421      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
73422        pExpr->iTable = 0;
73423        pTab = pParse->pTriggerTab;
73424      }
73425
73426      if( pTab ){
73427        int iCol;
73428        pSchema = pTab->pSchema;
73429        cntTab++;
73430        for(iCol=0; iCol<pTab->nCol; iCol++){
73431          Column *pCol = &pTab->aCol[iCol];
73432          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
73433            if( iCol==pTab->iPKey ){
73434              iCol = -1;
73435            }
73436            break;
73437          }
73438        }
73439        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
73440          iCol = -1;        /* IMP: R-44911-55124 */
73441        }
73442        if( iCol<pTab->nCol ){
73443          cnt++;
73444          if( iCol<0 ){
73445            pExpr->affinity = SQLITE_AFF_INTEGER;
73446          }else if( pExpr->iTable==0 ){
73447            testcase( iCol==31 );
73448            testcase( iCol==32 );
73449            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73450          }else{
73451            testcase( iCol==31 );
73452            testcase( iCol==32 );
73453            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73454          }
73455          pExpr->iColumn = (i16)iCol;
73456          pExpr->pTab = pTab;
73457          isTrigger = 1;
73458        }
73459      }
73460    }
73461#endif /* !defined(SQLITE_OMIT_TRIGGER) */
73462
73463    /*
73464    ** Perhaps the name is a reference to the ROWID
73465    */
73466    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
73467      cnt = 1;
73468      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
73469      pExpr->affinity = SQLITE_AFF_INTEGER;
73470    }
73471
73472    /*
73473    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
73474    ** might refer to an result-set alias.  This happens, for example, when
73475    ** we are resolving names in the WHERE clause of the following command:
73476    **
73477    **     SELECT a+b AS x FROM table WHERE x<10;
73478    **
73479    ** In cases like this, replace pExpr with a copy of the expression that
73480    ** forms the result set entry ("a+b" in the example) and return immediately.
73481    ** Note that the expression in the result set should have already been
73482    ** resolved by the time the WHERE clause is resolved.
73483    */
73484    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
73485      for(j=0; j<pEList->nExpr; j++){
73486        char *zAs = pEList->a[j].zName;
73487        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
73488          Expr *pOrig;
73489          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
73490          assert( pExpr->x.pList==0 );
73491          assert( pExpr->x.pSelect==0 );
73492          pOrig = pEList->a[j].pExpr;
73493          if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
73494            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
73495            return WRC_Abort;
73496          }
73497          resolveAlias(pParse, pEList, j, pExpr, "");
73498          cnt = 1;
73499          pMatch = 0;
73500          assert( zTab==0 && zDb==0 );
73501          goto lookupname_end;
73502        }
73503      }
73504    }
73505
73506    /* Advance to the next name context.  The loop will exit when either
73507    ** we have a match (cnt>0) or when we run out of name contexts.
73508    */
73509    if( cnt==0 ){
73510      pNC = pNC->pNext;
73511    }
73512  }
73513
73514  /*
73515  ** If X and Y are NULL (in other words if only the column name Z is
73516  ** supplied) and the value of Z is enclosed in double-quotes, then
73517  ** Z is a string literal if it doesn't match any column names.  In that
73518  ** case, we need to return right away and not make any changes to
73519  ** pExpr.
73520  **
73521  ** Because no reference was made to outer contexts, the pNC->nRef
73522  ** fields are not changed in any context.
73523  */
73524  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
73525    pExpr->op = TK_STRING;
73526    pExpr->pTab = 0;
73527    return WRC_Prune;
73528  }
73529
73530  /*
73531  ** cnt==0 means there was not match.  cnt>1 means there were two or
73532  ** more matches.  Either way, we have an error.
73533  */
73534  if( cnt!=1 ){
73535    const char *zErr;
73536    zErr = cnt==0 ? "no such column" : "ambiguous column name";
73537    if( zDb ){
73538      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
73539    }else if( zTab ){
73540      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
73541    }else{
73542      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
73543    }
73544    pParse->checkSchema = 1;
73545    pTopNC->nErr++;
73546  }
73547
73548  /* If a column from a table in pSrcList is referenced, then record
73549  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
73550  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
73551  ** column number is greater than the number of bits in the bitmask
73552  ** then set the high-order bit of the bitmask.
73553  */
73554  if( pExpr->iColumn>=0 && pMatch!=0 ){
73555    int n = pExpr->iColumn;
73556    testcase( n==BMS-1 );
73557    if( n>=BMS ){
73558      n = BMS-1;
73559    }
73560    assert( pMatch->iCursor==pExpr->iTable );
73561    pMatch->colUsed |= ((Bitmask)1)<<n;
73562  }
73563
73564  /* Clean up and return
73565  */
73566  sqlite3ExprDelete(db, pExpr->pLeft);
73567  pExpr->pLeft = 0;
73568  sqlite3ExprDelete(db, pExpr->pRight);
73569  pExpr->pRight = 0;
73570  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
73571lookupname_end:
73572  if( cnt==1 ){
73573    assert( pNC!=0 );
73574    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
73575    /* Increment the nRef value on all name contexts from TopNC up to
73576    ** the point where the name matched. */
73577    for(;;){
73578      assert( pTopNC!=0 );
73579      pTopNC->nRef++;
73580      if( pTopNC==pNC ) break;
73581      pTopNC = pTopNC->pNext;
73582    }
73583    return WRC_Prune;
73584  } else {
73585    return WRC_Abort;
73586  }
73587}
73588
73589/*
73590** Allocate and return a pointer to an expression to load the column iCol
73591** from datasource iSrc in SrcList pSrc.
73592*/
73593SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
73594  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
73595  if( p ){
73596    struct SrcList_item *pItem = &pSrc->a[iSrc];
73597    p->pTab = pItem->pTab;
73598    p->iTable = pItem->iCursor;
73599    if( p->pTab->iPKey==iCol ){
73600      p->iColumn = -1;
73601    }else{
73602      p->iColumn = (ynVar)iCol;
73603      testcase( iCol==BMS );
73604      testcase( iCol==BMS-1 );
73605      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
73606    }
73607    ExprSetProperty(p, EP_Resolved);
73608  }
73609  return p;
73610}
73611
73612/*
73613** This routine is callback for sqlite3WalkExpr().
73614**
73615** Resolve symbolic names into TK_COLUMN operators for the current
73616** node in the expression tree.  Return 0 to continue the search down
73617** the tree or 2 to abort the tree walk.
73618**
73619** This routine also does error checking and name resolution for
73620** function names.  The operator for aggregate functions is changed
73621** to TK_AGG_FUNCTION.
73622*/
73623static int resolveExprStep(Walker *pWalker, Expr *pExpr){
73624  NameContext *pNC;
73625  Parse *pParse;
73626
73627  pNC = pWalker->u.pNC;
73628  assert( pNC!=0 );
73629  pParse = pNC->pParse;
73630  assert( pParse==pWalker->pParse );
73631
73632  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
73633  ExprSetProperty(pExpr, EP_Resolved);
73634#ifndef NDEBUG
73635  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
73636    SrcList *pSrcList = pNC->pSrcList;
73637    int i;
73638    for(i=0; i<pNC->pSrcList->nSrc; i++){
73639      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
73640    }
73641  }
73642#endif
73643  switch( pExpr->op ){
73644
73645#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
73646    /* The special operator TK_ROW means use the rowid for the first
73647    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
73648    ** clause processing on UPDATE and DELETE statements.
73649    */
73650    case TK_ROW: {
73651      SrcList *pSrcList = pNC->pSrcList;
73652      struct SrcList_item *pItem;
73653      assert( pSrcList && pSrcList->nSrc==1 );
73654      pItem = pSrcList->a;
73655      pExpr->op = TK_COLUMN;
73656      pExpr->pTab = pItem->pTab;
73657      pExpr->iTable = pItem->iCursor;
73658      pExpr->iColumn = -1;
73659      pExpr->affinity = SQLITE_AFF_INTEGER;
73660      break;
73661    }
73662#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
73663
73664    /* A lone identifier is the name of a column.
73665    */
73666    case TK_ID: {
73667      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
73668    }
73669
73670    /* A table name and column name:     ID.ID
73671    ** Or a database, table and column:  ID.ID.ID
73672    */
73673    case TK_DOT: {
73674      const char *zColumn;
73675      const char *zTable;
73676      const char *zDb;
73677      Expr *pRight;
73678
73679      /* if( pSrcList==0 ) break; */
73680      pRight = pExpr->pRight;
73681      if( pRight->op==TK_ID ){
73682        zDb = 0;
73683        zTable = pExpr->pLeft->u.zToken;
73684        zColumn = pRight->u.zToken;
73685      }else{
73686        assert( pRight->op==TK_DOT );
73687        zDb = pExpr->pLeft->u.zToken;
73688        zTable = pRight->pLeft->u.zToken;
73689        zColumn = pRight->pRight->u.zToken;
73690      }
73691      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
73692    }
73693
73694    /* Resolve function names
73695    */
73696    case TK_CONST_FUNC:
73697    case TK_FUNCTION: {
73698      ExprList *pList = pExpr->x.pList;    /* The argument list */
73699      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
73700      int no_such_func = 0;       /* True if no such function exists */
73701      int wrong_num_args = 0;     /* True if wrong number of arguments */
73702      int is_agg = 0;             /* True if is an aggregate function */
73703      int auth;                   /* Authorization to use the function */
73704      int nId;                    /* Number of characters in function name */
73705      const char *zId;            /* The function name. */
73706      FuncDef *pDef;              /* Information about the function */
73707      u8 enc = ENC(pParse->db);   /* The database encoding */
73708
73709      testcase( pExpr->op==TK_CONST_FUNC );
73710      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73711      zId = pExpr->u.zToken;
73712      nId = sqlite3Strlen30(zId);
73713      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
73714      if( pDef==0 ){
73715        pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
73716        if( pDef==0 ){
73717          no_such_func = 1;
73718        }else{
73719          wrong_num_args = 1;
73720        }
73721      }else{
73722        is_agg = pDef->xFunc==0;
73723      }
73724#ifndef SQLITE_OMIT_AUTHORIZATION
73725      if( pDef ){
73726        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
73727        if( auth!=SQLITE_OK ){
73728          if( auth==SQLITE_DENY ){
73729            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
73730                                    pDef->zName);
73731            pNC->nErr++;
73732          }
73733          pExpr->op = TK_NULL;
73734          return WRC_Prune;
73735        }
73736      }
73737#endif
73738      if( is_agg && !pNC->allowAgg ){
73739        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
73740        pNC->nErr++;
73741        is_agg = 0;
73742      }else if( no_such_func ){
73743        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
73744        pNC->nErr++;
73745      }else if( wrong_num_args ){
73746        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
73747             nId, zId);
73748        pNC->nErr++;
73749      }
73750      if( is_agg ){
73751        pExpr->op = TK_AGG_FUNCTION;
73752        pNC->hasAgg = 1;
73753      }
73754      if( is_agg ) pNC->allowAgg = 0;
73755      sqlite3WalkExprList(pWalker, pList);
73756      if( is_agg ) pNC->allowAgg = 1;
73757      /* FIX ME:  Compute pExpr->affinity based on the expected return
73758      ** type of the function
73759      */
73760      return WRC_Prune;
73761    }
73762#ifndef SQLITE_OMIT_SUBQUERY
73763    case TK_SELECT:
73764    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
73765#endif
73766    case TK_IN: {
73767      testcase( pExpr->op==TK_IN );
73768      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73769        int nRef = pNC->nRef;
73770#ifndef SQLITE_OMIT_CHECK
73771        if( pNC->isCheck ){
73772          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
73773        }
73774#endif
73775        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
73776        assert( pNC->nRef>=nRef );
73777        if( nRef!=pNC->nRef ){
73778          ExprSetProperty(pExpr, EP_VarSelect);
73779        }
73780      }
73781      break;
73782    }
73783#ifndef SQLITE_OMIT_CHECK
73784    case TK_VARIABLE: {
73785      if( pNC->isCheck ){
73786        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
73787      }
73788      break;
73789    }
73790#endif
73791  }
73792  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
73793}
73794
73795/*
73796** pEList is a list of expressions which are really the result set of the
73797** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
73798** This routine checks to see if pE is a simple identifier which corresponds
73799** to the AS-name of one of the terms of the expression list.  If it is,
73800** this routine return an integer between 1 and N where N is the number of
73801** elements in pEList, corresponding to the matching entry.  If there is
73802** no match, or if pE is not a simple identifier, then this routine
73803** return 0.
73804**
73805** pEList has been resolved.  pE has not.
73806*/
73807static int resolveAsName(
73808  Parse *pParse,     /* Parsing context for error messages */
73809  ExprList *pEList,  /* List of expressions to scan */
73810  Expr *pE           /* Expression we are trying to match */
73811){
73812  int i;             /* Loop counter */
73813
73814  UNUSED_PARAMETER(pParse);
73815
73816  if( pE->op==TK_ID ){
73817    char *zCol = pE->u.zToken;
73818    for(i=0; i<pEList->nExpr; i++){
73819      char *zAs = pEList->a[i].zName;
73820      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
73821        return i+1;
73822      }
73823    }
73824  }
73825  return 0;
73826}
73827
73828/*
73829** pE is a pointer to an expression which is a single term in the
73830** ORDER BY of a compound SELECT.  The expression has not been
73831** name resolved.
73832**
73833** At the point this routine is called, we already know that the
73834** ORDER BY term is not an integer index into the result set.  That
73835** case is handled by the calling routine.
73836**
73837** Attempt to match pE against result set columns in the left-most
73838** SELECT statement.  Return the index i of the matching column,
73839** as an indication to the caller that it should sort by the i-th column.
73840** The left-most column is 1.  In other words, the value returned is the
73841** same integer value that would be used in the SQL statement to indicate
73842** the column.
73843**
73844** If there is no match, return 0.  Return -1 if an error occurs.
73845*/
73846static int resolveOrderByTermToExprList(
73847  Parse *pParse,     /* Parsing context for error messages */
73848  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
73849  Expr *pE           /* The specific ORDER BY term */
73850){
73851  int i;             /* Loop counter */
73852  ExprList *pEList;  /* The columns of the result set */
73853  NameContext nc;    /* Name context for resolving pE */
73854  sqlite3 *db;       /* Database connection */
73855  int rc;            /* Return code from subprocedures */
73856  u8 savedSuppErr;   /* Saved value of db->suppressErr */
73857
73858  assert( sqlite3ExprIsInteger(pE, &i)==0 );
73859  pEList = pSelect->pEList;
73860
73861  /* Resolve all names in the ORDER BY term expression
73862  */
73863  memset(&nc, 0, sizeof(nc));
73864  nc.pParse = pParse;
73865  nc.pSrcList = pSelect->pSrc;
73866  nc.pEList = pEList;
73867  nc.allowAgg = 1;
73868  nc.nErr = 0;
73869  db = pParse->db;
73870  savedSuppErr = db->suppressErr;
73871  db->suppressErr = 1;
73872  rc = sqlite3ResolveExprNames(&nc, pE);
73873  db->suppressErr = savedSuppErr;
73874  if( rc ) return 0;
73875
73876  /* Try to match the ORDER BY expression against an expression
73877  ** in the result set.  Return an 1-based index of the matching
73878  ** result-set entry.
73879  */
73880  for(i=0; i<pEList->nExpr; i++){
73881    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
73882      return i+1;
73883    }
73884  }
73885
73886  /* If no match, return 0. */
73887  return 0;
73888}
73889
73890/*
73891** Generate an ORDER BY or GROUP BY term out-of-range error.
73892*/
73893static void resolveOutOfRangeError(
73894  Parse *pParse,         /* The error context into which to write the error */
73895  const char *zType,     /* "ORDER" or "GROUP" */
73896  int i,                 /* The index (1-based) of the term out of range */
73897  int mx                 /* Largest permissible value of i */
73898){
73899  sqlite3ErrorMsg(pParse,
73900    "%r %s BY term out of range - should be "
73901    "between 1 and %d", i, zType, mx);
73902}
73903
73904/*
73905** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
73906** each term of the ORDER BY clause is a constant integer between 1
73907** and N where N is the number of columns in the compound SELECT.
73908**
73909** ORDER BY terms that are already an integer between 1 and N are
73910** unmodified.  ORDER BY terms that are integers outside the range of
73911** 1 through N generate an error.  ORDER BY terms that are expressions
73912** are matched against result set expressions of compound SELECT
73913** beginning with the left-most SELECT and working toward the right.
73914** At the first match, the ORDER BY expression is transformed into
73915** the integer column number.
73916**
73917** Return the number of errors seen.
73918*/
73919static int resolveCompoundOrderBy(
73920  Parse *pParse,        /* Parsing context.  Leave error messages here */
73921  Select *pSelect       /* The SELECT statement containing the ORDER BY */
73922){
73923  int i;
73924  ExprList *pOrderBy;
73925  ExprList *pEList;
73926  sqlite3 *db;
73927  int moreToDo = 1;
73928
73929  pOrderBy = pSelect->pOrderBy;
73930  if( pOrderBy==0 ) return 0;
73931  db = pParse->db;
73932#if SQLITE_MAX_COLUMN
73933  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
73934    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
73935    return 1;
73936  }
73937#endif
73938  for(i=0; i<pOrderBy->nExpr; i++){
73939    pOrderBy->a[i].done = 0;
73940  }
73941  pSelect->pNext = 0;
73942  while( pSelect->pPrior ){
73943    pSelect->pPrior->pNext = pSelect;
73944    pSelect = pSelect->pPrior;
73945  }
73946  while( pSelect && moreToDo ){
73947    struct ExprList_item *pItem;
73948    moreToDo = 0;
73949    pEList = pSelect->pEList;
73950    assert( pEList!=0 );
73951    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73952      int iCol = -1;
73953      Expr *pE, *pDup;
73954      if( pItem->done ) continue;
73955      pE = pItem->pExpr;
73956      if( sqlite3ExprIsInteger(pE, &iCol) ){
73957        if( iCol<=0 || iCol>pEList->nExpr ){
73958          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
73959          return 1;
73960        }
73961      }else{
73962        iCol = resolveAsName(pParse, pEList, pE);
73963        if( iCol==0 ){
73964          pDup = sqlite3ExprDup(db, pE, 0);
73965          if( !db->mallocFailed ){
73966            assert(pDup);
73967            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
73968          }
73969          sqlite3ExprDelete(db, pDup);
73970        }
73971      }
73972      if( iCol>0 ){
73973        CollSeq *pColl = pE->pColl;
73974        int flags = pE->flags & EP_ExpCollate;
73975        sqlite3ExprDelete(db, pE);
73976        pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
73977        if( pE==0 ) return 1;
73978        pE->pColl = pColl;
73979        pE->flags |= EP_IntValue | flags;
73980        pE->u.iValue = iCol;
73981        pItem->iOrderByCol = (u16)iCol;
73982        pItem->done = 1;
73983      }else{
73984        moreToDo = 1;
73985      }
73986    }
73987    pSelect = pSelect->pNext;
73988  }
73989  for(i=0; i<pOrderBy->nExpr; i++){
73990    if( pOrderBy->a[i].done==0 ){
73991      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
73992            "column in the result set", i+1);
73993      return 1;
73994    }
73995  }
73996  return 0;
73997}
73998
73999/*
74000** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
74001** the SELECT statement pSelect.  If any term is reference to a
74002** result set expression (as determined by the ExprList.a.iCol field)
74003** then convert that term into a copy of the corresponding result set
74004** column.
74005**
74006** If any errors are detected, add an error message to pParse and
74007** return non-zero.  Return zero if no errors are seen.
74008*/
74009SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
74010  Parse *pParse,        /* Parsing context.  Leave error messages here */
74011  Select *pSelect,      /* The SELECT statement containing the clause */
74012  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
74013  const char *zType     /* "ORDER" or "GROUP" */
74014){
74015  int i;
74016  sqlite3 *db = pParse->db;
74017  ExprList *pEList;
74018  struct ExprList_item *pItem;
74019
74020  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
74021#if SQLITE_MAX_COLUMN
74022  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
74023    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
74024    return 1;
74025  }
74026#endif
74027  pEList = pSelect->pEList;
74028  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
74029  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74030    if( pItem->iOrderByCol ){
74031      if( pItem->iOrderByCol>pEList->nExpr ){
74032        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
74033        return 1;
74034      }
74035      resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType);
74036    }
74037  }
74038  return 0;
74039}
74040
74041/*
74042** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
74043** The Name context of the SELECT statement is pNC.  zType is either
74044** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
74045**
74046** This routine resolves each term of the clause into an expression.
74047** If the order-by term is an integer I between 1 and N (where N is the
74048** number of columns in the result set of the SELECT) then the expression
74049** in the resolution is a copy of the I-th result-set expression.  If
74050** the order-by term is an identify that corresponds to the AS-name of
74051** a result-set expression, then the term resolves to a copy of the
74052** result-set expression.  Otherwise, the expression is resolved in
74053** the usual way - using sqlite3ResolveExprNames().
74054**
74055** This routine returns the number of errors.  If errors occur, then
74056** an appropriate error message might be left in pParse.  (OOM errors
74057** excepted.)
74058*/
74059static int resolveOrderGroupBy(
74060  NameContext *pNC,     /* The name context of the SELECT statement */
74061  Select *pSelect,      /* The SELECT statement holding pOrderBy */
74062  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
74063  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
74064){
74065  int i;                         /* Loop counter */
74066  int iCol;                      /* Column number */
74067  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
74068  Parse *pParse;                 /* Parsing context */
74069  int nResult;                   /* Number of terms in the result set */
74070
74071  if( pOrderBy==0 ) return 0;
74072  nResult = pSelect->pEList->nExpr;
74073  pParse = pNC->pParse;
74074  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74075    Expr *pE = pItem->pExpr;
74076    iCol = resolveAsName(pParse, pSelect->pEList, pE);
74077    if( iCol>0 ){
74078      /* If an AS-name match is found, mark this ORDER BY column as being
74079      ** a copy of the iCol-th result-set column.  The subsequent call to
74080      ** sqlite3ResolveOrderGroupBy() will convert the expression to a
74081      ** copy of the iCol-th result-set expression. */
74082      pItem->iOrderByCol = (u16)iCol;
74083      continue;
74084    }
74085    if( sqlite3ExprIsInteger(pE, &iCol) ){
74086      /* The ORDER BY term is an integer constant.  Again, set the column
74087      ** number so that sqlite3ResolveOrderGroupBy() will convert the
74088      ** order-by term to a copy of the result-set expression */
74089      if( iCol<1 ){
74090        resolveOutOfRangeError(pParse, zType, i+1, nResult);
74091        return 1;
74092      }
74093      pItem->iOrderByCol = (u16)iCol;
74094      continue;
74095    }
74096
74097    /* Otherwise, treat the ORDER BY term as an ordinary expression */
74098    pItem->iOrderByCol = 0;
74099    if( sqlite3ResolveExprNames(pNC, pE) ){
74100      return 1;
74101    }
74102  }
74103  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
74104}
74105
74106/*
74107** Resolve names in the SELECT statement p and all of its descendents.
74108*/
74109static int resolveSelectStep(Walker *pWalker, Select *p){
74110  NameContext *pOuterNC;  /* Context that contains this SELECT */
74111  NameContext sNC;        /* Name context of this SELECT */
74112  int isCompound;         /* True if p is a compound select */
74113  int nCompound;          /* Number of compound terms processed so far */
74114  Parse *pParse;          /* Parsing context */
74115  ExprList *pEList;       /* Result set expression list */
74116  int i;                  /* Loop counter */
74117  ExprList *pGroupBy;     /* The GROUP BY clause */
74118  Select *pLeftmost;      /* Left-most of SELECT of a compound */
74119  sqlite3 *db;            /* Database connection */
74120
74121
74122  assert( p!=0 );
74123  if( p->selFlags & SF_Resolved ){
74124    return WRC_Prune;
74125  }
74126  pOuterNC = pWalker->u.pNC;
74127  pParse = pWalker->pParse;
74128  db = pParse->db;
74129
74130  /* Normally sqlite3SelectExpand() will be called first and will have
74131  ** already expanded this SELECT.  However, if this is a subquery within
74132  ** an expression, sqlite3ResolveExprNames() will be called without a
74133  ** prior call to sqlite3SelectExpand().  When that happens, let
74134  ** sqlite3SelectPrep() do all of the processing for this SELECT.
74135  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
74136  ** this routine in the correct order.
74137  */
74138  if( (p->selFlags & SF_Expanded)==0 ){
74139    sqlite3SelectPrep(pParse, p, pOuterNC);
74140    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
74141  }
74142
74143  isCompound = p->pPrior!=0;
74144  nCompound = 0;
74145  pLeftmost = p;
74146  while( p ){
74147    assert( (p->selFlags & SF_Expanded)!=0 );
74148    assert( (p->selFlags & SF_Resolved)==0 );
74149    p->selFlags |= SF_Resolved;
74150
74151    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
74152    ** are not allowed to refer to any names, so pass an empty NameContext.
74153    */
74154    memset(&sNC, 0, sizeof(sNC));
74155    sNC.pParse = pParse;
74156    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
74157        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
74158      return WRC_Abort;
74159    }
74160
74161    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
74162    ** resolve the result-set expression list.
74163    */
74164    sNC.allowAgg = 1;
74165    sNC.pSrcList = p->pSrc;
74166    sNC.pNext = pOuterNC;
74167
74168    /* Resolve names in the result set. */
74169    pEList = p->pEList;
74170    assert( pEList!=0 );
74171    for(i=0; i<pEList->nExpr; i++){
74172      Expr *pX = pEList->a[i].pExpr;
74173      if( sqlite3ResolveExprNames(&sNC, pX) ){
74174        return WRC_Abort;
74175      }
74176    }
74177
74178    /* Recursively resolve names in all subqueries
74179    */
74180    for(i=0; i<p->pSrc->nSrc; i++){
74181      struct SrcList_item *pItem = &p->pSrc->a[i];
74182      if( pItem->pSelect ){
74183        NameContext *pNC;         /* Used to iterate name contexts */
74184        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
74185        const char *zSavedContext = pParse->zAuthContext;
74186
74187        /* Count the total number of references to pOuterNC and all of its
74188        ** parent contexts. After resolving references to expressions in
74189        ** pItem->pSelect, check if this value has changed. If so, then
74190        ** SELECT statement pItem->pSelect must be correlated. Set the
74191        ** pItem->isCorrelated flag if this is the case. */
74192        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
74193
74194        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
74195        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
74196        pParse->zAuthContext = zSavedContext;
74197        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
74198
74199        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
74200        assert( pItem->isCorrelated==0 && nRef<=0 );
74201        pItem->isCorrelated = (nRef!=0);
74202      }
74203    }
74204
74205    /* If there are no aggregate functions in the result-set, and no GROUP BY
74206    ** expression, do not allow aggregates in any of the other expressions.
74207    */
74208    assert( (p->selFlags & SF_Aggregate)==0 );
74209    pGroupBy = p->pGroupBy;
74210    if( pGroupBy || sNC.hasAgg ){
74211      p->selFlags |= SF_Aggregate;
74212    }else{
74213      sNC.allowAgg = 0;
74214    }
74215
74216    /* If a HAVING clause is present, then there must be a GROUP BY clause.
74217    */
74218    if( p->pHaving && !pGroupBy ){
74219      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
74220      return WRC_Abort;
74221    }
74222
74223    /* Add the expression list to the name-context before parsing the
74224    ** other expressions in the SELECT statement. This is so that
74225    ** expressions in the WHERE clause (etc.) can refer to expressions by
74226    ** aliases in the result set.
74227    **
74228    ** Minor point: If this is the case, then the expression will be
74229    ** re-evaluated for each reference to it.
74230    */
74231    sNC.pEList = p->pEList;
74232    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
74233       sqlite3ResolveExprNames(&sNC, p->pHaving)
74234    ){
74235      return WRC_Abort;
74236    }
74237
74238    /* The ORDER BY and GROUP BY clauses may not refer to terms in
74239    ** outer queries
74240    */
74241    sNC.pNext = 0;
74242    sNC.allowAgg = 1;
74243
74244    /* Process the ORDER BY clause for singleton SELECT statements.
74245    ** The ORDER BY clause for compounds SELECT statements is handled
74246    ** below, after all of the result-sets for all of the elements of
74247    ** the compound have been resolved.
74248    */
74249    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
74250      return WRC_Abort;
74251    }
74252    if( db->mallocFailed ){
74253      return WRC_Abort;
74254    }
74255
74256    /* Resolve the GROUP BY clause.  At the same time, make sure
74257    ** the GROUP BY clause does not contain aggregate functions.
74258    */
74259    if( pGroupBy ){
74260      struct ExprList_item *pItem;
74261
74262      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
74263        return WRC_Abort;
74264      }
74265      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
74266        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
74267          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
74268              "the GROUP BY clause");
74269          return WRC_Abort;
74270        }
74271      }
74272    }
74273
74274    /* Advance to the next term of the compound
74275    */
74276    p = p->pPrior;
74277    nCompound++;
74278  }
74279
74280  /* Resolve the ORDER BY on a compound SELECT after all terms of
74281  ** the compound have been resolved.
74282  */
74283  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
74284    return WRC_Abort;
74285  }
74286
74287  return WRC_Prune;
74288}
74289
74290/*
74291** This routine walks an expression tree and resolves references to
74292** table columns and result-set columns.  At the same time, do error
74293** checking on function usage and set a flag if any aggregate functions
74294** are seen.
74295**
74296** To resolve table columns references we look for nodes (or subtrees) of the
74297** form X.Y.Z or Y.Z or just Z where
74298**
74299**      X:   The name of a database.  Ex:  "main" or "temp" or
74300**           the symbolic name assigned to an ATTACH-ed database.
74301**
74302**      Y:   The name of a table in a FROM clause.  Or in a trigger
74303**           one of the special names "old" or "new".
74304**
74305**      Z:   The name of a column in table Y.
74306**
74307** The node at the root of the subtree is modified as follows:
74308**
74309**    Expr.op        Changed to TK_COLUMN
74310**    Expr.pTab      Points to the Table object for X.Y
74311**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
74312**    Expr.iTable    The VDBE cursor number for X.Y
74313**
74314**
74315** To resolve result-set references, look for expression nodes of the
74316** form Z (with no X and Y prefix) where the Z matches the right-hand
74317** size of an AS clause in the result-set of a SELECT.  The Z expression
74318** is replaced by a copy of the left-hand side of the result-set expression.
74319** Table-name and function resolution occurs on the substituted expression
74320** tree.  For example, in:
74321**
74322**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
74323**
74324** The "x" term of the order by is replaced by "a+b" to render:
74325**
74326**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
74327**
74328** Function calls are checked to make sure that the function is
74329** defined and that the correct number of arguments are specified.
74330** If the function is an aggregate function, then the pNC->hasAgg is
74331** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
74332** If an expression contains aggregate functions then the EP_Agg
74333** property on the expression is set.
74334**
74335** An error message is left in pParse if anything is amiss.  The number
74336** if errors is returned.
74337*/
74338SQLITE_PRIVATE int sqlite3ResolveExprNames(
74339  NameContext *pNC,       /* Namespace to resolve expressions in. */
74340  Expr *pExpr             /* The expression to be analyzed. */
74341){
74342  int savedHasAgg;
74343  Walker w;
74344
74345  if( pExpr==0 ) return 0;
74346#if SQLITE_MAX_EXPR_DEPTH>0
74347  {
74348    Parse *pParse = pNC->pParse;
74349    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
74350      return 1;
74351    }
74352    pParse->nHeight += pExpr->nHeight;
74353  }
74354#endif
74355  savedHasAgg = pNC->hasAgg;
74356  pNC->hasAgg = 0;
74357  w.xExprCallback = resolveExprStep;
74358  w.xSelectCallback = resolveSelectStep;
74359  w.pParse = pNC->pParse;
74360  w.u.pNC = pNC;
74361  sqlite3WalkExpr(&w, pExpr);
74362#if SQLITE_MAX_EXPR_DEPTH>0
74363  pNC->pParse->nHeight -= pExpr->nHeight;
74364#endif
74365  if( pNC->nErr>0 || w.pParse->nErr>0 ){
74366    ExprSetProperty(pExpr, EP_Error);
74367  }
74368  if( pNC->hasAgg ){
74369    ExprSetProperty(pExpr, EP_Agg);
74370  }else if( savedHasAgg ){
74371    pNC->hasAgg = 1;
74372  }
74373  return ExprHasProperty(pExpr, EP_Error);
74374}
74375
74376
74377/*
74378** Resolve all names in all expressions of a SELECT and in all
74379** decendents of the SELECT, including compounds off of p->pPrior,
74380** subqueries in expressions, and subqueries used as FROM clause
74381** terms.
74382**
74383** See sqlite3ResolveExprNames() for a description of the kinds of
74384** transformations that occur.
74385**
74386** All SELECT statements should have been expanded using
74387** sqlite3SelectExpand() prior to invoking this routine.
74388*/
74389SQLITE_PRIVATE void sqlite3ResolveSelectNames(
74390  Parse *pParse,         /* The parser context */
74391  Select *p,             /* The SELECT statement being coded. */
74392  NameContext *pOuterNC  /* Name context for parent SELECT statement */
74393){
74394  Walker w;
74395
74396  assert( p!=0 );
74397  w.xExprCallback = resolveExprStep;
74398  w.xSelectCallback = resolveSelectStep;
74399  w.pParse = pParse;
74400  w.u.pNC = pOuterNC;
74401  sqlite3WalkSelect(&w, p);
74402}
74403
74404/************** End of resolve.c *********************************************/
74405/************** Begin file expr.c ********************************************/
74406/*
74407** 2001 September 15
74408**
74409** The author disclaims copyright to this source code.  In place of
74410** a legal notice, here is a blessing:
74411**
74412**    May you do good and not evil.
74413**    May you find forgiveness for yourself and forgive others.
74414**    May you share freely, never taking more than you give.
74415**
74416*************************************************************************
74417** This file contains routines used for analyzing expressions and
74418** for generating VDBE code that evaluates expressions in SQLite.
74419*/
74420
74421/*
74422** Return the 'affinity' of the expression pExpr if any.
74423**
74424** If pExpr is a column, a reference to a column via an 'AS' alias,
74425** or a sub-select with a column as the return value, then the
74426** affinity of that column is returned. Otherwise, 0x00 is returned,
74427** indicating no affinity for the expression.
74428**
74429** i.e. the WHERE clause expresssions in the following statements all
74430** have an affinity:
74431**
74432** CREATE TABLE t1(a);
74433** SELECT * FROM t1 WHERE a;
74434** SELECT a AS b FROM t1 WHERE b;
74435** SELECT * FROM t1 WHERE (select a from t1);
74436*/
74437SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
74438  int op = pExpr->op;
74439  if( op==TK_SELECT ){
74440    assert( pExpr->flags&EP_xIsSelect );
74441    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
74442  }
74443#ifndef SQLITE_OMIT_CAST
74444  if( op==TK_CAST ){
74445    assert( !ExprHasProperty(pExpr, EP_IntValue) );
74446    return sqlite3AffinityType(pExpr->u.zToken);
74447  }
74448#endif
74449  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
74450   && pExpr->pTab!=0
74451  ){
74452    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
74453    ** a TK_COLUMN but was previously evaluated and cached in a register */
74454    int j = pExpr->iColumn;
74455    if( j<0 ) return SQLITE_AFF_INTEGER;
74456    assert( pExpr->pTab && j<pExpr->pTab->nCol );
74457    return pExpr->pTab->aCol[j].affinity;
74458  }
74459  return pExpr->affinity;
74460}
74461
74462/*
74463** Set the explicit collating sequence for an expression to the
74464** collating sequence supplied in the second argument.
74465*/
74466SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
74467  if( pExpr && pColl ){
74468    pExpr->pColl = pColl;
74469    pExpr->flags |= EP_ExpCollate;
74470  }
74471  return pExpr;
74472}
74473
74474/*
74475** Set the collating sequence for expression pExpr to be the collating
74476** sequence named by pToken.   Return a pointer to the revised expression.
74477** The collating sequence is marked as "explicit" using the EP_ExpCollate
74478** flag.  An explicit collating sequence will override implicit
74479** collating sequences.
74480*/
74481SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
74482  char *zColl = 0;            /* Dequoted name of collation sequence */
74483  CollSeq *pColl;
74484  sqlite3 *db = pParse->db;
74485  zColl = sqlite3NameFromToken(db, pCollName);
74486  pColl = sqlite3LocateCollSeq(pParse, zColl);
74487  sqlite3ExprSetColl(pExpr, pColl);
74488  sqlite3DbFree(db, zColl);
74489  return pExpr;
74490}
74491
74492/*
74493** Return the default collation sequence for the expression pExpr. If
74494** there is no default collation type, return 0.
74495*/
74496SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
74497  CollSeq *pColl = 0;
74498  Expr *p = pExpr;
74499  while( p ){
74500    int op;
74501    pColl = p->pColl;
74502    if( pColl ) break;
74503    op = p->op;
74504    if( p->pTab!=0 && (
74505        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
74506    )){
74507      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
74508      ** a TK_COLUMN but was previously evaluated and cached in a register */
74509      const char *zColl;
74510      int j = p->iColumn;
74511      if( j>=0 ){
74512        sqlite3 *db = pParse->db;
74513        zColl = p->pTab->aCol[j].zColl;
74514        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
74515        pExpr->pColl = pColl;
74516      }
74517      break;
74518    }
74519    if( op!=TK_CAST && op!=TK_UPLUS ){
74520      break;
74521    }
74522    p = p->pLeft;
74523  }
74524  if( sqlite3CheckCollSeq(pParse, pColl) ){
74525    pColl = 0;
74526  }
74527  return pColl;
74528}
74529
74530/*
74531** pExpr is an operand of a comparison operator.  aff2 is the
74532** type affinity of the other operand.  This routine returns the
74533** type affinity that should be used for the comparison operator.
74534*/
74535SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
74536  char aff1 = sqlite3ExprAffinity(pExpr);
74537  if( aff1 && aff2 ){
74538    /* Both sides of the comparison are columns. If one has numeric
74539    ** affinity, use that. Otherwise use no affinity.
74540    */
74541    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
74542      return SQLITE_AFF_NUMERIC;
74543    }else{
74544      return SQLITE_AFF_NONE;
74545    }
74546  }else if( !aff1 && !aff2 ){
74547    /* Neither side of the comparison is a column.  Compare the
74548    ** results directly.
74549    */
74550    return SQLITE_AFF_NONE;
74551  }else{
74552    /* One side is a column, the other is not. Use the columns affinity. */
74553    assert( aff1==0 || aff2==0 );
74554    return (aff1 + aff2);
74555  }
74556}
74557
74558/*
74559** pExpr is a comparison operator.  Return the type affinity that should
74560** be applied to both operands prior to doing the comparison.
74561*/
74562static char comparisonAffinity(Expr *pExpr){
74563  char aff;
74564  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
74565          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
74566          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
74567  assert( pExpr->pLeft );
74568  aff = sqlite3ExprAffinity(pExpr->pLeft);
74569  if( pExpr->pRight ){
74570    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
74571  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74572    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
74573  }else if( !aff ){
74574    aff = SQLITE_AFF_NONE;
74575  }
74576  return aff;
74577}
74578
74579/*
74580** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
74581** idx_affinity is the affinity of an indexed column. Return true
74582** if the index with affinity idx_affinity may be used to implement
74583** the comparison in pExpr.
74584*/
74585SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
74586  char aff = comparisonAffinity(pExpr);
74587  switch( aff ){
74588    case SQLITE_AFF_NONE:
74589      return 1;
74590    case SQLITE_AFF_TEXT:
74591      return idx_affinity==SQLITE_AFF_TEXT;
74592    default:
74593      return sqlite3IsNumericAffinity(idx_affinity);
74594  }
74595}
74596
74597/*
74598** Return the P5 value that should be used for a binary comparison
74599** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
74600*/
74601static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
74602  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
74603  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
74604  return aff;
74605}
74606
74607/*
74608** Return a pointer to the collation sequence that should be used by
74609** a binary comparison operator comparing pLeft and pRight.
74610**
74611** If the left hand expression has a collating sequence type, then it is
74612** used. Otherwise the collation sequence for the right hand expression
74613** is used, or the default (BINARY) if neither expression has a collating
74614** type.
74615**
74616** Argument pRight (but not pLeft) may be a null pointer. In this case,
74617** it is not considered.
74618*/
74619SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
74620  Parse *pParse,
74621  Expr *pLeft,
74622  Expr *pRight
74623){
74624  CollSeq *pColl;
74625  assert( pLeft );
74626  if( pLeft->flags & EP_ExpCollate ){
74627    assert( pLeft->pColl );
74628    pColl = pLeft->pColl;
74629  }else if( pRight && pRight->flags & EP_ExpCollate ){
74630    assert( pRight->pColl );
74631    pColl = pRight->pColl;
74632  }else{
74633    pColl = sqlite3ExprCollSeq(pParse, pLeft);
74634    if( !pColl ){
74635      pColl = sqlite3ExprCollSeq(pParse, pRight);
74636    }
74637  }
74638  return pColl;
74639}
74640
74641/*
74642** Generate code for a comparison operator.
74643*/
74644static int codeCompare(
74645  Parse *pParse,    /* The parsing (and code generating) context */
74646  Expr *pLeft,      /* The left operand */
74647  Expr *pRight,     /* The right operand */
74648  int opcode,       /* The comparison opcode */
74649  int in1, int in2, /* Register holding operands */
74650  int dest,         /* Jump here if true.  */
74651  int jumpIfNull    /* If true, jump if either operand is NULL */
74652){
74653  int p5;
74654  int addr;
74655  CollSeq *p4;
74656
74657  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
74658  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
74659  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
74660                           (void*)p4, P4_COLLSEQ);
74661  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
74662  return addr;
74663}
74664
74665#if SQLITE_MAX_EXPR_DEPTH>0
74666/*
74667** Check that argument nHeight is less than or equal to the maximum
74668** expression depth allowed. If it is not, leave an error message in
74669** pParse.
74670*/
74671SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
74672  int rc = SQLITE_OK;
74673  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
74674  if( nHeight>mxHeight ){
74675    sqlite3ErrorMsg(pParse,
74676       "Expression tree is too large (maximum depth %d)", mxHeight
74677    );
74678    rc = SQLITE_ERROR;
74679  }
74680  return rc;
74681}
74682
74683/* The following three functions, heightOfExpr(), heightOfExprList()
74684** and heightOfSelect(), are used to determine the maximum height
74685** of any expression tree referenced by the structure passed as the
74686** first argument.
74687**
74688** If this maximum height is greater than the current value pointed
74689** to by pnHeight, the second parameter, then set *pnHeight to that
74690** value.
74691*/
74692static void heightOfExpr(Expr *p, int *pnHeight){
74693  if( p ){
74694    if( p->nHeight>*pnHeight ){
74695      *pnHeight = p->nHeight;
74696    }
74697  }
74698}
74699static void heightOfExprList(ExprList *p, int *pnHeight){
74700  if( p ){
74701    int i;
74702    for(i=0; i<p->nExpr; i++){
74703      heightOfExpr(p->a[i].pExpr, pnHeight);
74704    }
74705  }
74706}
74707static void heightOfSelect(Select *p, int *pnHeight){
74708  if( p ){
74709    heightOfExpr(p->pWhere, pnHeight);
74710    heightOfExpr(p->pHaving, pnHeight);
74711    heightOfExpr(p->pLimit, pnHeight);
74712    heightOfExpr(p->pOffset, pnHeight);
74713    heightOfExprList(p->pEList, pnHeight);
74714    heightOfExprList(p->pGroupBy, pnHeight);
74715    heightOfExprList(p->pOrderBy, pnHeight);
74716    heightOfSelect(p->pPrior, pnHeight);
74717  }
74718}
74719
74720/*
74721** Set the Expr.nHeight variable in the structure passed as an
74722** argument. An expression with no children, Expr.pList or
74723** Expr.pSelect member has a height of 1. Any other expression
74724** has a height equal to the maximum height of any other
74725** referenced Expr plus one.
74726*/
74727static void exprSetHeight(Expr *p){
74728  int nHeight = 0;
74729  heightOfExpr(p->pLeft, &nHeight);
74730  heightOfExpr(p->pRight, &nHeight);
74731  if( ExprHasProperty(p, EP_xIsSelect) ){
74732    heightOfSelect(p->x.pSelect, &nHeight);
74733  }else{
74734    heightOfExprList(p->x.pList, &nHeight);
74735  }
74736  p->nHeight = nHeight + 1;
74737}
74738
74739/*
74740** Set the Expr.nHeight variable using the exprSetHeight() function. If
74741** the height is greater than the maximum allowed expression depth,
74742** leave an error in pParse.
74743*/
74744SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
74745  exprSetHeight(p);
74746  sqlite3ExprCheckHeight(pParse, p->nHeight);
74747}
74748
74749/*
74750** Return the maximum height of any expression tree referenced
74751** by the select statement passed as an argument.
74752*/
74753SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
74754  int nHeight = 0;
74755  heightOfSelect(p, &nHeight);
74756  return nHeight;
74757}
74758#else
74759  #define exprSetHeight(y)
74760#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
74761
74762/*
74763** This routine is the core allocator for Expr nodes.
74764**
74765** Construct a new expression node and return a pointer to it.  Memory
74766** for this node and for the pToken argument is a single allocation
74767** obtained from sqlite3DbMalloc().  The calling function
74768** is responsible for making sure the node eventually gets freed.
74769**
74770** If dequote is true, then the token (if it exists) is dequoted.
74771** If dequote is false, no dequoting is performance.  The deQuote
74772** parameter is ignored if pToken is NULL or if the token does not
74773** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
74774** then the EP_DblQuoted flag is set on the expression node.
74775**
74776** Special case:  If op==TK_INTEGER and pToken points to a string that
74777** can be translated into a 32-bit integer, then the token is not
74778** stored in u.zToken.  Instead, the integer values is written
74779** into u.iValue and the EP_IntValue flag is set.  No extra storage
74780** is allocated to hold the integer text and the dequote flag is ignored.
74781*/
74782SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
74783  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
74784  int op,                 /* Expression opcode */
74785  const Token *pToken,    /* Token argument.  Might be NULL */
74786  int dequote             /* True to dequote */
74787){
74788  Expr *pNew;
74789  int nExtra = 0;
74790  int iValue = 0;
74791
74792  if( pToken ){
74793    if( op!=TK_INTEGER || pToken->z==0
74794          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
74795      nExtra = pToken->n+1;
74796      assert( iValue>=0 );
74797    }
74798  }
74799  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
74800  if( pNew ){
74801    pNew->op = (u8)op;
74802    pNew->iAgg = -1;
74803    if( pToken ){
74804      if( nExtra==0 ){
74805        pNew->flags |= EP_IntValue;
74806        pNew->u.iValue = iValue;
74807      }else{
74808        int c;
74809        pNew->u.zToken = (char*)&pNew[1];
74810        assert( pToken->z!=0 || pToken->n==0 );
74811        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
74812        pNew->u.zToken[pToken->n] = 0;
74813        if( dequote && nExtra>=3
74814             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
74815          sqlite3Dequote(pNew->u.zToken);
74816          if( c=='"' ) pNew->flags |= EP_DblQuoted;
74817        }
74818      }
74819    }
74820#if SQLITE_MAX_EXPR_DEPTH>0
74821    pNew->nHeight = 1;
74822#endif
74823  }
74824  return pNew;
74825}
74826
74827/*
74828** Allocate a new expression node from a zero-terminated token that has
74829** already been dequoted.
74830*/
74831SQLITE_PRIVATE Expr *sqlite3Expr(
74832  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
74833  int op,                 /* Expression opcode */
74834  const char *zToken      /* Token argument.  Might be NULL */
74835){
74836  Token x;
74837  x.z = zToken;
74838  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
74839  return sqlite3ExprAlloc(db, op, &x, 0);
74840}
74841
74842/*
74843** Attach subtrees pLeft and pRight to the Expr node pRoot.
74844**
74845** If pRoot==NULL that means that a memory allocation error has occurred.
74846** In that case, delete the subtrees pLeft and pRight.
74847*/
74848SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
74849  sqlite3 *db,
74850  Expr *pRoot,
74851  Expr *pLeft,
74852  Expr *pRight
74853){
74854  if( pRoot==0 ){
74855    assert( db->mallocFailed );
74856    sqlite3ExprDelete(db, pLeft);
74857    sqlite3ExprDelete(db, pRight);
74858  }else{
74859    if( pRight ){
74860      pRoot->pRight = pRight;
74861      if( pRight->flags & EP_ExpCollate ){
74862        pRoot->flags |= EP_ExpCollate;
74863        pRoot->pColl = pRight->pColl;
74864      }
74865    }
74866    if( pLeft ){
74867      pRoot->pLeft = pLeft;
74868      if( pLeft->flags & EP_ExpCollate ){
74869        pRoot->flags |= EP_ExpCollate;
74870        pRoot->pColl = pLeft->pColl;
74871      }
74872    }
74873    exprSetHeight(pRoot);
74874  }
74875}
74876
74877/*
74878** Allocate a Expr node which joins as many as two subtrees.
74879**
74880** One or both of the subtrees can be NULL.  Return a pointer to the new
74881** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
74882** free the subtrees and return NULL.
74883*/
74884SQLITE_PRIVATE Expr *sqlite3PExpr(
74885  Parse *pParse,          /* Parsing context */
74886  int op,                 /* Expression opcode */
74887  Expr *pLeft,            /* Left operand */
74888  Expr *pRight,           /* Right operand */
74889  const Token *pToken     /* Argument token */
74890){
74891  Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
74892  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
74893  if( p ) {
74894    sqlite3ExprCheckHeight(pParse, p->nHeight);
74895  }
74896  return p;
74897}
74898
74899/*
74900** Join two expressions using an AND operator.  If either expression is
74901** NULL, then just return the other expression.
74902*/
74903SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
74904  if( pLeft==0 ){
74905    return pRight;
74906  }else if( pRight==0 ){
74907    return pLeft;
74908  }else{
74909    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
74910    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
74911    return pNew;
74912  }
74913}
74914
74915/*
74916** Construct a new expression node for a function with multiple
74917** arguments.
74918*/
74919SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
74920  Expr *pNew;
74921  sqlite3 *db = pParse->db;
74922  assert( pToken );
74923  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
74924  if( pNew==0 ){
74925    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
74926    return 0;
74927  }
74928  pNew->x.pList = pList;
74929  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
74930  sqlite3ExprSetHeight(pParse, pNew);
74931  return pNew;
74932}
74933
74934/*
74935** Assign a variable number to an expression that encodes a wildcard
74936** in the original SQL statement.
74937**
74938** Wildcards consisting of a single "?" are assigned the next sequential
74939** variable number.
74940**
74941** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
74942** sure "nnn" is not too be to avoid a denial of service attack when
74943** the SQL statement comes from an external source.
74944**
74945** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
74946** as the previous instance of the same wildcard.  Or if this is the first
74947** instance of the wildcard, the next sequenial variable number is
74948** assigned.
74949*/
74950SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
74951  sqlite3 *db = pParse->db;
74952  const char *z;
74953
74954  if( pExpr==0 ) return;
74955  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
74956  z = pExpr->u.zToken;
74957  assert( z!=0 );
74958  assert( z[0]!=0 );
74959  if( z[1]==0 ){
74960    /* Wildcard of the form "?".  Assign the next variable number */
74961    assert( z[0]=='?' );
74962    pExpr->iColumn = (ynVar)(++pParse->nVar);
74963  }else{
74964    ynVar x = 0;
74965    u32 n = sqlite3Strlen30(z);
74966    if( z[0]=='?' ){
74967      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
74968      ** use it as the variable number */
74969      i64 i;
74970      int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
74971      pExpr->iColumn = x = (ynVar)i;
74972      testcase( i==0 );
74973      testcase( i==1 );
74974      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
74975      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
74976      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
74977        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
74978            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
74979        x = 0;
74980      }
74981      if( i>pParse->nVar ){
74982        pParse->nVar = (int)i;
74983      }
74984    }else{
74985      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
74986      ** number as the prior appearance of the same name, or if the name
74987      ** has never appeared before, reuse the same variable number
74988      */
74989      ynVar i;
74990      for(i=0; i<pParse->nzVar; i++){
74991        if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
74992          pExpr->iColumn = x = (ynVar)i+1;
74993          break;
74994        }
74995      }
74996      if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
74997    }
74998    if( x>0 ){
74999      if( x>pParse->nzVar ){
75000        char **a;
75001        a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
75002        if( a==0 ) return;  /* Error reported through db->mallocFailed */
75003        pParse->azVar = a;
75004        memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
75005        pParse->nzVar = x;
75006      }
75007      if( z[0]!='?' || pParse->azVar[x-1]==0 ){
75008        sqlite3DbFree(db, pParse->azVar[x-1]);
75009        pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
75010      }
75011    }
75012  }
75013  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
75014    sqlite3ErrorMsg(pParse, "too many SQL variables");
75015  }
75016}
75017
75018/*
75019** Recursively delete an expression tree.
75020*/
75021SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
75022  if( p==0 ) return;
75023  /* Sanity check: Assert that the IntValue is non-negative if it exists */
75024  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
75025  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
75026    sqlite3ExprDelete(db, p->pLeft);
75027    sqlite3ExprDelete(db, p->pRight);
75028    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
75029      sqlite3DbFree(db, p->u.zToken);
75030    }
75031    if( ExprHasProperty(p, EP_xIsSelect) ){
75032      sqlite3SelectDelete(db, p->x.pSelect);
75033    }else{
75034      sqlite3ExprListDelete(db, p->x.pList);
75035    }
75036  }
75037  if( !ExprHasProperty(p, EP_Static) ){
75038    sqlite3DbFree(db, p);
75039  }
75040}
75041
75042/*
75043** Return the number of bytes allocated for the expression structure
75044** passed as the first argument. This is always one of EXPR_FULLSIZE,
75045** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
75046*/
75047static int exprStructSize(Expr *p){
75048  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
75049  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
75050  return EXPR_FULLSIZE;
75051}
75052
75053/*
75054** The dupedExpr*Size() routines each return the number of bytes required
75055** to store a copy of an expression or expression tree.  They differ in
75056** how much of the tree is measured.
75057**
75058**     dupedExprStructSize()     Size of only the Expr structure
75059**     dupedExprNodeSize()       Size of Expr + space for token
75060**     dupedExprSize()           Expr + token + subtree components
75061**
75062***************************************************************************
75063**
75064** The dupedExprStructSize() function returns two values OR-ed together:
75065** (1) the space required for a copy of the Expr structure only and
75066** (2) the EP_xxx flags that indicate what the structure size should be.
75067** The return values is always one of:
75068**
75069**      EXPR_FULLSIZE
75070**      EXPR_REDUCEDSIZE   | EP_Reduced
75071**      EXPR_TOKENONLYSIZE | EP_TokenOnly
75072**
75073** The size of the structure can be found by masking the return value
75074** of this routine with 0xfff.  The flags can be found by masking the
75075** return value with EP_Reduced|EP_TokenOnly.
75076**
75077** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
75078** (unreduced) Expr objects as they or originally constructed by the parser.
75079** During expression analysis, extra information is computed and moved into
75080** later parts of teh Expr object and that extra information might get chopped
75081** off if the expression is reduced.  Note also that it does not work to
75082** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
75083** to reduce a pristine expression tree from the parser.  The implementation
75084** of dupedExprStructSize() contain multiple assert() statements that attempt
75085** to enforce this constraint.
75086*/
75087static int dupedExprStructSize(Expr *p, int flags){
75088  int nSize;
75089  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
75090  if( 0==(flags&EXPRDUP_REDUCE) ){
75091    nSize = EXPR_FULLSIZE;
75092  }else{
75093    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
75094    assert( !ExprHasProperty(p, EP_FromJoin) );
75095    assert( (p->flags2 & EP2_MallocedToken)==0 );
75096    assert( (p->flags2 & EP2_Irreducible)==0 );
75097    if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
75098      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
75099    }else{
75100      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
75101    }
75102  }
75103  return nSize;
75104}
75105
75106/*
75107** This function returns the space in bytes required to store the copy
75108** of the Expr structure and a copy of the Expr.u.zToken string (if that
75109** string is defined.)
75110*/
75111static int dupedExprNodeSize(Expr *p, int flags){
75112  int nByte = dupedExprStructSize(p, flags) & 0xfff;
75113  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
75114    nByte += sqlite3Strlen30(p->u.zToken)+1;
75115  }
75116  return ROUND8(nByte);
75117}
75118
75119/*
75120** Return the number of bytes required to create a duplicate of the
75121** expression passed as the first argument. The second argument is a
75122** mask containing EXPRDUP_XXX flags.
75123**
75124** The value returned includes space to create a copy of the Expr struct
75125** itself and the buffer referred to by Expr.u.zToken, if any.
75126**
75127** If the EXPRDUP_REDUCE flag is set, then the return value includes
75128** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
75129** and Expr.pRight variables (but not for any structures pointed to or
75130** descended from the Expr.x.pList or Expr.x.pSelect variables).
75131*/
75132static int dupedExprSize(Expr *p, int flags){
75133  int nByte = 0;
75134  if( p ){
75135    nByte = dupedExprNodeSize(p, flags);
75136    if( flags&EXPRDUP_REDUCE ){
75137      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
75138    }
75139  }
75140  return nByte;
75141}
75142
75143/*
75144** This function is similar to sqlite3ExprDup(), except that if pzBuffer
75145** is not NULL then *pzBuffer is assumed to point to a buffer large enough
75146** to store the copy of expression p, the copies of p->u.zToken
75147** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
75148** if any. Before returning, *pzBuffer is set to the first byte passed the
75149** portion of the buffer copied into by this function.
75150*/
75151static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
75152  Expr *pNew = 0;                      /* Value to return */
75153  if( p ){
75154    const int isReduced = (flags&EXPRDUP_REDUCE);
75155    u8 *zAlloc;
75156    u32 staticFlag = 0;
75157
75158    assert( pzBuffer==0 || isReduced );
75159
75160    /* Figure out where to write the new Expr structure. */
75161    if( pzBuffer ){
75162      zAlloc = *pzBuffer;
75163      staticFlag = EP_Static;
75164    }else{
75165      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
75166    }
75167    pNew = (Expr *)zAlloc;
75168
75169    if( pNew ){
75170      /* Set nNewSize to the size allocated for the structure pointed to
75171      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
75172      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
75173      ** by the copy of the p->u.zToken string (if any).
75174      */
75175      const unsigned nStructSize = dupedExprStructSize(p, flags);
75176      const int nNewSize = nStructSize & 0xfff;
75177      int nToken;
75178      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
75179        nToken = sqlite3Strlen30(p->u.zToken) + 1;
75180      }else{
75181        nToken = 0;
75182      }
75183      if( isReduced ){
75184        assert( ExprHasProperty(p, EP_Reduced)==0 );
75185        memcpy(zAlloc, p, nNewSize);
75186      }else{
75187        int nSize = exprStructSize(p);
75188        memcpy(zAlloc, p, nSize);
75189        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
75190      }
75191
75192      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
75193      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
75194      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
75195      pNew->flags |= staticFlag;
75196
75197      /* Copy the p->u.zToken string, if any. */
75198      if( nToken ){
75199        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
75200        memcpy(zToken, p->u.zToken, nToken);
75201      }
75202
75203      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
75204        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
75205        if( ExprHasProperty(p, EP_xIsSelect) ){
75206          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
75207        }else{
75208          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
75209        }
75210      }
75211
75212      /* Fill in pNew->pLeft and pNew->pRight. */
75213      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
75214        zAlloc += dupedExprNodeSize(p, flags);
75215        if( ExprHasProperty(pNew, EP_Reduced) ){
75216          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
75217          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
75218        }
75219        if( pzBuffer ){
75220          *pzBuffer = zAlloc;
75221        }
75222      }else{
75223        pNew->flags2 = 0;
75224        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
75225          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
75226          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
75227        }
75228      }
75229
75230    }
75231  }
75232  return pNew;
75233}
75234
75235/*
75236** The following group of routines make deep copies of expressions,
75237** expression lists, ID lists, and select statements.  The copies can
75238** be deleted (by being passed to their respective ...Delete() routines)
75239** without effecting the originals.
75240**
75241** The expression list, ID, and source lists return by sqlite3ExprListDup(),
75242** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
75243** by subsequent calls to sqlite*ListAppend() routines.
75244**
75245** Any tables that the SrcList might point to are not duplicated.
75246**
75247** The flags parameter contains a combination of the EXPRDUP_XXX flags.
75248** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
75249** truncated version of the usual Expr structure that will be stored as
75250** part of the in-memory representation of the database schema.
75251*/
75252SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
75253  return exprDup(db, p, flags, 0);
75254}
75255SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
75256  ExprList *pNew;
75257  struct ExprList_item *pItem, *pOldItem;
75258  int i;
75259  if( p==0 ) return 0;
75260  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
75261  if( pNew==0 ) return 0;
75262  pNew->iECursor = 0;
75263  pNew->nExpr = i = p->nExpr;
75264  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
75265  pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
75266  if( pItem==0 ){
75267    sqlite3DbFree(db, pNew);
75268    return 0;
75269  }
75270  pOldItem = p->a;
75271  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
75272    Expr *pOldExpr = pOldItem->pExpr;
75273    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
75274    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
75275    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
75276    pItem->sortOrder = pOldItem->sortOrder;
75277    pItem->done = 0;
75278    pItem->iOrderByCol = pOldItem->iOrderByCol;
75279    pItem->iAlias = pOldItem->iAlias;
75280  }
75281  return pNew;
75282}
75283
75284/*
75285** If cursors, triggers, views and subqueries are all omitted from
75286** the build, then none of the following routines, except for
75287** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
75288** called with a NULL argument.
75289*/
75290#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
75291 || !defined(SQLITE_OMIT_SUBQUERY)
75292SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
75293  SrcList *pNew;
75294  int i;
75295  int nByte;
75296  if( p==0 ) return 0;
75297  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
75298  pNew = sqlite3DbMallocRaw(db, nByte );
75299  if( pNew==0 ) return 0;
75300  pNew->nSrc = pNew->nAlloc = p->nSrc;
75301  for(i=0; i<p->nSrc; i++){
75302    struct SrcList_item *pNewItem = &pNew->a[i];
75303    struct SrcList_item *pOldItem = &p->a[i];
75304    Table *pTab;
75305    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
75306    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
75307    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
75308    pNewItem->jointype = pOldItem->jointype;
75309    pNewItem->iCursor = pOldItem->iCursor;
75310    pNewItem->addrFillSub = pOldItem->addrFillSub;
75311    pNewItem->regReturn = pOldItem->regReturn;
75312    pNewItem->isCorrelated = pOldItem->isCorrelated;
75313    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
75314    pNewItem->notIndexed = pOldItem->notIndexed;
75315    pNewItem->pIndex = pOldItem->pIndex;
75316    pTab = pNewItem->pTab = pOldItem->pTab;
75317    if( pTab ){
75318      pTab->nRef++;
75319    }
75320    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
75321    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
75322    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
75323    pNewItem->colUsed = pOldItem->colUsed;
75324  }
75325  return pNew;
75326}
75327SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
75328  IdList *pNew;
75329  int i;
75330  if( p==0 ) return 0;
75331  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
75332  if( pNew==0 ) return 0;
75333  pNew->nId = p->nId;
75334  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
75335  if( pNew->a==0 ){
75336    sqlite3DbFree(db, pNew);
75337    return 0;
75338  }
75339  /* Note that because the size of the allocation for p->a[] is not
75340  ** necessarily a power of two, sqlite3IdListAppend() may not be called
75341  ** on the duplicate created by this function. */
75342  for(i=0; i<p->nId; i++){
75343    struct IdList_item *pNewItem = &pNew->a[i];
75344    struct IdList_item *pOldItem = &p->a[i];
75345    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
75346    pNewItem->idx = pOldItem->idx;
75347  }
75348  return pNew;
75349}
75350SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
75351  Select *pNew, *pPrior;
75352  if( p==0 ) return 0;
75353  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
75354  if( pNew==0 ) return 0;
75355  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
75356  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
75357  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
75358  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
75359  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
75360  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
75361  pNew->op = p->op;
75362  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
75363  if( pPrior ) pPrior->pNext = pNew;
75364  pNew->pNext = 0;
75365  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
75366  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
75367  pNew->iLimit = 0;
75368  pNew->iOffset = 0;
75369  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
75370  pNew->pRightmost = 0;
75371  pNew->addrOpenEphm[0] = -1;
75372  pNew->addrOpenEphm[1] = -1;
75373  pNew->addrOpenEphm[2] = -1;
75374  return pNew;
75375}
75376#else
75377SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
75378  assert( p==0 );
75379  return 0;
75380}
75381#endif
75382
75383
75384/*
75385** Add a new element to the end of an expression list.  If pList is
75386** initially NULL, then create a new expression list.
75387**
75388** If a memory allocation error occurs, the entire list is freed and
75389** NULL is returned.  If non-NULL is returned, then it is guaranteed
75390** that the new entry was successfully appended.
75391*/
75392SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
75393  Parse *pParse,          /* Parsing context */
75394  ExprList *pList,        /* List to which to append. Might be NULL */
75395  Expr *pExpr             /* Expression to be appended. Might be NULL */
75396){
75397  sqlite3 *db = pParse->db;
75398  if( pList==0 ){
75399    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
75400    if( pList==0 ){
75401      goto no_mem;
75402    }
75403    pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
75404    if( pList->a==0 ) goto no_mem;
75405  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
75406    struct ExprList_item *a;
75407    assert( pList->nExpr>0 );
75408    a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
75409    if( a==0 ){
75410      goto no_mem;
75411    }
75412    pList->a = a;
75413  }
75414  assert( pList->a!=0 );
75415  if( 1 ){
75416    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
75417    memset(pItem, 0, sizeof(*pItem));
75418    pItem->pExpr = pExpr;
75419  }
75420  return pList;
75421
75422no_mem:
75423  /* Avoid leaking memory if malloc has failed. */
75424  sqlite3ExprDelete(db, pExpr);
75425  sqlite3ExprListDelete(db, pList);
75426  return 0;
75427}
75428
75429/*
75430** Set the ExprList.a[].zName element of the most recently added item
75431** on the expression list.
75432**
75433** pList might be NULL following an OOM error.  But pName should never be
75434** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75435** is set.
75436*/
75437SQLITE_PRIVATE void sqlite3ExprListSetName(
75438  Parse *pParse,          /* Parsing context */
75439  ExprList *pList,        /* List to which to add the span. */
75440  Token *pName,           /* Name to be added */
75441  int dequote             /* True to cause the name to be dequoted */
75442){
75443  assert( pList!=0 || pParse->db->mallocFailed!=0 );
75444  if( pList ){
75445    struct ExprList_item *pItem;
75446    assert( pList->nExpr>0 );
75447    pItem = &pList->a[pList->nExpr-1];
75448    assert( pItem->zName==0 );
75449    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
75450    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
75451  }
75452}
75453
75454/*
75455** Set the ExprList.a[].zSpan element of the most recently added item
75456** on the expression list.
75457**
75458** pList might be NULL following an OOM error.  But pSpan should never be
75459** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75460** is set.
75461*/
75462SQLITE_PRIVATE void sqlite3ExprListSetSpan(
75463  Parse *pParse,          /* Parsing context */
75464  ExprList *pList,        /* List to which to add the span. */
75465  ExprSpan *pSpan         /* The span to be added */
75466){
75467  sqlite3 *db = pParse->db;
75468  assert( pList!=0 || db->mallocFailed!=0 );
75469  if( pList ){
75470    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
75471    assert( pList->nExpr>0 );
75472    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
75473    sqlite3DbFree(db, pItem->zSpan);
75474    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
75475                                    (int)(pSpan->zEnd - pSpan->zStart));
75476  }
75477}
75478
75479/*
75480** If the expression list pEList contains more than iLimit elements,
75481** leave an error message in pParse.
75482*/
75483SQLITE_PRIVATE void sqlite3ExprListCheckLength(
75484  Parse *pParse,
75485  ExprList *pEList,
75486  const char *zObject
75487){
75488  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
75489  testcase( pEList && pEList->nExpr==mx );
75490  testcase( pEList && pEList->nExpr==mx+1 );
75491  if( pEList && pEList->nExpr>mx ){
75492    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
75493  }
75494}
75495
75496/*
75497** Delete an entire expression list.
75498*/
75499SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
75500  int i;
75501  struct ExprList_item *pItem;
75502  if( pList==0 ) return;
75503  assert( pList->a!=0 || pList->nExpr==0 );
75504  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
75505    sqlite3ExprDelete(db, pItem->pExpr);
75506    sqlite3DbFree(db, pItem->zName);
75507    sqlite3DbFree(db, pItem->zSpan);
75508  }
75509  sqlite3DbFree(db, pList->a);
75510  sqlite3DbFree(db, pList);
75511}
75512
75513/*
75514** These routines are Walker callbacks.  Walker.u.pi is a pointer
75515** to an integer.  These routines are checking an expression to see
75516** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
75517** not constant.
75518**
75519** These callback routines are used to implement the following:
75520**
75521**     sqlite3ExprIsConstant()
75522**     sqlite3ExprIsConstantNotJoin()
75523**     sqlite3ExprIsConstantOrFunction()
75524**
75525*/
75526static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
75527
75528  /* If pWalker->u.i is 3 then any term of the expression that comes from
75529  ** the ON or USING clauses of a join disqualifies the expression
75530  ** from being considered constant. */
75531  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
75532    pWalker->u.i = 0;
75533    return WRC_Abort;
75534  }
75535
75536  switch( pExpr->op ){
75537    /* Consider functions to be constant if all their arguments are constant
75538    ** and pWalker->u.i==2 */
75539    case TK_FUNCTION:
75540      if( pWalker->u.i==2 ) return 0;
75541      /* Fall through */
75542    case TK_ID:
75543    case TK_COLUMN:
75544    case TK_AGG_FUNCTION:
75545    case TK_AGG_COLUMN:
75546      testcase( pExpr->op==TK_ID );
75547      testcase( pExpr->op==TK_COLUMN );
75548      testcase( pExpr->op==TK_AGG_FUNCTION );
75549      testcase( pExpr->op==TK_AGG_COLUMN );
75550      pWalker->u.i = 0;
75551      return WRC_Abort;
75552    default:
75553      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
75554      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
75555      return WRC_Continue;
75556  }
75557}
75558static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
75559  UNUSED_PARAMETER(NotUsed);
75560  pWalker->u.i = 0;
75561  return WRC_Abort;
75562}
75563static int exprIsConst(Expr *p, int initFlag){
75564  Walker w;
75565  w.u.i = initFlag;
75566  w.xExprCallback = exprNodeIsConstant;
75567  w.xSelectCallback = selectNodeIsConstant;
75568  sqlite3WalkExpr(&w, p);
75569  return w.u.i;
75570}
75571
75572/*
75573** Walk an expression tree.  Return 1 if the expression is constant
75574** and 0 if it involves variables or function calls.
75575**
75576** For the purposes of this function, a double-quoted string (ex: "abc")
75577** is considered a variable but a single-quoted string (ex: 'abc') is
75578** a constant.
75579*/
75580SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
75581  return exprIsConst(p, 1);
75582}
75583
75584/*
75585** Walk an expression tree.  Return 1 if the expression is constant
75586** that does no originate from the ON or USING clauses of a join.
75587** Return 0 if it involves variables or function calls or terms from
75588** an ON or USING clause.
75589*/
75590SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
75591  return exprIsConst(p, 3);
75592}
75593
75594/*
75595** Walk an expression tree.  Return 1 if the expression is constant
75596** or a function call with constant arguments.  Return and 0 if there
75597** are any variables.
75598**
75599** For the purposes of this function, a double-quoted string (ex: "abc")
75600** is considered a variable but a single-quoted string (ex: 'abc') is
75601** a constant.
75602*/
75603SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
75604  return exprIsConst(p, 2);
75605}
75606
75607/*
75608** If the expression p codes a constant integer that is small enough
75609** to fit in a 32-bit integer, return 1 and put the value of the integer
75610** in *pValue.  If the expression is not an integer or if it is too big
75611** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
75612*/
75613SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
75614  int rc = 0;
75615
75616  /* If an expression is an integer literal that fits in a signed 32-bit
75617  ** integer, then the EP_IntValue flag will have already been set */
75618  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
75619           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
75620
75621  if( p->flags & EP_IntValue ){
75622    *pValue = p->u.iValue;
75623    return 1;
75624  }
75625  switch( p->op ){
75626    case TK_UPLUS: {
75627      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
75628      break;
75629    }
75630    case TK_UMINUS: {
75631      int v;
75632      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
75633        *pValue = -v;
75634        rc = 1;
75635      }
75636      break;
75637    }
75638    default: break;
75639  }
75640  return rc;
75641}
75642
75643/*
75644** Return FALSE if there is no chance that the expression can be NULL.
75645**
75646** If the expression might be NULL or if the expression is too complex
75647** to tell return TRUE.
75648**
75649** This routine is used as an optimization, to skip OP_IsNull opcodes
75650** when we know that a value cannot be NULL.  Hence, a false positive
75651** (returning TRUE when in fact the expression can never be NULL) might
75652** be a small performance hit but is otherwise harmless.  On the other
75653** hand, a false negative (returning FALSE when the result could be NULL)
75654** will likely result in an incorrect answer.  So when in doubt, return
75655** TRUE.
75656*/
75657SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
75658  u8 op;
75659  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75660  op = p->op;
75661  if( op==TK_REGISTER ) op = p->op2;
75662  switch( op ){
75663    case TK_INTEGER:
75664    case TK_STRING:
75665    case TK_FLOAT:
75666    case TK_BLOB:
75667      return 0;
75668    default:
75669      return 1;
75670  }
75671}
75672
75673/*
75674** Generate an OP_IsNull instruction that tests register iReg and jumps
75675** to location iDest if the value in iReg is NULL.  The value in iReg
75676** was computed by pExpr.  If we can look at pExpr at compile-time and
75677** determine that it can never generate a NULL, then the OP_IsNull operation
75678** can be omitted.
75679*/
75680SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
75681  Vdbe *v,            /* The VDBE under construction */
75682  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
75683  int iReg,           /* Test the value in this register for NULL */
75684  int iDest           /* Jump here if the value is null */
75685){
75686  if( sqlite3ExprCanBeNull(pExpr) ){
75687    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
75688  }
75689}
75690
75691/*
75692** Return TRUE if the given expression is a constant which would be
75693** unchanged by OP_Affinity with the affinity given in the second
75694** argument.
75695**
75696** This routine is used to determine if the OP_Affinity operation
75697** can be omitted.  When in doubt return FALSE.  A false negative
75698** is harmless.  A false positive, however, can result in the wrong
75699** answer.
75700*/
75701SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
75702  u8 op;
75703  if( aff==SQLITE_AFF_NONE ) return 1;
75704  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75705  op = p->op;
75706  if( op==TK_REGISTER ) op = p->op2;
75707  switch( op ){
75708    case TK_INTEGER: {
75709      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
75710    }
75711    case TK_FLOAT: {
75712      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
75713    }
75714    case TK_STRING: {
75715      return aff==SQLITE_AFF_TEXT;
75716    }
75717    case TK_BLOB: {
75718      return 1;
75719    }
75720    case TK_COLUMN: {
75721      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
75722      return p->iColumn<0
75723          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
75724    }
75725    default: {
75726      return 0;
75727    }
75728  }
75729}
75730
75731/*
75732** Return TRUE if the given string is a row-id column name.
75733*/
75734SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
75735  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
75736  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
75737  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
75738  return 0;
75739}
75740
75741/*
75742** Return true if we are able to the IN operator optimization on a
75743** query of the form
75744**
75745**       x IN (SELECT ...)
75746**
75747** Where the SELECT... clause is as specified by the parameter to this
75748** routine.
75749**
75750** The Select object passed in has already been preprocessed and no
75751** errors have been found.
75752*/
75753#ifndef SQLITE_OMIT_SUBQUERY
75754static int isCandidateForInOpt(Select *p){
75755  SrcList *pSrc;
75756  ExprList *pEList;
75757  Table *pTab;
75758  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
75759  if( p->pPrior ) return 0;              /* Not a compound SELECT */
75760  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
75761    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
75762    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
75763    return 0; /* No DISTINCT keyword and no aggregate functions */
75764  }
75765  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
75766  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
75767  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
75768  if( p->pWhere ) return 0;              /* Has no WHERE clause */
75769  pSrc = p->pSrc;
75770  assert( pSrc!=0 );
75771  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
75772  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
75773  pTab = pSrc->a[0].pTab;
75774  if( NEVER(pTab==0) ) return 0;
75775  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
75776  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
75777  pEList = p->pEList;
75778  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
75779  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
75780  return 1;
75781}
75782#endif /* SQLITE_OMIT_SUBQUERY */
75783
75784/*
75785** Code an OP_Once instruction and allocate space for its flag. Return the
75786** address of the new instruction.
75787*/
75788SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
75789  Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
75790  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
75791}
75792
75793/*
75794** This function is used by the implementation of the IN (...) operator.
75795** It's job is to find or create a b-tree structure that may be used
75796** either to test for membership of the (...) set or to iterate through
75797** its members, skipping duplicates.
75798**
75799** The index of the cursor opened on the b-tree (database table, database index
75800** or ephermal table) is stored in pX->iTable before this function returns.
75801** The returned value of this function indicates the b-tree type, as follows:
75802**
75803**   IN_INDEX_ROWID - The cursor was opened on a database table.
75804**   IN_INDEX_INDEX - The cursor was opened on a database index.
75805**   IN_INDEX_EPH -   The cursor was opened on a specially created and
75806**                    populated epheremal table.
75807**
75808** An existing b-tree may only be used if the SELECT is of the simple
75809** form:
75810**
75811**     SELECT <column> FROM <table>
75812**
75813** If the prNotFound parameter is 0, then the b-tree will be used to iterate
75814** through the set members, skipping any duplicates. In this case an
75815** epheremal table must be used unless the selected <column> is guaranteed
75816** to be unique - either because it is an INTEGER PRIMARY KEY or it
75817** has a UNIQUE constraint or UNIQUE index.
75818**
75819** If the prNotFound parameter is not 0, then the b-tree will be used
75820** for fast set membership tests. In this case an epheremal table must
75821** be used unless <column> is an INTEGER PRIMARY KEY or an index can
75822** be found with <column> as its left-most column.
75823**
75824** When the b-tree is being used for membership tests, the calling function
75825** needs to know whether or not the structure contains an SQL NULL
75826** value in order to correctly evaluate expressions like "X IN (Y, Z)".
75827** If there is any chance that the (...) might contain a NULL value at
75828** runtime, then a register is allocated and the register number written
75829** to *prNotFound. If there is no chance that the (...) contains a
75830** NULL value, then *prNotFound is left unchanged.
75831**
75832** If a register is allocated and its location stored in *prNotFound, then
75833** its initial value is NULL.  If the (...) does not remain constant
75834** for the duration of the query (i.e. the SELECT within the (...)
75835** is a correlated subquery) then the value of the allocated register is
75836** reset to NULL each time the subquery is rerun. This allows the
75837** caller to use vdbe code equivalent to the following:
75838**
75839**   if( register==NULL ){
75840**     has_null = <test if data structure contains null>
75841**     register = 1
75842**   }
75843**
75844** in order to avoid running the <test if data structure contains null>
75845** test more often than is necessary.
75846*/
75847#ifndef SQLITE_OMIT_SUBQUERY
75848SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
75849  Select *p;                            /* SELECT to the right of IN operator */
75850  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
75851  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
75852  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
75853  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
75854
75855  assert( pX->op==TK_IN );
75856
75857  /* Check to see if an existing table or index can be used to
75858  ** satisfy the query.  This is preferable to generating a new
75859  ** ephemeral table.
75860  */
75861  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
75862  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
75863    sqlite3 *db = pParse->db;              /* Database connection */
75864    Table *pTab;                           /* Table <table>. */
75865    Expr *pExpr;                           /* Expression <column> */
75866    int iCol;                              /* Index of column <column> */
75867    int iDb;                               /* Database idx for pTab */
75868
75869    assert( p );                        /* Because of isCandidateForInOpt(p) */
75870    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
75871    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
75872    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
75873    pTab = p->pSrc->a[0].pTab;
75874    pExpr = p->pEList->a[0].pExpr;
75875    iCol = pExpr->iColumn;
75876
75877    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
75878    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75879    sqlite3CodeVerifySchema(pParse, iDb);
75880    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75881
75882    /* This function is only called from two places. In both cases the vdbe
75883    ** has already been allocated. So assume sqlite3GetVdbe() is always
75884    ** successful here.
75885    */
75886    assert(v);
75887    if( iCol<0 ){
75888      int iAddr;
75889
75890      iAddr = sqlite3CodeOnce(pParse);
75891
75892      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
75893      eType = IN_INDEX_ROWID;
75894
75895      sqlite3VdbeJumpHere(v, iAddr);
75896    }else{
75897      Index *pIdx;                         /* Iterator variable */
75898
75899      /* The collation sequence used by the comparison. If an index is to
75900      ** be used in place of a temp-table, it must be ordered according
75901      ** to this collation sequence.  */
75902      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
75903
75904      /* Check that the affinity that will be used to perform the
75905      ** comparison is the same as the affinity of the column. If
75906      ** it is not, it is not possible to use any index.
75907      */
75908      char aff = comparisonAffinity(pX);
75909      int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
75910
75911      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
75912        if( (pIdx->aiColumn[0]==iCol)
75913         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
75914         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
75915        ){
75916          int iAddr;
75917          char *pKey;
75918
75919          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
75920          iAddr = sqlite3CodeOnce(pParse);
75921
75922          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
75923                               pKey,P4_KEYINFO_HANDOFF);
75924          VdbeComment((v, "%s", pIdx->zName));
75925          eType = IN_INDEX_INDEX;
75926
75927          sqlite3VdbeJumpHere(v, iAddr);
75928          if( prNotFound && !pTab->aCol[iCol].notNull ){
75929            *prNotFound = ++pParse->nMem;
75930            sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
75931          }
75932        }
75933      }
75934    }
75935  }
75936
75937  if( eType==0 ){
75938    /* Could not found an existing table or index to use as the RHS b-tree.
75939    ** We will have to generate an ephemeral table to do the job.
75940    */
75941    double savedNQueryLoop = pParse->nQueryLoop;
75942    int rMayHaveNull = 0;
75943    eType = IN_INDEX_EPH;
75944    if( prNotFound ){
75945      *prNotFound = rMayHaveNull = ++pParse->nMem;
75946      sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
75947    }else{
75948      testcase( pParse->nQueryLoop>(double)1 );
75949      pParse->nQueryLoop = (double)1;
75950      if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
75951        eType = IN_INDEX_ROWID;
75952      }
75953    }
75954    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
75955    pParse->nQueryLoop = savedNQueryLoop;
75956  }else{
75957    pX->iTable = iTab;
75958  }
75959  return eType;
75960}
75961#endif
75962
75963/*
75964** Generate code for scalar subqueries used as a subquery expression, EXISTS,
75965** or IN operators.  Examples:
75966**
75967**     (SELECT a FROM b)          -- subquery
75968**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
75969**     x IN (4,5,11)              -- IN operator with list on right-hand side
75970**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
75971**
75972** The pExpr parameter describes the expression that contains the IN
75973** operator or subquery.
75974**
75975** If parameter isRowid is non-zero, then expression pExpr is guaranteed
75976** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
75977** to some integer key column of a table B-Tree. In this case, use an
75978** intkey B-Tree to store the set of IN(...) values instead of the usual
75979** (slower) variable length keys B-Tree.
75980**
75981** If rMayHaveNull is non-zero, that means that the operation is an IN
75982** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
75983** Furthermore, the IN is in a WHERE clause and that we really want
75984** to iterate over the RHS of the IN operator in order to quickly locate
75985** all corresponding LHS elements.  All this routine does is initialize
75986** the register given by rMayHaveNull to NULL.  Calling routines will take
75987** care of changing this register value to non-NULL if the RHS is NULL-free.
75988**
75989** If rMayHaveNull is zero, that means that the subquery is being used
75990** for membership testing only.  There is no need to initialize any
75991** registers to indicate the presense or absence of NULLs on the RHS.
75992**
75993** For a SELECT or EXISTS operator, return the register that holds the
75994** result.  For IN operators or if an error occurs, the return value is 0.
75995*/
75996#ifndef SQLITE_OMIT_SUBQUERY
75997SQLITE_PRIVATE int sqlite3CodeSubselect(
75998  Parse *pParse,          /* Parsing context */
75999  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
76000  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
76001  int isRowid             /* If true, LHS of IN operator is a rowid */
76002){
76003  int testAddr = -1;                      /* One-time test address */
76004  int rReg = 0;                           /* Register storing resulting */
76005  Vdbe *v = sqlite3GetVdbe(pParse);
76006  if( NEVER(v==0) ) return 0;
76007  sqlite3ExprCachePush(pParse);
76008
76009  /* This code must be run in its entirety every time it is encountered
76010  ** if any of the following is true:
76011  **
76012  **    *  The right-hand side is a correlated subquery
76013  **    *  The right-hand side is an expression list containing variables
76014  **    *  We are inside a trigger
76015  **
76016  ** If all of the above are false, then we can run this code just once
76017  ** save the results, and reuse the same result on subsequent invocations.
76018  */
76019  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
76020    testAddr = sqlite3CodeOnce(pParse);
76021  }
76022
76023#ifndef SQLITE_OMIT_EXPLAIN
76024  if( pParse->explain==2 ){
76025    char *zMsg = sqlite3MPrintf(
76026        pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
76027        pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
76028    );
76029    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
76030  }
76031#endif
76032
76033  switch( pExpr->op ){
76034    case TK_IN: {
76035      char affinity;              /* Affinity of the LHS of the IN */
76036      KeyInfo keyInfo;            /* Keyinfo for the generated table */
76037      int addr;                   /* Address of OP_OpenEphemeral instruction */
76038      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
76039
76040      if( rMayHaveNull ){
76041        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
76042      }
76043
76044      affinity = sqlite3ExprAffinity(pLeft);
76045
76046      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
76047      ** expression it is handled the same way.  An ephemeral table is
76048      ** filled with single-field index keys representing the results
76049      ** from the SELECT or the <exprlist>.
76050      **
76051      ** If the 'x' expression is a column value, or the SELECT...
76052      ** statement returns a column value, then the affinity of that
76053      ** column is used to build the index keys. If both 'x' and the
76054      ** SELECT... statement are columns, then numeric affinity is used
76055      ** if either column has NUMERIC or INTEGER affinity. If neither
76056      ** 'x' nor the SELECT... statement are columns, then numeric affinity
76057      ** is used.
76058      */
76059      pExpr->iTable = pParse->nTab++;
76060      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
76061      if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
76062      memset(&keyInfo, 0, sizeof(keyInfo));
76063      keyInfo.nField = 1;
76064
76065      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76066        /* Case 1:     expr IN (SELECT ...)
76067        **
76068        ** Generate code to write the results of the select into the temporary
76069        ** table allocated and opened above.
76070        */
76071        SelectDest dest;
76072        ExprList *pEList;
76073
76074        assert( !isRowid );
76075        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
76076        dest.affinity = (u8)affinity;
76077        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
76078        pExpr->x.pSelect->iLimit = 0;
76079        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
76080          return 0;
76081        }
76082        pEList = pExpr->x.pSelect->pEList;
76083        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
76084          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
76085              pEList->a[0].pExpr);
76086        }
76087      }else if( ALWAYS(pExpr->x.pList!=0) ){
76088        /* Case 2:     expr IN (exprlist)
76089        **
76090        ** For each expression, build an index key from the evaluation and
76091        ** store it in the temporary table. If <expr> is a column, then use
76092        ** that columns affinity when building index keys. If <expr> is not
76093        ** a column, use numeric affinity.
76094        */
76095        int i;
76096        ExprList *pList = pExpr->x.pList;
76097        struct ExprList_item *pItem;
76098        int r1, r2, r3;
76099
76100        if( !affinity ){
76101          affinity = SQLITE_AFF_NONE;
76102        }
76103        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
76104
76105        /* Loop through each expression in <exprlist>. */
76106        r1 = sqlite3GetTempReg(pParse);
76107        r2 = sqlite3GetTempReg(pParse);
76108        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
76109        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
76110          Expr *pE2 = pItem->pExpr;
76111          int iValToIns;
76112
76113          /* If the expression is not constant then we will need to
76114          ** disable the test that was generated above that makes sure
76115          ** this code only executes once.  Because for a non-constant
76116          ** expression we need to rerun this code each time.
76117          */
76118          if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
76119            sqlite3VdbeChangeToNoop(v, testAddr);
76120            testAddr = -1;
76121          }
76122
76123          /* Evaluate the expression and insert it into the temp table */
76124          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
76125            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
76126          }else{
76127            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
76128            if( isRowid ){
76129              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
76130                                sqlite3VdbeCurrentAddr(v)+2);
76131              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
76132            }else{
76133              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
76134              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
76135              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
76136            }
76137          }
76138        }
76139        sqlite3ReleaseTempReg(pParse, r1);
76140        sqlite3ReleaseTempReg(pParse, r2);
76141      }
76142      if( !isRowid ){
76143        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
76144      }
76145      break;
76146    }
76147
76148    case TK_EXISTS:
76149    case TK_SELECT:
76150    default: {
76151      /* If this has to be a scalar SELECT.  Generate code to put the
76152      ** value of this select in a memory cell and record the number
76153      ** of the memory cell in iColumn.  If this is an EXISTS, write
76154      ** an integer 0 (not exists) or 1 (exists) into a memory cell
76155      ** and record that memory cell in iColumn.
76156      */
76157      Select *pSel;                         /* SELECT statement to encode */
76158      SelectDest dest;                      /* How to deal with SELECt result */
76159
76160      testcase( pExpr->op==TK_EXISTS );
76161      testcase( pExpr->op==TK_SELECT );
76162      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
76163
76164      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
76165      pSel = pExpr->x.pSelect;
76166      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
76167      if( pExpr->op==TK_SELECT ){
76168        dest.eDest = SRT_Mem;
76169        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
76170        VdbeComment((v, "Init subquery result"));
76171      }else{
76172        dest.eDest = SRT_Exists;
76173        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
76174        VdbeComment((v, "Init EXISTS result"));
76175      }
76176      sqlite3ExprDelete(pParse->db, pSel->pLimit);
76177      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
76178                                  &sqlite3IntTokens[1]);
76179      pSel->iLimit = 0;
76180      if( sqlite3Select(pParse, pSel, &dest) ){
76181        return 0;
76182      }
76183      rReg = dest.iParm;
76184      ExprSetIrreducible(pExpr);
76185      break;
76186    }
76187  }
76188
76189  if( testAddr>=0 ){
76190    sqlite3VdbeJumpHere(v, testAddr);
76191  }
76192  sqlite3ExprCachePop(pParse, 1);
76193
76194  return rReg;
76195}
76196#endif /* SQLITE_OMIT_SUBQUERY */
76197
76198#ifndef SQLITE_OMIT_SUBQUERY
76199/*
76200** Generate code for an IN expression.
76201**
76202**      x IN (SELECT ...)
76203**      x IN (value, value, ...)
76204**
76205** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
76206** is an array of zero or more values.  The expression is true if the LHS is
76207** contained within the RHS.  The value of the expression is unknown (NULL)
76208** if the LHS is NULL or if the LHS is not contained within the RHS and the
76209** RHS contains one or more NULL values.
76210**
76211** This routine generates code will jump to destIfFalse if the LHS is not
76212** contained within the RHS.  If due to NULLs we cannot determine if the LHS
76213** is contained in the RHS then jump to destIfNull.  If the LHS is contained
76214** within the RHS then fall through.
76215*/
76216static void sqlite3ExprCodeIN(
76217  Parse *pParse,        /* Parsing and code generating context */
76218  Expr *pExpr,          /* The IN expression */
76219  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
76220  int destIfNull        /* Jump here if the results are unknown due to NULLs */
76221){
76222  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
76223  char affinity;        /* Comparison affinity to use */
76224  int eType;            /* Type of the RHS */
76225  int r1;               /* Temporary use register */
76226  Vdbe *v;              /* Statement under construction */
76227
76228  /* Compute the RHS.   After this step, the table with cursor
76229  ** pExpr->iTable will contains the values that make up the RHS.
76230  */
76231  v = pParse->pVdbe;
76232  assert( v!=0 );       /* OOM detected prior to this routine */
76233  VdbeNoopComment((v, "begin IN expr"));
76234  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
76235
76236  /* Figure out the affinity to use to create a key from the results
76237  ** of the expression. affinityStr stores a static string suitable for
76238  ** P4 of OP_MakeRecord.
76239  */
76240  affinity = comparisonAffinity(pExpr);
76241
76242  /* Code the LHS, the <expr> from "<expr> IN (...)".
76243  */
76244  sqlite3ExprCachePush(pParse);
76245  r1 = sqlite3GetTempReg(pParse);
76246  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
76247
76248  /* If the LHS is NULL, then the result is either false or NULL depending
76249  ** on whether the RHS is empty or not, respectively.
76250  */
76251  if( destIfNull==destIfFalse ){
76252    /* Shortcut for the common case where the false and NULL outcomes are
76253    ** the same. */
76254    sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
76255  }else{
76256    int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
76257    sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
76258    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
76259    sqlite3VdbeJumpHere(v, addr1);
76260  }
76261
76262  if( eType==IN_INDEX_ROWID ){
76263    /* In this case, the RHS is the ROWID of table b-tree
76264    */
76265    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
76266    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
76267  }else{
76268    /* In this case, the RHS is an index b-tree.
76269    */
76270    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
76271
76272    /* If the set membership test fails, then the result of the
76273    ** "x IN (...)" expression must be either 0 or NULL. If the set
76274    ** contains no NULL values, then the result is 0. If the set
76275    ** contains one or more NULL values, then the result of the
76276    ** expression is also NULL.
76277    */
76278    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
76279      /* This branch runs if it is known at compile time that the RHS
76280      ** cannot contain NULL values. This happens as the result
76281      ** of a "NOT NULL" constraint in the database schema.
76282      **
76283      ** Also run this branch if NULL is equivalent to FALSE
76284      ** for this particular IN operator.
76285      */
76286      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
76287
76288    }else{
76289      /* In this branch, the RHS of the IN might contain a NULL and
76290      ** the presence of a NULL on the RHS makes a difference in the
76291      ** outcome.
76292      */
76293      int j1, j2, j3;
76294
76295      /* First check to see if the LHS is contained in the RHS.  If so,
76296      ** then the presence of NULLs in the RHS does not matter, so jump
76297      ** over all of the code that follows.
76298      */
76299      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
76300
76301      /* Here we begin generating code that runs if the LHS is not
76302      ** contained within the RHS.  Generate additional code that
76303      ** tests the RHS for NULLs.  If the RHS contains a NULL then
76304      ** jump to destIfNull.  If there are no NULLs in the RHS then
76305      ** jump to destIfFalse.
76306      */
76307      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
76308      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
76309      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
76310      sqlite3VdbeJumpHere(v, j3);
76311      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
76312      sqlite3VdbeJumpHere(v, j2);
76313
76314      /* Jump to the appropriate target depending on whether or not
76315      ** the RHS contains a NULL
76316      */
76317      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
76318      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
76319
76320      /* The OP_Found at the top of this branch jumps here when true,
76321      ** causing the overall IN expression evaluation to fall through.
76322      */
76323      sqlite3VdbeJumpHere(v, j1);
76324    }
76325  }
76326  sqlite3ReleaseTempReg(pParse, r1);
76327  sqlite3ExprCachePop(pParse, 1);
76328  VdbeComment((v, "end IN expr"));
76329}
76330#endif /* SQLITE_OMIT_SUBQUERY */
76331
76332/*
76333** Duplicate an 8-byte value
76334*/
76335static char *dup8bytes(Vdbe *v, const char *in){
76336  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
76337  if( out ){
76338    memcpy(out, in, 8);
76339  }
76340  return out;
76341}
76342
76343#ifndef SQLITE_OMIT_FLOATING_POINT
76344/*
76345** Generate an instruction that will put the floating point
76346** value described by z[0..n-1] into register iMem.
76347**
76348** The z[] string will probably not be zero-terminated.  But the
76349** z[n] character is guaranteed to be something that does not look
76350** like the continuation of the number.
76351*/
76352static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
76353  if( ALWAYS(z!=0) ){
76354    double value;
76355    char *zV;
76356    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
76357    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
76358    if( negateFlag ) value = -value;
76359    zV = dup8bytes(v, (char*)&value);
76360    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
76361  }
76362}
76363#endif
76364
76365
76366/*
76367** Generate an instruction that will put the integer describe by
76368** text z[0..n-1] into register iMem.
76369**
76370** Expr.u.zToken is always UTF8 and zero-terminated.
76371*/
76372static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
76373  Vdbe *v = pParse->pVdbe;
76374  if( pExpr->flags & EP_IntValue ){
76375    int i = pExpr->u.iValue;
76376    assert( i>=0 );
76377    if( negFlag ) i = -i;
76378    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
76379  }else{
76380    int c;
76381    i64 value;
76382    const char *z = pExpr->u.zToken;
76383    assert( z!=0 );
76384    c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
76385    if( c==0 || (c==2 && negFlag) ){
76386      char *zV;
76387      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
76388      zV = dup8bytes(v, (char*)&value);
76389      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
76390    }else{
76391#ifdef SQLITE_OMIT_FLOATING_POINT
76392      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
76393#else
76394      codeReal(v, z, negFlag, iMem);
76395#endif
76396    }
76397  }
76398}
76399
76400/*
76401** Clear a cache entry.
76402*/
76403static void cacheEntryClear(Parse *pParse, struct yColCache *p){
76404  if( p->tempReg ){
76405    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
76406      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
76407    }
76408    p->tempReg = 0;
76409  }
76410}
76411
76412
76413/*
76414** Record in the column cache that a particular column from a
76415** particular table is stored in a particular register.
76416*/
76417SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
76418  int i;
76419  int minLru;
76420  int idxLru;
76421  struct yColCache *p;
76422
76423  assert( iReg>0 );  /* Register numbers are always positive */
76424  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
76425
76426  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
76427  ** for testing only - to verify that SQLite always gets the same answer
76428  ** with and without the column cache.
76429  */
76430  if( pParse->db->flags & SQLITE_ColumnCache ) return;
76431
76432  /* First replace any existing entry.
76433  **
76434  ** Actually, the way the column cache is currently used, we are guaranteed
76435  ** that the object will never already be in cache.  Verify this guarantee.
76436  */
76437#ifndef NDEBUG
76438  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76439#if 0 /* This code wold remove the entry from the cache if it existed */
76440    if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
76441      cacheEntryClear(pParse, p);
76442      p->iLevel = pParse->iCacheLevel;
76443      p->iReg = iReg;
76444      p->lru = pParse->iCacheCnt++;
76445      return;
76446    }
76447#endif
76448    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
76449  }
76450#endif
76451
76452  /* Find an empty slot and replace it */
76453  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76454    if( p->iReg==0 ){
76455      p->iLevel = pParse->iCacheLevel;
76456      p->iTable = iTab;
76457      p->iColumn = iCol;
76458      p->iReg = iReg;
76459      p->tempReg = 0;
76460      p->lru = pParse->iCacheCnt++;
76461      return;
76462    }
76463  }
76464
76465  /* Replace the last recently used */
76466  minLru = 0x7fffffff;
76467  idxLru = -1;
76468  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76469    if( p->lru<minLru ){
76470      idxLru = i;
76471      minLru = p->lru;
76472    }
76473  }
76474  if( ALWAYS(idxLru>=0) ){
76475    p = &pParse->aColCache[idxLru];
76476    p->iLevel = pParse->iCacheLevel;
76477    p->iTable = iTab;
76478    p->iColumn = iCol;
76479    p->iReg = iReg;
76480    p->tempReg = 0;
76481    p->lru = pParse->iCacheCnt++;
76482    return;
76483  }
76484}
76485
76486/*
76487** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
76488** Purge the range of registers from the column cache.
76489*/
76490SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
76491  int i;
76492  int iLast = iReg + nReg - 1;
76493  struct yColCache *p;
76494  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76495    int r = p->iReg;
76496    if( r>=iReg && r<=iLast ){
76497      cacheEntryClear(pParse, p);
76498      p->iReg = 0;
76499    }
76500  }
76501}
76502
76503/*
76504** Remember the current column cache context.  Any new entries added
76505** added to the column cache after this call are removed when the
76506** corresponding pop occurs.
76507*/
76508SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
76509  pParse->iCacheLevel++;
76510}
76511
76512/*
76513** Remove from the column cache any entries that were added since the
76514** the previous N Push operations.  In other words, restore the cache
76515** to the state it was in N Pushes ago.
76516*/
76517SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
76518  int i;
76519  struct yColCache *p;
76520  assert( N>0 );
76521  assert( pParse->iCacheLevel>=N );
76522  pParse->iCacheLevel -= N;
76523  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76524    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
76525      cacheEntryClear(pParse, p);
76526      p->iReg = 0;
76527    }
76528  }
76529}
76530
76531/*
76532** When a cached column is reused, make sure that its register is
76533** no longer available as a temp register.  ticket #3879:  that same
76534** register might be in the cache in multiple places, so be sure to
76535** get them all.
76536*/
76537static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
76538  int i;
76539  struct yColCache *p;
76540  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76541    if( p->iReg==iReg ){
76542      p->tempReg = 0;
76543    }
76544  }
76545}
76546
76547/*
76548** Generate code to extract the value of the iCol-th column of a table.
76549*/
76550SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
76551  Vdbe *v,        /* The VDBE under construction */
76552  Table *pTab,    /* The table containing the value */
76553  int iTabCur,    /* The cursor for this table */
76554  int iCol,       /* Index of the column to extract */
76555  int regOut      /* Extract the valud into this register */
76556){
76557  if( iCol<0 || iCol==pTab->iPKey ){
76558    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
76559  }else{
76560    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
76561    sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
76562  }
76563  if( iCol>=0 ){
76564    sqlite3ColumnDefault(v, pTab, iCol, regOut);
76565  }
76566}
76567
76568/*
76569** Generate code that will extract the iColumn-th column from
76570** table pTab and store the column value in a register.  An effort
76571** is made to store the column value in register iReg, but this is
76572** not guaranteed.  The location of the column value is returned.
76573**
76574** There must be an open cursor to pTab in iTable when this routine
76575** is called.  If iColumn<0 then code is generated that extracts the rowid.
76576*/
76577SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
76578  Parse *pParse,   /* Parsing and code generating context */
76579  Table *pTab,     /* Description of the table we are reading from */
76580  int iColumn,     /* Index of the table column */
76581  int iTable,      /* The cursor pointing to the table */
76582  int iReg         /* Store results here */
76583){
76584  Vdbe *v = pParse->pVdbe;
76585  int i;
76586  struct yColCache *p;
76587
76588  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76589    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
76590      p->lru = pParse->iCacheCnt++;
76591      sqlite3ExprCachePinRegister(pParse, p->iReg);
76592      return p->iReg;
76593    }
76594  }
76595  assert( v!=0 );
76596  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
76597  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
76598  return iReg;
76599}
76600
76601/*
76602** Clear all column cache entries.
76603*/
76604SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
76605  int i;
76606  struct yColCache *p;
76607
76608  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76609    if( p->iReg ){
76610      cacheEntryClear(pParse, p);
76611      p->iReg = 0;
76612    }
76613  }
76614}
76615
76616/*
76617** Record the fact that an affinity change has occurred on iCount
76618** registers starting with iStart.
76619*/
76620SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
76621  sqlite3ExprCacheRemove(pParse, iStart, iCount);
76622}
76623
76624/*
76625** Generate code to move content from registers iFrom...iFrom+nReg-1
76626** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
76627*/
76628SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
76629  int i;
76630  struct yColCache *p;
76631  if( NEVER(iFrom==iTo) ) return;
76632  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
76633  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76634    int x = p->iReg;
76635    if( x>=iFrom && x<iFrom+nReg ){
76636      p->iReg += iTo-iFrom;
76637    }
76638  }
76639}
76640
76641/*
76642** Generate code to copy content from registers iFrom...iFrom+nReg-1
76643** over to iTo..iTo+nReg-1.
76644*/
76645SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
76646  int i;
76647  if( NEVER(iFrom==iTo) ) return;
76648  for(i=0; i<nReg; i++){
76649    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
76650  }
76651}
76652
76653#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
76654/*
76655** Return true if any register in the range iFrom..iTo (inclusive)
76656** is used as part of the column cache.
76657**
76658** This routine is used within assert() and testcase() macros only
76659** and does not appear in a normal build.
76660*/
76661static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
76662  int i;
76663  struct yColCache *p;
76664  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76665    int r = p->iReg;
76666    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
76667  }
76668  return 0;
76669}
76670#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
76671
76672/*
76673** Generate code into the current Vdbe to evaluate the given
76674** expression.  Attempt to store the results in register "target".
76675** Return the register where results are stored.
76676**
76677** With this routine, there is no guarantee that results will
76678** be stored in target.  The result might be stored in some other
76679** register if it is convenient to do so.  The calling function
76680** must check the return code and move the results to the desired
76681** register.
76682*/
76683SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
76684  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
76685  int op;                   /* The opcode being coded */
76686  int inReg = target;       /* Results stored in register inReg */
76687  int regFree1 = 0;         /* If non-zero free this temporary register */
76688  int regFree2 = 0;         /* If non-zero free this temporary register */
76689  int r1, r2, r3, r4;       /* Various register numbers */
76690  sqlite3 *db = pParse->db; /* The database connection */
76691
76692  assert( target>0 && target<=pParse->nMem );
76693  if( v==0 ){
76694    assert( pParse->db->mallocFailed );
76695    return 0;
76696  }
76697
76698  if( pExpr==0 ){
76699    op = TK_NULL;
76700  }else{
76701    op = pExpr->op;
76702  }
76703  switch( op ){
76704    case TK_AGG_COLUMN: {
76705      AggInfo *pAggInfo = pExpr->pAggInfo;
76706      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
76707      if( !pAggInfo->directMode ){
76708        assert( pCol->iMem>0 );
76709        inReg = pCol->iMem;
76710        break;
76711      }else if( pAggInfo->useSortingIdx ){
76712        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
76713                              pCol->iSorterColumn, target);
76714        break;
76715      }
76716      /* Otherwise, fall thru into the TK_COLUMN case */
76717    }
76718    case TK_COLUMN: {
76719      if( pExpr->iTable<0 ){
76720        /* This only happens when coding check constraints */
76721        assert( pParse->ckBase>0 );
76722        inReg = pExpr->iColumn + pParse->ckBase;
76723      }else{
76724        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
76725                                 pExpr->iColumn, pExpr->iTable, target);
76726      }
76727      break;
76728    }
76729    case TK_INTEGER: {
76730      codeInteger(pParse, pExpr, 0, target);
76731      break;
76732    }
76733#ifndef SQLITE_OMIT_FLOATING_POINT
76734    case TK_FLOAT: {
76735      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76736      codeReal(v, pExpr->u.zToken, 0, target);
76737      break;
76738    }
76739#endif
76740    case TK_STRING: {
76741      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76742      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
76743      break;
76744    }
76745    case TK_NULL: {
76746      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76747      break;
76748    }
76749#ifndef SQLITE_OMIT_BLOB_LITERAL
76750    case TK_BLOB: {
76751      int n;
76752      const char *z;
76753      char *zBlob;
76754      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76755      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
76756      assert( pExpr->u.zToken[1]=='\'' );
76757      z = &pExpr->u.zToken[2];
76758      n = sqlite3Strlen30(z) - 1;
76759      assert( z[n]=='\'' );
76760      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
76761      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
76762      break;
76763    }
76764#endif
76765    case TK_VARIABLE: {
76766      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76767      assert( pExpr->u.zToken!=0 );
76768      assert( pExpr->u.zToken[0]!=0 );
76769      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
76770      if( pExpr->u.zToken[1]!=0 ){
76771        assert( pExpr->u.zToken[0]=='?'
76772             || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
76773        sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
76774      }
76775      break;
76776    }
76777    case TK_REGISTER: {
76778      inReg = pExpr->iTable;
76779      break;
76780    }
76781    case TK_AS: {
76782      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76783      break;
76784    }
76785#ifndef SQLITE_OMIT_CAST
76786    case TK_CAST: {
76787      /* Expressions of the form:   CAST(pLeft AS token) */
76788      int aff, to_op;
76789      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76790      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76791      aff = sqlite3AffinityType(pExpr->u.zToken);
76792      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
76793      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
76794      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
76795      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
76796      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
76797      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
76798      testcase( to_op==OP_ToText );
76799      testcase( to_op==OP_ToBlob );
76800      testcase( to_op==OP_ToNumeric );
76801      testcase( to_op==OP_ToInt );
76802      testcase( to_op==OP_ToReal );
76803      if( inReg!=target ){
76804        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
76805        inReg = target;
76806      }
76807      sqlite3VdbeAddOp1(v, to_op, inReg);
76808      testcase( usedAsColumnCache(pParse, inReg, inReg) );
76809      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
76810      break;
76811    }
76812#endif /* SQLITE_OMIT_CAST */
76813    case TK_LT:
76814    case TK_LE:
76815    case TK_GT:
76816    case TK_GE:
76817    case TK_NE:
76818    case TK_EQ: {
76819      assert( TK_LT==OP_Lt );
76820      assert( TK_LE==OP_Le );
76821      assert( TK_GT==OP_Gt );
76822      assert( TK_GE==OP_Ge );
76823      assert( TK_EQ==OP_Eq );
76824      assert( TK_NE==OP_Ne );
76825      testcase( op==TK_LT );
76826      testcase( op==TK_LE );
76827      testcase( op==TK_GT );
76828      testcase( op==TK_GE );
76829      testcase( op==TK_EQ );
76830      testcase( op==TK_NE );
76831      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76832      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76833      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76834                  r1, r2, inReg, SQLITE_STOREP2);
76835      testcase( regFree1==0 );
76836      testcase( regFree2==0 );
76837      break;
76838    }
76839    case TK_IS:
76840    case TK_ISNOT: {
76841      testcase( op==TK_IS );
76842      testcase( op==TK_ISNOT );
76843      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76844      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76845      op = (op==TK_IS) ? TK_EQ : TK_NE;
76846      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76847                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
76848      testcase( regFree1==0 );
76849      testcase( regFree2==0 );
76850      break;
76851    }
76852    case TK_AND:
76853    case TK_OR:
76854    case TK_PLUS:
76855    case TK_STAR:
76856    case TK_MINUS:
76857    case TK_REM:
76858    case TK_BITAND:
76859    case TK_BITOR:
76860    case TK_SLASH:
76861    case TK_LSHIFT:
76862    case TK_RSHIFT:
76863    case TK_CONCAT: {
76864      assert( TK_AND==OP_And );
76865      assert( TK_OR==OP_Or );
76866      assert( TK_PLUS==OP_Add );
76867      assert( TK_MINUS==OP_Subtract );
76868      assert( TK_REM==OP_Remainder );
76869      assert( TK_BITAND==OP_BitAnd );
76870      assert( TK_BITOR==OP_BitOr );
76871      assert( TK_SLASH==OP_Divide );
76872      assert( TK_LSHIFT==OP_ShiftLeft );
76873      assert( TK_RSHIFT==OP_ShiftRight );
76874      assert( TK_CONCAT==OP_Concat );
76875      testcase( op==TK_AND );
76876      testcase( op==TK_OR );
76877      testcase( op==TK_PLUS );
76878      testcase( op==TK_MINUS );
76879      testcase( op==TK_REM );
76880      testcase( op==TK_BITAND );
76881      testcase( op==TK_BITOR );
76882      testcase( op==TK_SLASH );
76883      testcase( op==TK_LSHIFT );
76884      testcase( op==TK_RSHIFT );
76885      testcase( op==TK_CONCAT );
76886      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76887      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76888      sqlite3VdbeAddOp3(v, op, r2, r1, target);
76889      testcase( regFree1==0 );
76890      testcase( regFree2==0 );
76891      break;
76892    }
76893    case TK_UMINUS: {
76894      Expr *pLeft = pExpr->pLeft;
76895      assert( pLeft );
76896      if( pLeft->op==TK_INTEGER ){
76897        codeInteger(pParse, pLeft, 1, target);
76898#ifndef SQLITE_OMIT_FLOATING_POINT
76899      }else if( pLeft->op==TK_FLOAT ){
76900        assert( !ExprHasProperty(pExpr, EP_IntValue) );
76901        codeReal(v, pLeft->u.zToken, 1, target);
76902#endif
76903      }else{
76904        regFree1 = r1 = sqlite3GetTempReg(pParse);
76905        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
76906        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
76907        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
76908        testcase( regFree2==0 );
76909      }
76910      inReg = target;
76911      break;
76912    }
76913    case TK_BITNOT:
76914    case TK_NOT: {
76915      assert( TK_BITNOT==OP_BitNot );
76916      assert( TK_NOT==OP_Not );
76917      testcase( op==TK_BITNOT );
76918      testcase( op==TK_NOT );
76919      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76920      testcase( regFree1==0 );
76921      inReg = target;
76922      sqlite3VdbeAddOp2(v, op, r1, inReg);
76923      break;
76924    }
76925    case TK_ISNULL:
76926    case TK_NOTNULL: {
76927      int addr;
76928      assert( TK_ISNULL==OP_IsNull );
76929      assert( TK_NOTNULL==OP_NotNull );
76930      testcase( op==TK_ISNULL );
76931      testcase( op==TK_NOTNULL );
76932      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
76933      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76934      testcase( regFree1==0 );
76935      addr = sqlite3VdbeAddOp1(v, op, r1);
76936      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
76937      sqlite3VdbeJumpHere(v, addr);
76938      break;
76939    }
76940    case TK_AGG_FUNCTION: {
76941      AggInfo *pInfo = pExpr->pAggInfo;
76942      if( pInfo==0 ){
76943        assert( !ExprHasProperty(pExpr, EP_IntValue) );
76944        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
76945      }else{
76946        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
76947      }
76948      break;
76949    }
76950    case TK_CONST_FUNC:
76951    case TK_FUNCTION: {
76952      ExprList *pFarg;       /* List of function arguments */
76953      int nFarg;             /* Number of function arguments */
76954      FuncDef *pDef;         /* The function definition object */
76955      int nId;               /* Length of the function name in bytes */
76956      const char *zId;       /* The function name */
76957      int constMask = 0;     /* Mask of function arguments that are constant */
76958      int i;                 /* Loop counter */
76959      u8 enc = ENC(db);      /* The text encoding used by this database */
76960      CollSeq *pColl = 0;    /* A collating sequence */
76961
76962      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76963      testcase( op==TK_CONST_FUNC );
76964      testcase( op==TK_FUNCTION );
76965      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
76966        pFarg = 0;
76967      }else{
76968        pFarg = pExpr->x.pList;
76969      }
76970      nFarg = pFarg ? pFarg->nExpr : 0;
76971      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76972      zId = pExpr->u.zToken;
76973      nId = sqlite3Strlen30(zId);
76974      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
76975      if( pDef==0 ){
76976        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
76977        break;
76978      }
76979
76980      /* Attempt a direct implementation of the built-in COALESCE() and
76981      ** IFNULL() functions.  This avoids unnecessary evalation of
76982      ** arguments past the first non-NULL argument.
76983      */
76984      if( pDef->flags & SQLITE_FUNC_COALESCE ){
76985        int endCoalesce = sqlite3VdbeMakeLabel(v);
76986        assert( nFarg>=2 );
76987        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
76988        for(i=1; i<nFarg; i++){
76989          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
76990          sqlite3ExprCacheRemove(pParse, target, 1);
76991          sqlite3ExprCachePush(pParse);
76992          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
76993          sqlite3ExprCachePop(pParse, 1);
76994        }
76995        sqlite3VdbeResolveLabel(v, endCoalesce);
76996        break;
76997      }
76998
76999
77000      if( pFarg ){
77001        r1 = sqlite3GetTempRange(pParse, nFarg);
77002        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
77003        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
77004        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
77005      }else{
77006        r1 = 0;
77007      }
77008#ifndef SQLITE_OMIT_VIRTUALTABLE
77009      /* Possibly overload the function if the first argument is
77010      ** a virtual table column.
77011      **
77012      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
77013      ** second argument, not the first, as the argument to test to
77014      ** see if it is a column in a virtual table.  This is done because
77015      ** the left operand of infix functions (the operand we want to
77016      ** control overloading) ends up as the second argument to the
77017      ** function.  The expression "A glob B" is equivalent to
77018      ** "glob(B,A).  We want to use the A in "A glob B" to test
77019      ** for function overloading.  But we use the B term in "glob(B,A)".
77020      */
77021      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
77022        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
77023      }else if( nFarg>0 ){
77024        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
77025      }
77026#endif
77027      for(i=0; i<nFarg; i++){
77028        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
77029          constMask |= (1<<i);
77030        }
77031        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
77032          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
77033        }
77034      }
77035      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
77036        if( !pColl ) pColl = db->pDfltColl;
77037        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
77038      }
77039      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
77040                        (char*)pDef, P4_FUNCDEF);
77041      sqlite3VdbeChangeP5(v, (u8)nFarg);
77042      if( nFarg ){
77043        sqlite3ReleaseTempRange(pParse, r1, nFarg);
77044      }
77045      break;
77046    }
77047#ifndef SQLITE_OMIT_SUBQUERY
77048    case TK_EXISTS:
77049    case TK_SELECT: {
77050      testcase( op==TK_EXISTS );
77051      testcase( op==TK_SELECT );
77052      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
77053      break;
77054    }
77055    case TK_IN: {
77056      int destIfFalse = sqlite3VdbeMakeLabel(v);
77057      int destIfNull = sqlite3VdbeMakeLabel(v);
77058      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
77059      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
77060      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
77061      sqlite3VdbeResolveLabel(v, destIfFalse);
77062      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
77063      sqlite3VdbeResolveLabel(v, destIfNull);
77064      break;
77065    }
77066#endif /* SQLITE_OMIT_SUBQUERY */
77067
77068
77069    /*
77070    **    x BETWEEN y AND z
77071    **
77072    ** This is equivalent to
77073    **
77074    **    x>=y AND x<=z
77075    **
77076    ** X is stored in pExpr->pLeft.
77077    ** Y is stored in pExpr->pList->a[0].pExpr.
77078    ** Z is stored in pExpr->pList->a[1].pExpr.
77079    */
77080    case TK_BETWEEN: {
77081      Expr *pLeft = pExpr->pLeft;
77082      struct ExprList_item *pLItem = pExpr->x.pList->a;
77083      Expr *pRight = pLItem->pExpr;
77084
77085      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
77086      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
77087      testcase( regFree1==0 );
77088      testcase( regFree2==0 );
77089      r3 = sqlite3GetTempReg(pParse);
77090      r4 = sqlite3GetTempReg(pParse);
77091      codeCompare(pParse, pLeft, pRight, OP_Ge,
77092                  r1, r2, r3, SQLITE_STOREP2);
77093      pLItem++;
77094      pRight = pLItem->pExpr;
77095      sqlite3ReleaseTempReg(pParse, regFree2);
77096      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
77097      testcase( regFree2==0 );
77098      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
77099      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
77100      sqlite3ReleaseTempReg(pParse, r3);
77101      sqlite3ReleaseTempReg(pParse, r4);
77102      break;
77103    }
77104    case TK_UPLUS: {
77105      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77106      break;
77107    }
77108
77109    case TK_TRIGGER: {
77110      /* If the opcode is TK_TRIGGER, then the expression is a reference
77111      ** to a column in the new.* or old.* pseudo-tables available to
77112      ** trigger programs. In this case Expr.iTable is set to 1 for the
77113      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
77114      ** is set to the column of the pseudo-table to read, or to -1 to
77115      ** read the rowid field.
77116      **
77117      ** The expression is implemented using an OP_Param opcode. The p1
77118      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
77119      ** to reference another column of the old.* pseudo-table, where
77120      ** i is the index of the column. For a new.rowid reference, p1 is
77121      ** set to (n+1), where n is the number of columns in each pseudo-table.
77122      ** For a reference to any other column in the new.* pseudo-table, p1
77123      ** is set to (n+2+i), where n and i are as defined previously. For
77124      ** example, if the table on which triggers are being fired is
77125      ** declared as:
77126      **
77127      **   CREATE TABLE t1(a, b);
77128      **
77129      ** Then p1 is interpreted as follows:
77130      **
77131      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
77132      **   p1==1   ->    old.a         p1==4   ->    new.a
77133      **   p1==2   ->    old.b         p1==5   ->    new.b
77134      */
77135      Table *pTab = pExpr->pTab;
77136      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
77137
77138      assert( pExpr->iTable==0 || pExpr->iTable==1 );
77139      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
77140      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
77141      assert( p1>=0 && p1<(pTab->nCol*2+2) );
77142
77143      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
77144      VdbeComment((v, "%s.%s -> $%d",
77145        (pExpr->iTable ? "new" : "old"),
77146        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
77147        target
77148      ));
77149
77150#ifndef SQLITE_OMIT_FLOATING_POINT
77151      /* If the column has REAL affinity, it may currently be stored as an
77152      ** integer. Use OP_RealAffinity to make sure it is really real.  */
77153      if( pExpr->iColumn>=0
77154       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
77155      ){
77156        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
77157      }
77158#endif
77159      break;
77160    }
77161
77162
77163    /*
77164    ** Form A:
77165    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
77166    **
77167    ** Form B:
77168    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
77169    **
77170    ** Form A is can be transformed into the equivalent form B as follows:
77171    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
77172    **        WHEN x=eN THEN rN ELSE y END
77173    **
77174    ** X (if it exists) is in pExpr->pLeft.
77175    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
77176    ** ELSE clause and no other term matches, then the result of the
77177    ** exprssion is NULL.
77178    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
77179    **
77180    ** The result of the expression is the Ri for the first matching Ei,
77181    ** or if there is no matching Ei, the ELSE term Y, or if there is
77182    ** no ELSE term, NULL.
77183    */
77184    default: assert( op==TK_CASE ); {
77185      int endLabel;                     /* GOTO label for end of CASE stmt */
77186      int nextCase;                     /* GOTO label for next WHEN clause */
77187      int nExpr;                        /* 2x number of WHEN terms */
77188      int i;                            /* Loop counter */
77189      ExprList *pEList;                 /* List of WHEN terms */
77190      struct ExprList_item *aListelem;  /* Array of WHEN terms */
77191      Expr opCompare;                   /* The X==Ei expression */
77192      Expr cacheX;                      /* Cached expression X */
77193      Expr *pX;                         /* The X expression */
77194      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
77195      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
77196
77197      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
77198      assert((pExpr->x.pList->nExpr % 2) == 0);
77199      assert(pExpr->x.pList->nExpr > 0);
77200      pEList = pExpr->x.pList;
77201      aListelem = pEList->a;
77202      nExpr = pEList->nExpr;
77203      endLabel = sqlite3VdbeMakeLabel(v);
77204      if( (pX = pExpr->pLeft)!=0 ){
77205        cacheX = *pX;
77206        testcase( pX->op==TK_COLUMN );
77207        testcase( pX->op==TK_REGISTER );
77208        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
77209        testcase( regFree1==0 );
77210        cacheX.op = TK_REGISTER;
77211        opCompare.op = TK_EQ;
77212        opCompare.pLeft = &cacheX;
77213        pTest = &opCompare;
77214        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
77215        ** The value in regFree1 might get SCopy-ed into the file result.
77216        ** So make sure that the regFree1 register is not reused for other
77217        ** purposes and possibly overwritten.  */
77218        regFree1 = 0;
77219      }
77220      for(i=0; i<nExpr; i=i+2){
77221        sqlite3ExprCachePush(pParse);
77222        if( pX ){
77223          assert( pTest!=0 );
77224          opCompare.pRight = aListelem[i].pExpr;
77225        }else{
77226          pTest = aListelem[i].pExpr;
77227        }
77228        nextCase = sqlite3VdbeMakeLabel(v);
77229        testcase( pTest->op==TK_COLUMN );
77230        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
77231        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
77232        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
77233        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
77234        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
77235        sqlite3ExprCachePop(pParse, 1);
77236        sqlite3VdbeResolveLabel(v, nextCase);
77237      }
77238      if( pExpr->pRight ){
77239        sqlite3ExprCachePush(pParse);
77240        sqlite3ExprCode(pParse, pExpr->pRight, target);
77241        sqlite3ExprCachePop(pParse, 1);
77242      }else{
77243        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
77244      }
77245      assert( db->mallocFailed || pParse->nErr>0
77246           || pParse->iCacheLevel==iCacheLevel );
77247      sqlite3VdbeResolveLabel(v, endLabel);
77248      break;
77249    }
77250#ifndef SQLITE_OMIT_TRIGGER
77251    case TK_RAISE: {
77252      assert( pExpr->affinity==OE_Rollback
77253           || pExpr->affinity==OE_Abort
77254           || pExpr->affinity==OE_Fail
77255           || pExpr->affinity==OE_Ignore
77256      );
77257      if( !pParse->pTriggerTab ){
77258        sqlite3ErrorMsg(pParse,
77259                       "RAISE() may only be used within a trigger-program");
77260        return 0;
77261      }
77262      if( pExpr->affinity==OE_Abort ){
77263        sqlite3MayAbort(pParse);
77264      }
77265      assert( !ExprHasProperty(pExpr, EP_IntValue) );
77266      if( pExpr->affinity==OE_Ignore ){
77267        sqlite3VdbeAddOp4(
77268            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
77269      }else{
77270        sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
77271      }
77272
77273      break;
77274    }
77275#endif
77276  }
77277  sqlite3ReleaseTempReg(pParse, regFree1);
77278  sqlite3ReleaseTempReg(pParse, regFree2);
77279  return inReg;
77280}
77281
77282/*
77283** Generate code to evaluate an expression and store the results
77284** into a register.  Return the register number where the results
77285** are stored.
77286**
77287** If the register is a temporary register that can be deallocated,
77288** then write its number into *pReg.  If the result register is not
77289** a temporary, then set *pReg to zero.
77290*/
77291SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
77292  int r1 = sqlite3GetTempReg(pParse);
77293  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
77294  if( r2==r1 ){
77295    *pReg = r1;
77296  }else{
77297    sqlite3ReleaseTempReg(pParse, r1);
77298    *pReg = 0;
77299  }
77300  return r2;
77301}
77302
77303/*
77304** Generate code that will evaluate expression pExpr and store the
77305** results in register target.  The results are guaranteed to appear
77306** in register target.
77307*/
77308SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
77309  int inReg;
77310
77311  assert( target>0 && target<=pParse->nMem );
77312  if( pExpr && pExpr->op==TK_REGISTER ){
77313    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
77314  }else{
77315    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
77316    assert( pParse->pVdbe || pParse->db->mallocFailed );
77317    if( inReg!=target && pParse->pVdbe ){
77318      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
77319    }
77320  }
77321  return target;
77322}
77323
77324/*
77325** Generate code that evalutes the given expression and puts the result
77326** in register target.
77327**
77328** Also make a copy of the expression results into another "cache" register
77329** and modify the expression so that the next time it is evaluated,
77330** the result is a copy of the cache register.
77331**
77332** This routine is used for expressions that are used multiple
77333** times.  They are evaluated once and the results of the expression
77334** are reused.
77335*/
77336SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
77337  Vdbe *v = pParse->pVdbe;
77338  int inReg;
77339  inReg = sqlite3ExprCode(pParse, pExpr, target);
77340  assert( target>0 );
77341  /* This routine is called for terms to INSERT or UPDATE.  And the only
77342  ** other place where expressions can be converted into TK_REGISTER is
77343  ** in WHERE clause processing.  So as currently implemented, there is
77344  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
77345  ** keep the ALWAYS() in case the conditions above change with future
77346  ** modifications or enhancements. */
77347  if( ALWAYS(pExpr->op!=TK_REGISTER) ){
77348    int iMem;
77349    iMem = ++pParse->nMem;
77350    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
77351    pExpr->iTable = iMem;
77352    pExpr->op2 = pExpr->op;
77353    pExpr->op = TK_REGISTER;
77354  }
77355  return inReg;
77356}
77357
77358#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
77359/*
77360** Generate a human-readable explanation of an expression tree.
77361*/
77362SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
77363  int op;                   /* The opcode being coded */
77364  const char *zBinOp = 0;   /* Binary operator */
77365  const char *zUniOp = 0;   /* Unary operator */
77366  if( pExpr==0 ){
77367    op = TK_NULL;
77368  }else{
77369    op = pExpr->op;
77370  }
77371  switch( op ){
77372    case TK_AGG_COLUMN: {
77373      sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
77374            pExpr->iTable, pExpr->iColumn);
77375      break;
77376    }
77377    case TK_COLUMN: {
77378      if( pExpr->iTable<0 ){
77379        /* This only happens when coding check constraints */
77380        sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
77381      }else{
77382        sqlite3ExplainPrintf(pOut, "{%d:%d}",
77383                             pExpr->iTable, pExpr->iColumn);
77384      }
77385      break;
77386    }
77387    case TK_INTEGER: {
77388      if( pExpr->flags & EP_IntValue ){
77389        sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
77390      }else{
77391        sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
77392      }
77393      break;
77394    }
77395#ifndef SQLITE_OMIT_FLOATING_POINT
77396    case TK_FLOAT: {
77397      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
77398      break;
77399    }
77400#endif
77401    case TK_STRING: {
77402      sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
77403      break;
77404    }
77405    case TK_NULL: {
77406      sqlite3ExplainPrintf(pOut,"NULL");
77407      break;
77408    }
77409#ifndef SQLITE_OMIT_BLOB_LITERAL
77410    case TK_BLOB: {
77411      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
77412      break;
77413    }
77414#endif
77415    case TK_VARIABLE: {
77416      sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
77417                           pExpr->u.zToken, pExpr->iColumn);
77418      break;
77419    }
77420    case TK_REGISTER: {
77421      sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
77422      break;
77423    }
77424    case TK_AS: {
77425      sqlite3ExplainExpr(pOut, pExpr->pLeft);
77426      break;
77427    }
77428#ifndef SQLITE_OMIT_CAST
77429    case TK_CAST: {
77430      /* Expressions of the form:   CAST(pLeft AS token) */
77431      const char *zAff = "unk";
77432      switch( sqlite3AffinityType(pExpr->u.zToken) ){
77433        case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
77434        case SQLITE_AFF_NONE:    zAff = "NONE";     break;
77435        case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
77436        case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
77437        case SQLITE_AFF_REAL:    zAff = "REAL";     break;
77438      }
77439      sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
77440      sqlite3ExplainExpr(pOut, pExpr->pLeft);
77441      sqlite3ExplainPrintf(pOut, ")");
77442      break;
77443    }
77444#endif /* SQLITE_OMIT_CAST */
77445    case TK_LT:      zBinOp = "LT";     break;
77446    case TK_LE:      zBinOp = "LE";     break;
77447    case TK_GT:      zBinOp = "GT";     break;
77448    case TK_GE:      zBinOp = "GE";     break;
77449    case TK_NE:      zBinOp = "NE";     break;
77450    case TK_EQ:      zBinOp = "EQ";     break;
77451    case TK_IS:      zBinOp = "IS";     break;
77452    case TK_ISNOT:   zBinOp = "ISNOT";  break;
77453    case TK_AND:     zBinOp = "AND";    break;
77454    case TK_OR:      zBinOp = "OR";     break;
77455    case TK_PLUS:    zBinOp = "ADD";    break;
77456    case TK_STAR:    zBinOp = "MUL";    break;
77457    case TK_MINUS:   zBinOp = "SUB";    break;
77458    case TK_REM:     zBinOp = "REM";    break;
77459    case TK_BITAND:  zBinOp = "BITAND"; break;
77460    case TK_BITOR:   zBinOp = "BITOR";  break;
77461    case TK_SLASH:   zBinOp = "DIV";    break;
77462    case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
77463    case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
77464    case TK_CONCAT:  zBinOp = "CONCAT"; break;
77465
77466    case TK_UMINUS:  zUniOp = "UMINUS"; break;
77467    case TK_UPLUS:   zUniOp = "UPLUS";  break;
77468    case TK_BITNOT:  zUniOp = "BITNOT"; break;
77469    case TK_NOT:     zUniOp = "NOT";    break;
77470    case TK_ISNULL:  zUniOp = "ISNULL"; break;
77471    case TK_NOTNULL: zUniOp = "NOTNULL"; break;
77472
77473    case TK_AGG_FUNCTION:
77474    case TK_CONST_FUNC:
77475    case TK_FUNCTION: {
77476      ExprList *pFarg;       /* List of function arguments */
77477      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
77478        pFarg = 0;
77479      }else{
77480        pFarg = pExpr->x.pList;
77481      }
77482      sqlite3ExplainPrintf(pOut, "%sFUNCTION:%s(",
77483                           op==TK_AGG_FUNCTION ? "AGG_" : "",
77484                           pExpr->u.zToken);
77485      if( pFarg ){
77486        sqlite3ExplainExprList(pOut, pFarg);
77487      }
77488      sqlite3ExplainPrintf(pOut, ")");
77489      break;
77490    }
77491#ifndef SQLITE_OMIT_SUBQUERY
77492    case TK_EXISTS: {
77493      sqlite3ExplainPrintf(pOut, "EXISTS(");
77494      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77495      sqlite3ExplainPrintf(pOut,")");
77496      break;
77497    }
77498    case TK_SELECT: {
77499      sqlite3ExplainPrintf(pOut, "(");
77500      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77501      sqlite3ExplainPrintf(pOut, ")");
77502      break;
77503    }
77504    case TK_IN: {
77505      sqlite3ExplainPrintf(pOut, "IN(");
77506      sqlite3ExplainExpr(pOut, pExpr->pLeft);
77507      sqlite3ExplainPrintf(pOut, ",");
77508      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
77509        sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77510      }else{
77511        sqlite3ExplainExprList(pOut, pExpr->x.pList);
77512      }
77513      sqlite3ExplainPrintf(pOut, ")");
77514      break;
77515    }
77516#endif /* SQLITE_OMIT_SUBQUERY */
77517
77518    /*
77519    **    x BETWEEN y AND z
77520    **
77521    ** This is equivalent to
77522    **
77523    **    x>=y AND x<=z
77524    **
77525    ** X is stored in pExpr->pLeft.
77526    ** Y is stored in pExpr->pList->a[0].pExpr.
77527    ** Z is stored in pExpr->pList->a[1].pExpr.
77528    */
77529    case TK_BETWEEN: {
77530      Expr *pX = pExpr->pLeft;
77531      Expr *pY = pExpr->x.pList->a[0].pExpr;
77532      Expr *pZ = pExpr->x.pList->a[1].pExpr;
77533      sqlite3ExplainPrintf(pOut, "BETWEEN(");
77534      sqlite3ExplainExpr(pOut, pX);
77535      sqlite3ExplainPrintf(pOut, ",");
77536      sqlite3ExplainExpr(pOut, pY);
77537      sqlite3ExplainPrintf(pOut, ",");
77538      sqlite3ExplainExpr(pOut, pZ);
77539      sqlite3ExplainPrintf(pOut, ")");
77540      break;
77541    }
77542    case TK_TRIGGER: {
77543      /* If the opcode is TK_TRIGGER, then the expression is a reference
77544      ** to a column in the new.* or old.* pseudo-tables available to
77545      ** trigger programs. In this case Expr.iTable is set to 1 for the
77546      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
77547      ** is set to the column of the pseudo-table to read, or to -1 to
77548      ** read the rowid field.
77549      */
77550      sqlite3ExplainPrintf(pOut, "%s(%d)",
77551          pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
77552      break;
77553    }
77554    case TK_CASE: {
77555      sqlite3ExplainPrintf(pOut, "CASE(");
77556      sqlite3ExplainExpr(pOut, pExpr->pLeft);
77557      sqlite3ExplainPrintf(pOut, ",");
77558      sqlite3ExplainExprList(pOut, pExpr->x.pList);
77559      break;
77560    }
77561#ifndef SQLITE_OMIT_TRIGGER
77562    case TK_RAISE: {
77563      const char *zType = "unk";
77564      switch( pExpr->affinity ){
77565        case OE_Rollback:   zType = "rollback";  break;
77566        case OE_Abort:      zType = "abort";     break;
77567        case OE_Fail:       zType = "fail";      break;
77568        case OE_Ignore:     zType = "ignore";    break;
77569      }
77570      sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
77571      break;
77572    }
77573#endif
77574  }
77575  if( zBinOp ){
77576    sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
77577    sqlite3ExplainExpr(pOut, pExpr->pLeft);
77578    sqlite3ExplainPrintf(pOut,",");
77579    sqlite3ExplainExpr(pOut, pExpr->pRight);
77580    sqlite3ExplainPrintf(pOut,")");
77581  }else if( zUniOp ){
77582    sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
77583    sqlite3ExplainExpr(pOut, pExpr->pLeft);
77584    sqlite3ExplainPrintf(pOut,")");
77585  }
77586}
77587#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
77588
77589#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
77590/*
77591** Generate a human-readable explanation of an expression list.
77592*/
77593SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
77594  int i;
77595  if( pList==0 || pList->nExpr==0 ){
77596    sqlite3ExplainPrintf(pOut, "(empty-list)");
77597    return;
77598  }else if( pList->nExpr==1 ){
77599    sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
77600  }else{
77601    sqlite3ExplainPush(pOut);
77602    for(i=0; i<pList->nExpr; i++){
77603      sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
77604      sqlite3ExplainPush(pOut);
77605      sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
77606      sqlite3ExplainPop(pOut);
77607      if( i<pList->nExpr-1 ){
77608        sqlite3ExplainNL(pOut);
77609      }
77610    }
77611    sqlite3ExplainPop(pOut);
77612  }
77613}
77614#endif /* SQLITE_DEBUG */
77615
77616/*
77617** Return TRUE if pExpr is an constant expression that is appropriate
77618** for factoring out of a loop.  Appropriate expressions are:
77619**
77620**    *  Any expression that evaluates to two or more opcodes.
77621**
77622**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
77623**       or OP_Variable that does not need to be placed in a
77624**       specific register.
77625**
77626** There is no point in factoring out single-instruction constant
77627** expressions that need to be placed in a particular register.
77628** We could factor them out, but then we would end up adding an
77629** OP_SCopy instruction to move the value into the correct register
77630** later.  We might as well just use the original instruction and
77631** avoid the OP_SCopy.
77632*/
77633static int isAppropriateForFactoring(Expr *p){
77634  if( !sqlite3ExprIsConstantNotJoin(p) ){
77635    return 0;  /* Only constant expressions are appropriate for factoring */
77636  }
77637  if( (p->flags & EP_FixedDest)==0 ){
77638    return 1;  /* Any constant without a fixed destination is appropriate */
77639  }
77640  while( p->op==TK_UPLUS ) p = p->pLeft;
77641  switch( p->op ){
77642#ifndef SQLITE_OMIT_BLOB_LITERAL
77643    case TK_BLOB:
77644#endif
77645    case TK_VARIABLE:
77646    case TK_INTEGER:
77647    case TK_FLOAT:
77648    case TK_NULL:
77649    case TK_STRING: {
77650      testcase( p->op==TK_BLOB );
77651      testcase( p->op==TK_VARIABLE );
77652      testcase( p->op==TK_INTEGER );
77653      testcase( p->op==TK_FLOAT );
77654      testcase( p->op==TK_NULL );
77655      testcase( p->op==TK_STRING );
77656      /* Single-instruction constants with a fixed destination are
77657      ** better done in-line.  If we factor them, they will just end
77658      ** up generating an OP_SCopy to move the value to the destination
77659      ** register. */
77660      return 0;
77661    }
77662    case TK_UMINUS: {
77663      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
77664        return 0;
77665      }
77666      break;
77667    }
77668    default: {
77669      break;
77670    }
77671  }
77672  return 1;
77673}
77674
77675/*
77676** If pExpr is a constant expression that is appropriate for
77677** factoring out of a loop, then evaluate the expression
77678** into a register and convert the expression into a TK_REGISTER
77679** expression.
77680*/
77681static int evalConstExpr(Walker *pWalker, Expr *pExpr){
77682  Parse *pParse = pWalker->pParse;
77683  switch( pExpr->op ){
77684    case TK_IN:
77685    case TK_REGISTER: {
77686      return WRC_Prune;
77687    }
77688    case TK_FUNCTION:
77689    case TK_AGG_FUNCTION:
77690    case TK_CONST_FUNC: {
77691      /* The arguments to a function have a fixed destination.
77692      ** Mark them this way to avoid generated unneeded OP_SCopy
77693      ** instructions.
77694      */
77695      ExprList *pList = pExpr->x.pList;
77696      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77697      if( pList ){
77698        int i = pList->nExpr;
77699        struct ExprList_item *pItem = pList->a;
77700        for(; i>0; i--, pItem++){
77701          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
77702        }
77703      }
77704      break;
77705    }
77706  }
77707  if( isAppropriateForFactoring(pExpr) ){
77708    int r1 = ++pParse->nMem;
77709    int r2;
77710    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
77711    if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
77712    pExpr->op2 = pExpr->op;
77713    pExpr->op = TK_REGISTER;
77714    pExpr->iTable = r2;
77715    return WRC_Prune;
77716  }
77717  return WRC_Continue;
77718}
77719
77720/*
77721** Preevaluate constant subexpressions within pExpr and store the
77722** results in registers.  Modify pExpr so that the constant subexpresions
77723** are TK_REGISTER opcodes that refer to the precomputed values.
77724**
77725** This routine is a no-op if the jump to the cookie-check code has
77726** already occur.  Since the cookie-check jump is generated prior to
77727** any other serious processing, this check ensures that there is no
77728** way to accidently bypass the constant initializations.
77729**
77730** This routine is also a no-op if the SQLITE_FactorOutConst optimization
77731** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
77732** interface.  This allows test logic to verify that the same answer is
77733** obtained for queries regardless of whether or not constants are
77734** precomputed into registers or if they are inserted in-line.
77735*/
77736SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
77737  Walker w;
77738  if( pParse->cookieGoto ) return;
77739  if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
77740  w.xExprCallback = evalConstExpr;
77741  w.xSelectCallback = 0;
77742  w.pParse = pParse;
77743  sqlite3WalkExpr(&w, pExpr);
77744}
77745
77746
77747/*
77748** Generate code that pushes the value of every element of the given
77749** expression list into a sequence of registers beginning at target.
77750**
77751** Return the number of elements evaluated.
77752*/
77753SQLITE_PRIVATE int sqlite3ExprCodeExprList(
77754  Parse *pParse,     /* Parsing context */
77755  ExprList *pList,   /* The expression list to be coded */
77756  int target,        /* Where to write results */
77757  int doHardCopy     /* Make a hard copy of every element */
77758){
77759  struct ExprList_item *pItem;
77760  int i, n;
77761  assert( pList!=0 );
77762  assert( target>0 );
77763  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
77764  n = pList->nExpr;
77765  for(pItem=pList->a, i=0; i<n; i++, pItem++){
77766    Expr *pExpr = pItem->pExpr;
77767    int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
77768    if( inReg!=target+i ){
77769      sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
77770                        inReg, target+i);
77771    }
77772  }
77773  return n;
77774}
77775
77776/*
77777** Generate code for a BETWEEN operator.
77778**
77779**    x BETWEEN y AND z
77780**
77781** The above is equivalent to
77782**
77783**    x>=y AND x<=z
77784**
77785** Code it as such, taking care to do the common subexpression
77786** elementation of x.
77787*/
77788static void exprCodeBetween(
77789  Parse *pParse,    /* Parsing and code generating context */
77790  Expr *pExpr,      /* The BETWEEN expression */
77791  int dest,         /* Jump here if the jump is taken */
77792  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
77793  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
77794){
77795  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
77796  Expr compLeft;    /* The  x>=y  term */
77797  Expr compRight;   /* The  x<=z  term */
77798  Expr exprX;       /* The  x  subexpression */
77799  int regFree1 = 0; /* Temporary use register */
77800
77801  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77802  exprX = *pExpr->pLeft;
77803  exprAnd.op = TK_AND;
77804  exprAnd.pLeft = &compLeft;
77805  exprAnd.pRight = &compRight;
77806  compLeft.op = TK_GE;
77807  compLeft.pLeft = &exprX;
77808  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
77809  compRight.op = TK_LE;
77810  compRight.pLeft = &exprX;
77811  compRight.pRight = pExpr->x.pList->a[1].pExpr;
77812  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
77813  exprX.op = TK_REGISTER;
77814  if( jumpIfTrue ){
77815    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
77816  }else{
77817    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
77818  }
77819  sqlite3ReleaseTempReg(pParse, regFree1);
77820
77821  /* Ensure adequate test coverage */
77822  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
77823  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
77824  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
77825  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
77826  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
77827  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
77828  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
77829  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
77830}
77831
77832/*
77833** Generate code for a boolean expression such that a jump is made
77834** to the label "dest" if the expression is true but execution
77835** continues straight thru if the expression is false.
77836**
77837** If the expression evaluates to NULL (neither true nor false), then
77838** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
77839**
77840** This code depends on the fact that certain token values (ex: TK_EQ)
77841** are the same as opcode values (ex: OP_Eq) that implement the corresponding
77842** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
77843** the make process cause these values to align.  Assert()s in the code
77844** below verify that the numbers are aligned correctly.
77845*/
77846SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77847  Vdbe *v = pParse->pVdbe;
77848  int op = 0;
77849  int regFree1 = 0;
77850  int regFree2 = 0;
77851  int r1, r2;
77852
77853  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
77854  if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
77855  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
77856  op = pExpr->op;
77857  switch( op ){
77858    case TK_AND: {
77859      int d2 = sqlite3VdbeMakeLabel(v);
77860      testcase( jumpIfNull==0 );
77861      sqlite3ExprCachePush(pParse);
77862      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
77863      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77864      sqlite3VdbeResolveLabel(v, d2);
77865      sqlite3ExprCachePop(pParse, 1);
77866      break;
77867    }
77868    case TK_OR: {
77869      testcase( jumpIfNull==0 );
77870      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77871      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77872      break;
77873    }
77874    case TK_NOT: {
77875      testcase( jumpIfNull==0 );
77876      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77877      break;
77878    }
77879    case TK_LT:
77880    case TK_LE:
77881    case TK_GT:
77882    case TK_GE:
77883    case TK_NE:
77884    case TK_EQ: {
77885      assert( TK_LT==OP_Lt );
77886      assert( TK_LE==OP_Le );
77887      assert( TK_GT==OP_Gt );
77888      assert( TK_GE==OP_Ge );
77889      assert( TK_EQ==OP_Eq );
77890      assert( TK_NE==OP_Ne );
77891      testcase( op==TK_LT );
77892      testcase( op==TK_LE );
77893      testcase( op==TK_GT );
77894      testcase( op==TK_GE );
77895      testcase( op==TK_EQ );
77896      testcase( op==TK_NE );
77897      testcase( jumpIfNull==0 );
77898      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77899      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77900      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77901                  r1, r2, dest, jumpIfNull);
77902      testcase( regFree1==0 );
77903      testcase( regFree2==0 );
77904      break;
77905    }
77906    case TK_IS:
77907    case TK_ISNOT: {
77908      testcase( op==TK_IS );
77909      testcase( op==TK_ISNOT );
77910      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77911      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77912      op = (op==TK_IS) ? TK_EQ : TK_NE;
77913      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77914                  r1, r2, dest, SQLITE_NULLEQ);
77915      testcase( regFree1==0 );
77916      testcase( regFree2==0 );
77917      break;
77918    }
77919    case TK_ISNULL:
77920    case TK_NOTNULL: {
77921      assert( TK_ISNULL==OP_IsNull );
77922      assert( TK_NOTNULL==OP_NotNull );
77923      testcase( op==TK_ISNULL );
77924      testcase( op==TK_NOTNULL );
77925      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77926      sqlite3VdbeAddOp2(v, op, r1, dest);
77927      testcase( regFree1==0 );
77928      break;
77929    }
77930    case TK_BETWEEN: {
77931      testcase( jumpIfNull==0 );
77932      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
77933      break;
77934    }
77935#ifndef SQLITE_OMIT_SUBQUERY
77936    case TK_IN: {
77937      int destIfFalse = sqlite3VdbeMakeLabel(v);
77938      int destIfNull = jumpIfNull ? dest : destIfFalse;
77939      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
77940      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
77941      sqlite3VdbeResolveLabel(v, destIfFalse);
77942      break;
77943    }
77944#endif
77945    default: {
77946      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
77947      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
77948      testcase( regFree1==0 );
77949      testcase( jumpIfNull==0 );
77950      break;
77951    }
77952  }
77953  sqlite3ReleaseTempReg(pParse, regFree1);
77954  sqlite3ReleaseTempReg(pParse, regFree2);
77955}
77956
77957/*
77958** Generate code for a boolean expression such that a jump is made
77959** to the label "dest" if the expression is false but execution
77960** continues straight thru if the expression is true.
77961**
77962** If the expression evaluates to NULL (neither true nor false) then
77963** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
77964** is 0.
77965*/
77966SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77967  Vdbe *v = pParse->pVdbe;
77968  int op = 0;
77969  int regFree1 = 0;
77970  int regFree2 = 0;
77971  int r1, r2;
77972
77973  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
77974  if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
77975  if( pExpr==0 )    return;
77976
77977  /* The value of pExpr->op and op are related as follows:
77978  **
77979  **       pExpr->op            op
77980  **       ---------          ----------
77981  **       TK_ISNULL          OP_NotNull
77982  **       TK_NOTNULL         OP_IsNull
77983  **       TK_NE              OP_Eq
77984  **       TK_EQ              OP_Ne
77985  **       TK_GT              OP_Le
77986  **       TK_LE              OP_Gt
77987  **       TK_GE              OP_Lt
77988  **       TK_LT              OP_Ge
77989  **
77990  ** For other values of pExpr->op, op is undefined and unused.
77991  ** The value of TK_ and OP_ constants are arranged such that we
77992  ** can compute the mapping above using the following expression.
77993  ** Assert()s verify that the computation is correct.
77994  */
77995  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
77996
77997  /* Verify correct alignment of TK_ and OP_ constants
77998  */
77999  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
78000  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
78001  assert( pExpr->op!=TK_NE || op==OP_Eq );
78002  assert( pExpr->op!=TK_EQ || op==OP_Ne );
78003  assert( pExpr->op!=TK_LT || op==OP_Ge );
78004  assert( pExpr->op!=TK_LE || op==OP_Gt );
78005  assert( pExpr->op!=TK_GT || op==OP_Le );
78006  assert( pExpr->op!=TK_GE || op==OP_Lt );
78007
78008  switch( pExpr->op ){
78009    case TK_AND: {
78010      testcase( jumpIfNull==0 );
78011      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
78012      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
78013      break;
78014    }
78015    case TK_OR: {
78016      int d2 = sqlite3VdbeMakeLabel(v);
78017      testcase( jumpIfNull==0 );
78018      sqlite3ExprCachePush(pParse);
78019      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
78020      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
78021      sqlite3VdbeResolveLabel(v, d2);
78022      sqlite3ExprCachePop(pParse, 1);
78023      break;
78024    }
78025    case TK_NOT: {
78026      testcase( jumpIfNull==0 );
78027      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
78028      break;
78029    }
78030    case TK_LT:
78031    case TK_LE:
78032    case TK_GT:
78033    case TK_GE:
78034    case TK_NE:
78035    case TK_EQ: {
78036      testcase( op==TK_LT );
78037      testcase( op==TK_LE );
78038      testcase( op==TK_GT );
78039      testcase( op==TK_GE );
78040      testcase( op==TK_EQ );
78041      testcase( op==TK_NE );
78042      testcase( jumpIfNull==0 );
78043      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78044      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78045      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78046                  r1, r2, dest, jumpIfNull);
78047      testcase( regFree1==0 );
78048      testcase( regFree2==0 );
78049      break;
78050    }
78051    case TK_IS:
78052    case TK_ISNOT: {
78053      testcase( pExpr->op==TK_IS );
78054      testcase( pExpr->op==TK_ISNOT );
78055      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78056      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78057      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
78058      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78059                  r1, r2, dest, SQLITE_NULLEQ);
78060      testcase( regFree1==0 );
78061      testcase( regFree2==0 );
78062      break;
78063    }
78064    case TK_ISNULL:
78065    case TK_NOTNULL: {
78066      testcase( op==TK_ISNULL );
78067      testcase( op==TK_NOTNULL );
78068      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78069      sqlite3VdbeAddOp2(v, op, r1, dest);
78070      testcase( regFree1==0 );
78071      break;
78072    }
78073    case TK_BETWEEN: {
78074      testcase( jumpIfNull==0 );
78075      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
78076      break;
78077    }
78078#ifndef SQLITE_OMIT_SUBQUERY
78079    case TK_IN: {
78080      if( jumpIfNull ){
78081        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
78082      }else{
78083        int destIfNull = sqlite3VdbeMakeLabel(v);
78084        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
78085        sqlite3VdbeResolveLabel(v, destIfNull);
78086      }
78087      break;
78088    }
78089#endif
78090    default: {
78091      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
78092      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
78093      testcase( regFree1==0 );
78094      testcase( jumpIfNull==0 );
78095      break;
78096    }
78097  }
78098  sqlite3ReleaseTempReg(pParse, regFree1);
78099  sqlite3ReleaseTempReg(pParse, regFree2);
78100}
78101
78102/*
78103** Do a deep comparison of two expression trees.  Return 0 if the two
78104** expressions are completely identical.  Return 1 if they differ only
78105** by a COLLATE operator at the top level.  Return 2 if there are differences
78106** other than the top-level COLLATE operator.
78107**
78108** Sometimes this routine will return 2 even if the two expressions
78109** really are equivalent.  If we cannot prove that the expressions are
78110** identical, we return 2 just to be safe.  So if this routine
78111** returns 2, then you do not really know for certain if the two
78112** expressions are the same.  But if you get a 0 or 1 return, then you
78113** can be sure the expressions are the same.  In the places where
78114** this routine is used, it does not hurt to get an extra 2 - that
78115** just might result in some slightly slower code.  But returning
78116** an incorrect 0 or 1 could lead to a malfunction.
78117*/
78118SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
78119  if( pA==0||pB==0 ){
78120    return pB==pA ? 0 : 2;
78121  }
78122  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
78123  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
78124  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
78125    return 2;
78126  }
78127  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
78128  if( pA->op!=pB->op ) return 2;
78129  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
78130  if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
78131  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
78132  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
78133  if( ExprHasProperty(pA, EP_IntValue) ){
78134    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
78135      return 2;
78136    }
78137  }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
78138    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
78139    if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
78140      return 2;
78141    }
78142  }
78143  if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
78144  if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
78145  return 0;
78146}
78147
78148/*
78149** Compare two ExprList objects.  Return 0 if they are identical and
78150** non-zero if they differ in any way.
78151**
78152** This routine might return non-zero for equivalent ExprLists.  The
78153** only consequence will be disabled optimizations.  But this routine
78154** must never return 0 if the two ExprList objects are different, or
78155** a malfunction will result.
78156**
78157** Two NULL pointers are considered to be the same.  But a NULL pointer
78158** always differs from a non-NULL pointer.
78159*/
78160SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
78161  int i;
78162  if( pA==0 && pB==0 ) return 0;
78163  if( pA==0 || pB==0 ) return 1;
78164  if( pA->nExpr!=pB->nExpr ) return 1;
78165  for(i=0; i<pA->nExpr; i++){
78166    Expr *pExprA = pA->a[i].pExpr;
78167    Expr *pExprB = pB->a[i].pExpr;
78168    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
78169    if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
78170  }
78171  return 0;
78172}
78173
78174/*
78175** Add a new element to the pAggInfo->aCol[] array.  Return the index of
78176** the new element.  Return a negative number if malloc fails.
78177*/
78178static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
78179  int i;
78180  pInfo->aCol = sqlite3ArrayAllocate(
78181       db,
78182       pInfo->aCol,
78183       sizeof(pInfo->aCol[0]),
78184       &pInfo->nColumn,
78185       &i
78186  );
78187  return i;
78188}
78189
78190/*
78191** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
78192** the new element.  Return a negative number if malloc fails.
78193*/
78194static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
78195  int i;
78196  pInfo->aFunc = sqlite3ArrayAllocate(
78197       db,
78198       pInfo->aFunc,
78199       sizeof(pInfo->aFunc[0]),
78200       &pInfo->nFunc,
78201       &i
78202  );
78203  return i;
78204}
78205
78206/*
78207** This is the xExprCallback for a tree walker.  It is used to
78208** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
78209** for additional information.
78210*/
78211static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
78212  int i;
78213  NameContext *pNC = pWalker->u.pNC;
78214  Parse *pParse = pNC->pParse;
78215  SrcList *pSrcList = pNC->pSrcList;
78216  AggInfo *pAggInfo = pNC->pAggInfo;
78217
78218  switch( pExpr->op ){
78219    case TK_AGG_COLUMN:
78220    case TK_COLUMN: {
78221      testcase( pExpr->op==TK_AGG_COLUMN );
78222      testcase( pExpr->op==TK_COLUMN );
78223      /* Check to see if the column is in one of the tables in the FROM
78224      ** clause of the aggregate query */
78225      if( ALWAYS(pSrcList!=0) ){
78226        struct SrcList_item *pItem = pSrcList->a;
78227        for(i=0; i<pSrcList->nSrc; i++, pItem++){
78228          struct AggInfo_col *pCol;
78229          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
78230          if( pExpr->iTable==pItem->iCursor ){
78231            /* If we reach this point, it means that pExpr refers to a table
78232            ** that is in the FROM clause of the aggregate query.
78233            **
78234            ** Make an entry for the column in pAggInfo->aCol[] if there
78235            ** is not an entry there already.
78236            */
78237            int k;
78238            pCol = pAggInfo->aCol;
78239            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
78240              if( pCol->iTable==pExpr->iTable &&
78241                  pCol->iColumn==pExpr->iColumn ){
78242                break;
78243              }
78244            }
78245            if( (k>=pAggInfo->nColumn)
78246             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
78247            ){
78248              pCol = &pAggInfo->aCol[k];
78249              pCol->pTab = pExpr->pTab;
78250              pCol->iTable = pExpr->iTable;
78251              pCol->iColumn = pExpr->iColumn;
78252              pCol->iMem = ++pParse->nMem;
78253              pCol->iSorterColumn = -1;
78254              pCol->pExpr = pExpr;
78255              if( pAggInfo->pGroupBy ){
78256                int j, n;
78257                ExprList *pGB = pAggInfo->pGroupBy;
78258                struct ExprList_item *pTerm = pGB->a;
78259                n = pGB->nExpr;
78260                for(j=0; j<n; j++, pTerm++){
78261                  Expr *pE = pTerm->pExpr;
78262                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
78263                      pE->iColumn==pExpr->iColumn ){
78264                    pCol->iSorterColumn = j;
78265                    break;
78266                  }
78267                }
78268              }
78269              if( pCol->iSorterColumn<0 ){
78270                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
78271              }
78272            }
78273            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
78274            ** because it was there before or because we just created it).
78275            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
78276            ** pAggInfo->aCol[] entry.
78277            */
78278            ExprSetIrreducible(pExpr);
78279            pExpr->pAggInfo = pAggInfo;
78280            pExpr->op = TK_AGG_COLUMN;
78281            pExpr->iAgg = (i16)k;
78282            break;
78283          } /* endif pExpr->iTable==pItem->iCursor */
78284        } /* end loop over pSrcList */
78285      }
78286      return WRC_Prune;
78287    }
78288    case TK_AGG_FUNCTION: {
78289      /* The pNC->nDepth==0 test causes aggregate functions in subqueries
78290      ** to be ignored */
78291      if( pNC->nDepth==0 ){
78292        /* Check to see if pExpr is a duplicate of another aggregate
78293        ** function that is already in the pAggInfo structure
78294        */
78295        struct AggInfo_func *pItem = pAggInfo->aFunc;
78296        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
78297          if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
78298            break;
78299          }
78300        }
78301        if( i>=pAggInfo->nFunc ){
78302          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
78303          */
78304          u8 enc = ENC(pParse->db);
78305          i = addAggInfoFunc(pParse->db, pAggInfo);
78306          if( i>=0 ){
78307            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78308            pItem = &pAggInfo->aFunc[i];
78309            pItem->pExpr = pExpr;
78310            pItem->iMem = ++pParse->nMem;
78311            assert( !ExprHasProperty(pExpr, EP_IntValue) );
78312            pItem->pFunc = sqlite3FindFunction(pParse->db,
78313                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
78314                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
78315            if( pExpr->flags & EP_Distinct ){
78316              pItem->iDistinct = pParse->nTab++;
78317            }else{
78318              pItem->iDistinct = -1;
78319            }
78320          }
78321        }
78322        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
78323        */
78324        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
78325        ExprSetIrreducible(pExpr);
78326        pExpr->iAgg = (i16)i;
78327        pExpr->pAggInfo = pAggInfo;
78328        return WRC_Prune;
78329      }
78330    }
78331  }
78332  return WRC_Continue;
78333}
78334static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
78335  NameContext *pNC = pWalker->u.pNC;
78336  if( pNC->nDepth==0 ){
78337    pNC->nDepth++;
78338    sqlite3WalkSelect(pWalker, pSelect);
78339    pNC->nDepth--;
78340    return WRC_Prune;
78341  }else{
78342    return WRC_Continue;
78343  }
78344}
78345
78346/*
78347** Analyze the given expression looking for aggregate functions and
78348** for variables that need to be added to the pParse->aAgg[] array.
78349** Make additional entries to the pParse->aAgg[] array as necessary.
78350**
78351** This routine should only be called after the expression has been
78352** analyzed by sqlite3ResolveExprNames().
78353*/
78354SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
78355  Walker w;
78356  w.xExprCallback = analyzeAggregate;
78357  w.xSelectCallback = analyzeAggregatesInSelect;
78358  w.u.pNC = pNC;
78359  assert( pNC->pSrcList!=0 );
78360  sqlite3WalkExpr(&w, pExpr);
78361}
78362
78363/*
78364** Call sqlite3ExprAnalyzeAggregates() for every expression in an
78365** expression list.  Return the number of errors.
78366**
78367** If an error is found, the analysis is cut short.
78368*/
78369SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
78370  struct ExprList_item *pItem;
78371  int i;
78372  if( pList ){
78373    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
78374      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
78375    }
78376  }
78377}
78378
78379/*
78380** Allocate a single new register for use to hold some intermediate result.
78381*/
78382SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
78383  if( pParse->nTempReg==0 ){
78384    return ++pParse->nMem;
78385  }
78386  return pParse->aTempReg[--pParse->nTempReg];
78387}
78388
78389/*
78390** Deallocate a register, making available for reuse for some other
78391** purpose.
78392**
78393** If a register is currently being used by the column cache, then
78394** the dallocation is deferred until the column cache line that uses
78395** the register becomes stale.
78396*/
78397SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
78398  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
78399    int i;
78400    struct yColCache *p;
78401    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78402      if( p->iReg==iReg ){
78403        p->tempReg = 1;
78404        return;
78405      }
78406    }
78407    pParse->aTempReg[pParse->nTempReg++] = iReg;
78408  }
78409}
78410
78411/*
78412** Allocate or deallocate a block of nReg consecutive registers
78413*/
78414SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
78415  int i, n;
78416  i = pParse->iRangeReg;
78417  n = pParse->nRangeReg;
78418  if( nReg<=n ){
78419    assert( !usedAsColumnCache(pParse, i, i+n-1) );
78420    pParse->iRangeReg += nReg;
78421    pParse->nRangeReg -= nReg;
78422  }else{
78423    i = pParse->nMem+1;
78424    pParse->nMem += nReg;
78425  }
78426  return i;
78427}
78428SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
78429  sqlite3ExprCacheRemove(pParse, iReg, nReg);
78430  if( nReg>pParse->nRangeReg ){
78431    pParse->nRangeReg = nReg;
78432    pParse->iRangeReg = iReg;
78433  }
78434}
78435
78436/*
78437** Mark all temporary registers as being unavailable for reuse.
78438*/
78439SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
78440  pParse->nTempReg = 0;
78441  pParse->nRangeReg = 0;
78442}
78443
78444/************** End of expr.c ************************************************/
78445/************** Begin file alter.c *******************************************/
78446/*
78447** 2005 February 15
78448**
78449** The author disclaims copyright to this source code.  In place of
78450** a legal notice, here is a blessing:
78451**
78452**    May you do good and not evil.
78453**    May you find forgiveness for yourself and forgive others.
78454**    May you share freely, never taking more than you give.
78455**
78456*************************************************************************
78457** This file contains C code routines that used to generate VDBE code
78458** that implements the ALTER TABLE command.
78459*/
78460
78461/*
78462** The code in this file only exists if we are not omitting the
78463** ALTER TABLE logic from the build.
78464*/
78465#ifndef SQLITE_OMIT_ALTERTABLE
78466
78467
78468/*
78469** This function is used by SQL generated to implement the
78470** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
78471** CREATE INDEX command. The second is a table name. The table name in
78472** the CREATE TABLE or CREATE INDEX statement is replaced with the third
78473** argument and the result returned. Examples:
78474**
78475** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
78476**     -> 'CREATE TABLE def(a, b, c)'
78477**
78478** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
78479**     -> 'CREATE INDEX i ON def(a, b, c)'
78480*/
78481static void renameTableFunc(
78482  sqlite3_context *context,
78483  int NotUsed,
78484  sqlite3_value **argv
78485){
78486  unsigned char const *zSql = sqlite3_value_text(argv[0]);
78487  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
78488
78489  int token;
78490  Token tname;
78491  unsigned char const *zCsr = zSql;
78492  int len = 0;
78493  char *zRet;
78494
78495  sqlite3 *db = sqlite3_context_db_handle(context);
78496
78497  UNUSED_PARAMETER(NotUsed);
78498
78499  /* The principle used to locate the table name in the CREATE TABLE
78500  ** statement is that the table name is the first non-space token that
78501  ** is immediately followed by a TK_LP or TK_USING token.
78502  */
78503  if( zSql ){
78504    do {
78505      if( !*zCsr ){
78506        /* Ran out of input before finding an opening bracket. Return NULL. */
78507        return;
78508      }
78509
78510      /* Store the token that zCsr points to in tname. */
78511      tname.z = (char*)zCsr;
78512      tname.n = len;
78513
78514      /* Advance zCsr to the next token. Store that token type in 'token',
78515      ** and its length in 'len' (to be used next iteration of this loop).
78516      */
78517      do {
78518        zCsr += len;
78519        len = sqlite3GetToken(zCsr, &token);
78520      } while( token==TK_SPACE );
78521      assert( len>0 );
78522    } while( token!=TK_LP && token!=TK_USING );
78523
78524    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
78525       zTableName, tname.z+tname.n);
78526    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
78527  }
78528}
78529
78530/*
78531** This C function implements an SQL user function that is used by SQL code
78532** generated by the ALTER TABLE ... RENAME command to modify the definition
78533** of any foreign key constraints that use the table being renamed as the
78534** parent table. It is passed three arguments:
78535**
78536**   1) The complete text of the CREATE TABLE statement being modified,
78537**   2) The old name of the table being renamed, and
78538**   3) The new name of the table being renamed.
78539**
78540** It returns the new CREATE TABLE statement. For example:
78541**
78542**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
78543**       -> 'CREATE TABLE t1(a REFERENCES t3)'
78544*/
78545#ifndef SQLITE_OMIT_FOREIGN_KEY
78546static void renameParentFunc(
78547  sqlite3_context *context,
78548  int NotUsed,
78549  sqlite3_value **argv
78550){
78551  sqlite3 *db = sqlite3_context_db_handle(context);
78552  char *zOutput = 0;
78553  char *zResult;
78554  unsigned char const *zInput = sqlite3_value_text(argv[0]);
78555  unsigned char const *zOld = sqlite3_value_text(argv[1]);
78556  unsigned char const *zNew = sqlite3_value_text(argv[2]);
78557
78558  unsigned const char *z;         /* Pointer to token */
78559  int n;                          /* Length of token z */
78560  int token;                      /* Type of token */
78561
78562  UNUSED_PARAMETER(NotUsed);
78563  for(z=zInput; *z; z=z+n){
78564    n = sqlite3GetToken(z, &token);
78565    if( token==TK_REFERENCES ){
78566      char *zParent;
78567      do {
78568        z += n;
78569        n = sqlite3GetToken(z, &token);
78570      }while( token==TK_SPACE );
78571
78572      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
78573      if( zParent==0 ) break;
78574      sqlite3Dequote(zParent);
78575      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
78576        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
78577            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
78578        );
78579        sqlite3DbFree(db, zOutput);
78580        zOutput = zOut;
78581        zInput = &z[n];
78582      }
78583      sqlite3DbFree(db, zParent);
78584    }
78585  }
78586
78587  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
78588  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
78589  sqlite3DbFree(db, zOutput);
78590}
78591#endif
78592
78593#ifndef SQLITE_OMIT_TRIGGER
78594/* This function is used by SQL generated to implement the
78595** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
78596** statement. The second is a table name. The table name in the CREATE
78597** TRIGGER statement is replaced with the third argument and the result
78598** returned. This is analagous to renameTableFunc() above, except for CREATE
78599** TRIGGER, not CREATE INDEX and CREATE TABLE.
78600*/
78601static void renameTriggerFunc(
78602  sqlite3_context *context,
78603  int NotUsed,
78604  sqlite3_value **argv
78605){
78606  unsigned char const *zSql = sqlite3_value_text(argv[0]);
78607  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
78608
78609  int token;
78610  Token tname;
78611  int dist = 3;
78612  unsigned char const *zCsr = zSql;
78613  int len = 0;
78614  char *zRet;
78615  sqlite3 *db = sqlite3_context_db_handle(context);
78616
78617  UNUSED_PARAMETER(NotUsed);
78618
78619  /* The principle used to locate the table name in the CREATE TRIGGER
78620  ** statement is that the table name is the first token that is immediatedly
78621  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
78622  ** of TK_WHEN, TK_BEGIN or TK_FOR.
78623  */
78624  if( zSql ){
78625    do {
78626
78627      if( !*zCsr ){
78628        /* Ran out of input before finding the table name. Return NULL. */
78629        return;
78630      }
78631
78632      /* Store the token that zCsr points to in tname. */
78633      tname.z = (char*)zCsr;
78634      tname.n = len;
78635
78636      /* Advance zCsr to the next token. Store that token type in 'token',
78637      ** and its length in 'len' (to be used next iteration of this loop).
78638      */
78639      do {
78640        zCsr += len;
78641        len = sqlite3GetToken(zCsr, &token);
78642      }while( token==TK_SPACE );
78643      assert( len>0 );
78644
78645      /* Variable 'dist' stores the number of tokens read since the most
78646      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
78647      ** token is read and 'dist' equals 2, the condition stated above
78648      ** to be met.
78649      **
78650      ** Note that ON cannot be a database, table or column name, so
78651      ** there is no need to worry about syntax like
78652      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
78653      */
78654      dist++;
78655      if( token==TK_DOT || token==TK_ON ){
78656        dist = 0;
78657      }
78658    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
78659
78660    /* Variable tname now contains the token that is the old table-name
78661    ** in the CREATE TRIGGER statement.
78662    */
78663    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
78664       zTableName, tname.z+tname.n);
78665    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
78666  }
78667}
78668#endif   /* !SQLITE_OMIT_TRIGGER */
78669
78670/*
78671** Register built-in functions used to help implement ALTER TABLE
78672*/
78673SQLITE_PRIVATE void sqlite3AlterFunctions(void){
78674  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
78675    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
78676#ifndef SQLITE_OMIT_TRIGGER
78677    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
78678#endif
78679#ifndef SQLITE_OMIT_FOREIGN_KEY
78680    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
78681#endif
78682  };
78683  int i;
78684  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
78685  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
78686
78687  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
78688    sqlite3FuncDefInsert(pHash, &aFunc[i]);
78689  }
78690}
78691
78692/*
78693** This function is used to create the text of expressions of the form:
78694**
78695**   name=<constant1> OR name=<constant2> OR ...
78696**
78697** If argument zWhere is NULL, then a pointer string containing the text
78698** "name=<constant>" is returned, where <constant> is the quoted version
78699** of the string passed as argument zConstant. The returned buffer is
78700** allocated using sqlite3DbMalloc(). It is the responsibility of the
78701** caller to ensure that it is eventually freed.
78702**
78703** If argument zWhere is not NULL, then the string returned is
78704** "<where> OR name=<constant>", where <where> is the contents of zWhere.
78705** In this case zWhere is passed to sqlite3DbFree() before returning.
78706**
78707*/
78708static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
78709  char *zNew;
78710  if( !zWhere ){
78711    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
78712  }else{
78713    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
78714    sqlite3DbFree(db, zWhere);
78715  }
78716  return zNew;
78717}
78718
78719#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78720/*
78721** Generate the text of a WHERE expression which can be used to select all
78722** tables that have foreign key constraints that refer to table pTab (i.e.
78723** constraints for which pTab is the parent table) from the sqlite_master
78724** table.
78725*/
78726static char *whereForeignKeys(Parse *pParse, Table *pTab){
78727  FKey *p;
78728  char *zWhere = 0;
78729  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
78730    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
78731  }
78732  return zWhere;
78733}
78734#endif
78735
78736/*
78737** Generate the text of a WHERE expression which can be used to select all
78738** temporary triggers on table pTab from the sqlite_temp_master table. If
78739** table pTab has no temporary triggers, or is itself stored in the
78740** temporary database, NULL is returned.
78741*/
78742static char *whereTempTriggers(Parse *pParse, Table *pTab){
78743  Trigger *pTrig;
78744  char *zWhere = 0;
78745  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
78746
78747  /* If the table is not located in the temp-db (in which case NULL is
78748  ** returned, loop through the tables list of triggers. For each trigger
78749  ** that is not part of the temp-db schema, add a clause to the WHERE
78750  ** expression being built up in zWhere.
78751  */
78752  if( pTab->pSchema!=pTempSchema ){
78753    sqlite3 *db = pParse->db;
78754    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78755      if( pTrig->pSchema==pTempSchema ){
78756        zWhere = whereOrName(db, zWhere, pTrig->zName);
78757      }
78758    }
78759  }
78760  if( zWhere ){
78761    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
78762    sqlite3DbFree(pParse->db, zWhere);
78763    zWhere = zNew;
78764  }
78765  return zWhere;
78766}
78767
78768/*
78769** Generate code to drop and reload the internal representation of table
78770** pTab from the database, including triggers and temporary triggers.
78771** Argument zName is the name of the table in the database schema at
78772** the time the generated code is executed. This can be different from
78773** pTab->zName if this function is being called to code part of an
78774** "ALTER TABLE RENAME TO" statement.
78775*/
78776static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
78777  Vdbe *v;
78778  char *zWhere;
78779  int iDb;                   /* Index of database containing pTab */
78780#ifndef SQLITE_OMIT_TRIGGER
78781  Trigger *pTrig;
78782#endif
78783
78784  v = sqlite3GetVdbe(pParse);
78785  if( NEVER(v==0) ) return;
78786  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78787  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78788  assert( iDb>=0 );
78789
78790#ifndef SQLITE_OMIT_TRIGGER
78791  /* Drop any table triggers from the internal schema. */
78792  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78793    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
78794    assert( iTrigDb==iDb || iTrigDb==1 );
78795    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
78796  }
78797#endif
78798
78799  /* Drop the table and index from the internal schema.  */
78800  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
78801
78802  /* Reload the table, index and permanent trigger schemas. */
78803  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
78804  if( !zWhere ) return;
78805  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
78806
78807#ifndef SQLITE_OMIT_TRIGGER
78808  /* Now, if the table is not stored in the temp database, reload any temp
78809  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
78810  */
78811  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78812    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
78813  }
78814#endif
78815}
78816
78817/*
78818** Parameter zName is the name of a table that is about to be altered
78819** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
78820** If the table is a system table, this function leaves an error message
78821** in pParse->zErr (system tables may not be altered) and returns non-zero.
78822**
78823** Or, if zName is not a system table, zero is returned.
78824*/
78825static int isSystemTable(Parse *pParse, const char *zName){
78826  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
78827    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
78828    return 1;
78829  }
78830  return 0;
78831}
78832
78833/*
78834** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
78835** command.
78836*/
78837SQLITE_PRIVATE void sqlite3AlterRenameTable(
78838  Parse *pParse,            /* Parser context. */
78839  SrcList *pSrc,            /* The table to rename. */
78840  Token *pName              /* The new table name. */
78841){
78842  int iDb;                  /* Database that contains the table */
78843  char *zDb;                /* Name of database iDb */
78844  Table *pTab;              /* Table being renamed */
78845  char *zName = 0;          /* NULL-terminated version of pName */
78846  sqlite3 *db = pParse->db; /* Database connection */
78847  int nTabName;             /* Number of UTF-8 characters in zTabName */
78848  const char *zTabName;     /* Original name of the table */
78849  Vdbe *v;
78850#ifndef SQLITE_OMIT_TRIGGER
78851  char *zWhere = 0;         /* Where clause to locate temp triggers */
78852#endif
78853  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
78854  int savedDbFlags;         /* Saved value of db->flags */
78855
78856  savedDbFlags = db->flags;
78857  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
78858  assert( pSrc->nSrc==1 );
78859  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78860
78861  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
78862  if( !pTab ) goto exit_rename_table;
78863  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78864  zDb = db->aDb[iDb].zName;
78865  db->flags |= SQLITE_PreferBuiltin;
78866
78867  /* Get a NULL terminated version of the new table name. */
78868  zName = sqlite3NameFromToken(db, pName);
78869  if( !zName ) goto exit_rename_table;
78870
78871  /* Check that a table or index named 'zName' does not already exist
78872  ** in database iDb. If so, this is an error.
78873  */
78874  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
78875    sqlite3ErrorMsg(pParse,
78876        "there is already another table or index with this name: %s", zName);
78877    goto exit_rename_table;
78878  }
78879
78880  /* Make sure it is not a system table being altered, or a reserved name
78881  ** that the table is being renamed to.
78882  */
78883  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
78884    goto exit_rename_table;
78885  }
78886  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
78887    exit_rename_table;
78888  }
78889
78890#ifndef SQLITE_OMIT_VIEW
78891  if( pTab->pSelect ){
78892    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
78893    goto exit_rename_table;
78894  }
78895#endif
78896
78897#ifndef SQLITE_OMIT_AUTHORIZATION
78898  /* Invoke the authorization callback. */
78899  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
78900    goto exit_rename_table;
78901  }
78902#endif
78903
78904#ifndef SQLITE_OMIT_VIRTUALTABLE
78905  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
78906    goto exit_rename_table;
78907  }
78908  if( IsVirtual(pTab) ){
78909    pVTab = sqlite3GetVTable(db, pTab);
78910    if( pVTab->pVtab->pModule->xRename==0 ){
78911      pVTab = 0;
78912    }
78913  }
78914#endif
78915
78916  /* Begin a transaction and code the VerifyCookie for database iDb.
78917  ** Then modify the schema cookie (since the ALTER TABLE modifies the
78918  ** schema). Open a statement transaction if the table is a virtual
78919  ** table.
78920  */
78921  v = sqlite3GetVdbe(pParse);
78922  if( v==0 ){
78923    goto exit_rename_table;
78924  }
78925  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
78926  sqlite3ChangeCookie(pParse, iDb);
78927
78928  /* If this is a virtual table, invoke the xRename() function if
78929  ** one is defined. The xRename() callback will modify the names
78930  ** of any resources used by the v-table implementation (including other
78931  ** SQLite tables) that are identified by the name of the virtual table.
78932  */
78933#ifndef SQLITE_OMIT_VIRTUALTABLE
78934  if( pVTab ){
78935    int i = ++pParse->nMem;
78936    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
78937    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
78938    sqlite3MayAbort(pParse);
78939  }
78940#endif
78941
78942  /* figure out how many UTF-8 characters are in zName */
78943  zTabName = pTab->zName;
78944  nTabName = sqlite3Utf8CharLen(zTabName, -1);
78945
78946#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78947  if( db->flags&SQLITE_ForeignKeys ){
78948    /* If foreign-key support is enabled, rewrite the CREATE TABLE
78949    ** statements corresponding to all child tables of foreign key constraints
78950    ** for which the renamed table is the parent table.  */
78951    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
78952      sqlite3NestedParse(pParse,
78953          "UPDATE \"%w\".%s SET "
78954              "sql = sqlite_rename_parent(sql, %Q, %Q) "
78955              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
78956      sqlite3DbFree(db, zWhere);
78957    }
78958  }
78959#endif
78960
78961  /* Modify the sqlite_master table to use the new table name. */
78962  sqlite3NestedParse(pParse,
78963      "UPDATE %Q.%s SET "
78964#ifdef SQLITE_OMIT_TRIGGER
78965          "sql = sqlite_rename_table(sql, %Q), "
78966#else
78967          "sql = CASE "
78968            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
78969            "ELSE sqlite_rename_table(sql, %Q) END, "
78970#endif
78971          "tbl_name = %Q, "
78972          "name = CASE "
78973            "WHEN type='table' THEN %Q "
78974            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
78975             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
78976            "ELSE name END "
78977      "WHERE tbl_name=%Q COLLATE nocase AND "
78978          "(type='table' OR type='index' OR type='trigger');",
78979      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
78980#ifndef SQLITE_OMIT_TRIGGER
78981      zName,
78982#endif
78983      zName, nTabName, zTabName
78984  );
78985
78986#ifndef SQLITE_OMIT_AUTOINCREMENT
78987  /* If the sqlite_sequence table exists in this database, then update
78988  ** it with the new table name.
78989  */
78990  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
78991    sqlite3NestedParse(pParse,
78992        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
78993        zDb, zName, pTab->zName);
78994  }
78995#endif
78996
78997#ifndef SQLITE_OMIT_TRIGGER
78998  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
78999  ** table. Don't do this if the table being ALTERed is itself located in
79000  ** the temp database.
79001  */
79002  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
79003    sqlite3NestedParse(pParse,
79004        "UPDATE sqlite_temp_master SET "
79005            "sql = sqlite_rename_trigger(sql, %Q), "
79006            "tbl_name = %Q "
79007            "WHERE %s;", zName, zName, zWhere);
79008    sqlite3DbFree(db, zWhere);
79009  }
79010#endif
79011
79012#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79013  if( db->flags&SQLITE_ForeignKeys ){
79014    FKey *p;
79015    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79016      Table *pFrom = p->pFrom;
79017      if( pFrom!=pTab ){
79018        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
79019      }
79020    }
79021  }
79022#endif
79023
79024  /* Drop and reload the internal table schema. */
79025  reloadTableSchema(pParse, pTab, zName);
79026
79027exit_rename_table:
79028  sqlite3SrcListDelete(db, pSrc);
79029  sqlite3DbFree(db, zName);
79030  db->flags = savedDbFlags;
79031}
79032
79033
79034/*
79035** Generate code to make sure the file format number is at least minFormat.
79036** The generated code will increase the file format number if necessary.
79037*/
79038SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
79039  Vdbe *v;
79040  v = sqlite3GetVdbe(pParse);
79041  /* The VDBE should have been allocated before this routine is called.
79042  ** If that allocation failed, we would have quit before reaching this
79043  ** point */
79044  if( ALWAYS(v) ){
79045    int r1 = sqlite3GetTempReg(pParse);
79046    int r2 = sqlite3GetTempReg(pParse);
79047    int j1;
79048    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
79049    sqlite3VdbeUsesBtree(v, iDb);
79050    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
79051    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
79052    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
79053    sqlite3VdbeJumpHere(v, j1);
79054    sqlite3ReleaseTempReg(pParse, r1);
79055    sqlite3ReleaseTempReg(pParse, r2);
79056  }
79057}
79058
79059/*
79060** This function is called after an "ALTER TABLE ... ADD" statement
79061** has been parsed. Argument pColDef contains the text of the new
79062** column definition.
79063**
79064** The Table structure pParse->pNewTable was extended to include
79065** the new column during parsing.
79066*/
79067SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
79068  Table *pNew;              /* Copy of pParse->pNewTable */
79069  Table *pTab;              /* Table being altered */
79070  int iDb;                  /* Database number */
79071  const char *zDb;          /* Database name */
79072  const char *zTab;         /* Table name */
79073  char *zCol;               /* Null-terminated column definition */
79074  Column *pCol;             /* The new column */
79075  Expr *pDflt;              /* Default value for the new column */
79076  sqlite3 *db;              /* The database connection; */
79077
79078  db = pParse->db;
79079  if( pParse->nErr || db->mallocFailed ) return;
79080  pNew = pParse->pNewTable;
79081  assert( pNew );
79082
79083  assert( sqlite3BtreeHoldsAllMutexes(db) );
79084  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
79085  zDb = db->aDb[iDb].zName;
79086  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
79087  pCol = &pNew->aCol[pNew->nCol-1];
79088  pDflt = pCol->pDflt;
79089  pTab = sqlite3FindTable(db, zTab, zDb);
79090  assert( pTab );
79091
79092#ifndef SQLITE_OMIT_AUTHORIZATION
79093  /* Invoke the authorization callback. */
79094  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
79095    return;
79096  }
79097#endif
79098
79099  /* If the default value for the new column was specified with a
79100  ** literal NULL, then set pDflt to 0. This simplifies checking
79101  ** for an SQL NULL default below.
79102  */
79103  if( pDflt && pDflt->op==TK_NULL ){
79104    pDflt = 0;
79105  }
79106
79107  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
79108  ** If there is a NOT NULL constraint, then the default value for the
79109  ** column must not be NULL.
79110  */
79111  if( pCol->isPrimKey ){
79112    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
79113    return;
79114  }
79115  if( pNew->pIndex ){
79116    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
79117    return;
79118  }
79119  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
79120    sqlite3ErrorMsg(pParse,
79121        "Cannot add a REFERENCES column with non-NULL default value");
79122    return;
79123  }
79124  if( pCol->notNull && !pDflt ){
79125    sqlite3ErrorMsg(pParse,
79126        "Cannot add a NOT NULL column with default value NULL");
79127    return;
79128  }
79129
79130  /* Ensure the default expression is something that sqlite3ValueFromExpr()
79131  ** can handle (i.e. not CURRENT_TIME etc.)
79132  */
79133  if( pDflt ){
79134    sqlite3_value *pVal;
79135    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
79136      db->mallocFailed = 1;
79137      return;
79138    }
79139    if( !pVal ){
79140      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
79141      return;
79142    }
79143    sqlite3ValueFree(pVal);
79144  }
79145
79146  /* Modify the CREATE TABLE statement. */
79147  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
79148  if( zCol ){
79149    char *zEnd = &zCol[pColDef->n-1];
79150    int savedDbFlags = db->flags;
79151    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
79152      *zEnd-- = '\0';
79153    }
79154    db->flags |= SQLITE_PreferBuiltin;
79155    sqlite3NestedParse(pParse,
79156        "UPDATE \"%w\".%s SET "
79157          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
79158        "WHERE type = 'table' AND name = %Q",
79159      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
79160      zTab
79161    );
79162    sqlite3DbFree(db, zCol);
79163    db->flags = savedDbFlags;
79164  }
79165
79166  /* If the default value of the new column is NULL, then set the file
79167  ** format to 2. If the default value of the new column is not NULL,
79168  ** the file format becomes 3.
79169  */
79170  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
79171
79172  /* Reload the schema of the modified table. */
79173  reloadTableSchema(pParse, pTab, pTab->zName);
79174}
79175
79176/*
79177** This function is called by the parser after the table-name in
79178** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
79179** pSrc is the full-name of the table being altered.
79180**
79181** This routine makes a (partial) copy of the Table structure
79182** for the table being altered and sets Parse.pNewTable to point
79183** to it. Routines called by the parser as the column definition
79184** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
79185** the copy. The copy of the Table structure is deleted by tokenize.c
79186** after parsing is finished.
79187**
79188** Routine sqlite3AlterFinishAddColumn() will be called to complete
79189** coding the "ALTER TABLE ... ADD" statement.
79190*/
79191SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
79192  Table *pNew;
79193  Table *pTab;
79194  Vdbe *v;
79195  int iDb;
79196  int i;
79197  int nAlloc;
79198  sqlite3 *db = pParse->db;
79199
79200  /* Look up the table being altered. */
79201  assert( pParse->pNewTable==0 );
79202  assert( sqlite3BtreeHoldsAllMutexes(db) );
79203  if( db->mallocFailed ) goto exit_begin_add_column;
79204  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
79205  if( !pTab ) goto exit_begin_add_column;
79206
79207#ifndef SQLITE_OMIT_VIRTUALTABLE
79208  if( IsVirtual(pTab) ){
79209    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
79210    goto exit_begin_add_column;
79211  }
79212#endif
79213
79214  /* Make sure this is not an attempt to ALTER a view. */
79215  if( pTab->pSelect ){
79216    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
79217    goto exit_begin_add_column;
79218  }
79219  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
79220    goto exit_begin_add_column;
79221  }
79222
79223  assert( pTab->addColOffset>0 );
79224  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79225
79226  /* Put a copy of the Table struct in Parse.pNewTable for the
79227  ** sqlite3AddColumn() function and friends to modify.  But modify
79228  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
79229  ** prefix, we insure that the name will not collide with an existing
79230  ** table because user table are not allowed to have the "sqlite_"
79231  ** prefix on their name.
79232  */
79233  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
79234  if( !pNew ) goto exit_begin_add_column;
79235  pParse->pNewTable = pNew;
79236  pNew->nRef = 1;
79237  pNew->nCol = pTab->nCol;
79238  assert( pNew->nCol>0 );
79239  nAlloc = (((pNew->nCol-1)/8)*8)+8;
79240  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
79241  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
79242  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
79243  if( !pNew->aCol || !pNew->zName ){
79244    db->mallocFailed = 1;
79245    goto exit_begin_add_column;
79246  }
79247  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
79248  for(i=0; i<pNew->nCol; i++){
79249    Column *pCol = &pNew->aCol[i];
79250    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
79251    pCol->zColl = 0;
79252    pCol->zType = 0;
79253    pCol->pDflt = 0;
79254    pCol->zDflt = 0;
79255  }
79256  pNew->pSchema = db->aDb[iDb].pSchema;
79257  pNew->addColOffset = pTab->addColOffset;
79258  pNew->nRef = 1;
79259
79260  /* Begin a transaction and increment the schema cookie.  */
79261  sqlite3BeginWriteOperation(pParse, 0, iDb);
79262  v = sqlite3GetVdbe(pParse);
79263  if( !v ) goto exit_begin_add_column;
79264  sqlite3ChangeCookie(pParse, iDb);
79265
79266exit_begin_add_column:
79267  sqlite3SrcListDelete(db, pSrc);
79268  return;
79269}
79270#endif  /* SQLITE_ALTER_TABLE */
79271
79272/************** End of alter.c ***********************************************/
79273/************** Begin file analyze.c *****************************************/
79274/*
79275** 2005 July 8
79276**
79277** The author disclaims copyright to this source code.  In place of
79278** a legal notice, here is a blessing:
79279**
79280**    May you do good and not evil.
79281**    May you find forgiveness for yourself and forgive others.
79282**    May you share freely, never taking more than you give.
79283**
79284*************************************************************************
79285** This file contains code associated with the ANALYZE command.
79286**
79287** The ANALYZE command gather statistics about the content of tables
79288** and indices.  These statistics are made available to the query planner
79289** to help it make better decisions about how to perform queries.
79290**
79291** The following system tables are or have been supported:
79292**
79293**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
79294**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
79295**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
79296**
79297** Additional tables might be added in future releases of SQLite.
79298** The sqlite_stat2 table is not created or used unless the SQLite version
79299** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
79300** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
79301** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
79302** created and used by SQLite versions 3.7.9 and later and with
79303** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
79304** is a superset of sqlite_stat2.
79305**
79306** Format of sqlite_stat1:
79307**
79308** There is normally one row per index, with the index identified by the
79309** name in the idx column.  The tbl column is the name of the table to
79310** which the index belongs.  In each such row, the stat column will be
79311** a string consisting of a list of integers.  The first integer in this
79312** list is the number of rows in the index and in the table.  The second
79313** integer is the average number of rows in the index that have the same
79314** value in the first column of the index.  The third integer is the average
79315** number of rows in the index that have the same value for the first two
79316** columns.  The N-th integer (for N>1) is the average number of rows in
79317** the index which have the same value for the first N-1 columns.  For
79318** a K-column index, there will be K+1 integers in the stat column.  If
79319** the index is unique, then the last integer will be 1.
79320**
79321** The list of integers in the stat column can optionally be followed
79322** by the keyword "unordered".  The "unordered" keyword, if it is present,
79323** must be separated from the last integer by a single space.  If the
79324** "unordered" keyword is present, then the query planner assumes that
79325** the index is unordered and will not use the index for a range query.
79326**
79327** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
79328** column contains a single integer which is the (estimated) number of
79329** rows in the table identified by sqlite_stat1.tbl.
79330**
79331** Format of sqlite_stat2:
79332**
79333** The sqlite_stat2 is only created and is only used if SQLite is compiled
79334** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
79335** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
79336** about the distribution of keys within an index.  The index is identified by
79337** the "idx" column and the "tbl" column is the name of the table to which
79338** the index belongs.  There are usually 10 rows in the sqlite_stat2
79339** table for each index.
79340**
79341** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
79342** inclusive are samples of the left-most key value in the index taken at
79343** evenly spaced points along the index.  Let the number of samples be S
79344** (10 in the standard build) and let C be the number of rows in the index.
79345** Then the sampled rows are given by:
79346**
79347**     rownumber = (i*C*2 + C)/(S*2)
79348**
79349** For i between 0 and S-1.  Conceptually, the index space is divided into
79350** S uniform buckets and the samples are the middle row from each bucket.
79351**
79352** The format for sqlite_stat2 is recorded here for legacy reference.  This
79353** version of SQLite does not support sqlite_stat2.  It neither reads nor
79354** writes the sqlite_stat2 table.  This version of SQLite only supports
79355** sqlite_stat3.
79356**
79357** Format for sqlite_stat3:
79358**
79359** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
79360** used to avoid compatibility problems.
79361**
79362** The format of the sqlite_stat3 table is similar to the format of
79363** the sqlite_stat2 table.  There are multiple entries for each index.
79364** The idx column names the index and the tbl column is the table of the
79365** index.  If the idx and tbl columns are the same, then the sample is
79366** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
79367** the left-most column of the index.  The nEq column is the approximate
79368** number of entires in the index whose left-most column exactly matches
79369** the sample.  nLt is the approximate number of entires whose left-most
79370** column is less than the sample.  The nDLt column is the approximate
79371** number of distinct left-most entries in the index that are less than
79372** the sample.
79373**
79374** Future versions of SQLite might change to store a string containing
79375** multiple integers values in the nDLt column of sqlite_stat3.  The first
79376** integer will be the number of prior index entires that are distinct in
79377** the left-most column.  The second integer will be the number of prior index
79378** entries that are distinct in the first two columns.  The third integer
79379** will be the number of prior index entries that are distinct in the first
79380** three columns.  And so forth.  With that extension, the nDLt field is
79381** similar in function to the sqlite_stat1.stat field.
79382**
79383** There can be an arbitrary number of sqlite_stat3 entries per index.
79384** The ANALYZE command will typically generate sqlite_stat3 tables
79385** that contain between 10 and 40 samples which are distributed across
79386** the key space, though not uniformly, and which include samples with
79387** largest possible nEq values.
79388*/
79389#ifndef SQLITE_OMIT_ANALYZE
79390
79391/*
79392** This routine generates code that opens the sqlite_stat1 table for
79393** writing with cursor iStatCur. If the library was built with the
79394** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
79395** opened for writing using cursor (iStatCur+1)
79396**
79397** If the sqlite_stat1 tables does not previously exist, it is created.
79398** Similarly, if the sqlite_stat3 table does not exist and the library
79399** is compiled with SQLITE_ENABLE_STAT3 defined, it is created.
79400**
79401** Argument zWhere may be a pointer to a buffer containing a table name,
79402** or it may be a NULL pointer. If it is not NULL, then all entries in
79403** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
79404** with the named table are deleted. If zWhere==0, then code is generated
79405** to delete all stat table entries.
79406*/
79407static void openStatTable(
79408  Parse *pParse,          /* Parsing context */
79409  int iDb,                /* The database we are looking in */
79410  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
79411  const char *zWhere,     /* Delete entries for this table or index */
79412  const char *zWhereType  /* Either "tbl" or "idx" */
79413){
79414  static const struct {
79415    const char *zName;
79416    const char *zCols;
79417  } aTable[] = {
79418    { "sqlite_stat1", "tbl,idx,stat" },
79419#ifdef SQLITE_ENABLE_STAT3
79420    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
79421#endif
79422  };
79423
79424  int aRoot[] = {0, 0};
79425  u8 aCreateTbl[] = {0, 0};
79426
79427  int i;
79428  sqlite3 *db = pParse->db;
79429  Db *pDb;
79430  Vdbe *v = sqlite3GetVdbe(pParse);
79431  if( v==0 ) return;
79432  assert( sqlite3BtreeHoldsAllMutexes(db) );
79433  assert( sqlite3VdbeDb(v)==db );
79434  pDb = &db->aDb[iDb];
79435
79436  /* Create new statistic tables if they do not exist, or clear them
79437  ** if they do already exist.
79438  */
79439  for(i=0; i<ArraySize(aTable); i++){
79440    const char *zTab = aTable[i].zName;
79441    Table *pStat;
79442    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
79443      /* The sqlite_stat[12] table does not exist. Create it. Note that a
79444      ** side-effect of the CREATE TABLE statement is to leave the rootpage
79445      ** of the new table in register pParse->regRoot. This is important
79446      ** because the OpenWrite opcode below will be needing it. */
79447      sqlite3NestedParse(pParse,
79448          "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
79449      );
79450      aRoot[i] = pParse->regRoot;
79451      aCreateTbl[i] = 1;
79452    }else{
79453      /* The table already exists. If zWhere is not NULL, delete all entries
79454      ** associated with the table zWhere. If zWhere is NULL, delete the
79455      ** entire contents of the table. */
79456      aRoot[i] = pStat->tnum;
79457      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
79458      if( zWhere ){
79459        sqlite3NestedParse(pParse,
79460           "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
79461        );
79462      }else{
79463        /* The sqlite_stat[12] table already exists.  Delete all rows. */
79464        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
79465      }
79466    }
79467  }
79468
79469  /* Open the sqlite_stat[13] tables for writing. */
79470  for(i=0; i<ArraySize(aTable); i++){
79471    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
79472    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
79473    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
79474  }
79475}
79476
79477/*
79478** Recommended number of samples for sqlite_stat3
79479*/
79480#ifndef SQLITE_STAT3_SAMPLES
79481# define SQLITE_STAT3_SAMPLES 24
79482#endif
79483
79484/*
79485** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
79486** share an instance of the following structure to hold their state
79487** information.
79488*/
79489typedef struct Stat3Accum Stat3Accum;
79490struct Stat3Accum {
79491  tRowcnt nRow;             /* Number of rows in the entire table */
79492  tRowcnt nPSample;         /* How often to do a periodic sample */
79493  int iMin;                 /* Index of entry with minimum nEq and hash */
79494  int mxSample;             /* Maximum number of samples to accumulate */
79495  int nSample;              /* Current number of samples */
79496  u32 iPrn;                 /* Pseudo-random number used for sampling */
79497  struct Stat3Sample {
79498    i64 iRowid;                /* Rowid in main table of the key */
79499    tRowcnt nEq;               /* sqlite_stat3.nEq */
79500    tRowcnt nLt;               /* sqlite_stat3.nLt */
79501    tRowcnt nDLt;              /* sqlite_stat3.nDLt */
79502    u8 isPSample;              /* True if a periodic sample */
79503    u32 iHash;                 /* Tiebreaker hash */
79504  } *a;                     /* An array of samples */
79505};
79506
79507#ifdef SQLITE_ENABLE_STAT3
79508/*
79509** Implementation of the stat3_init(C,S) SQL function.  The two parameters
79510** are the number of rows in the table or index (C) and the number of samples
79511** to accumulate (S).
79512**
79513** This routine allocates the Stat3Accum object.
79514**
79515** The return value is the Stat3Accum object (P).
79516*/
79517static void stat3Init(
79518  sqlite3_context *context,
79519  int argc,
79520  sqlite3_value **argv
79521){
79522  Stat3Accum *p;
79523  tRowcnt nRow;
79524  int mxSample;
79525  int n;
79526
79527  UNUSED_PARAMETER(argc);
79528  nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
79529  mxSample = sqlite3_value_int(argv[1]);
79530  n = sizeof(*p) + sizeof(p->a[0])*mxSample;
79531  p = sqlite3_malloc( n );
79532  if( p==0 ){
79533    sqlite3_result_error_nomem(context);
79534    return;
79535  }
79536  memset(p, 0, n);
79537  p->a = (struct Stat3Sample*)&p[1];
79538  p->nRow = nRow;
79539  p->mxSample = mxSample;
79540  p->nPSample = p->nRow/(mxSample/3+1) + 1;
79541  sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
79542  sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
79543}
79544static const FuncDef stat3InitFuncdef = {
79545  2,                /* nArg */
79546  SQLITE_UTF8,      /* iPrefEnc */
79547  0,                /* flags */
79548  0,                /* pUserData */
79549  0,                /* pNext */
79550  stat3Init,        /* xFunc */
79551  0,                /* xStep */
79552  0,                /* xFinalize */
79553  "stat3_init",     /* zName */
79554  0,                /* pHash */
79555  0                 /* pDestructor */
79556};
79557
79558
79559/*
79560** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
79561** arguments describe a single key instance.  This routine makes the
79562** decision about whether or not to retain this key for the sqlite_stat3
79563** table.
79564**
79565** The return value is NULL.
79566*/
79567static void stat3Push(
79568  sqlite3_context *context,
79569  int argc,
79570  sqlite3_value **argv
79571){
79572  Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
79573  tRowcnt nEq = sqlite3_value_int64(argv[0]);
79574  tRowcnt nLt = sqlite3_value_int64(argv[1]);
79575  tRowcnt nDLt = sqlite3_value_int64(argv[2]);
79576  i64 rowid = sqlite3_value_int64(argv[3]);
79577  u8 isPSample = 0;
79578  u8 doInsert = 0;
79579  int iMin = p->iMin;
79580  struct Stat3Sample *pSample;
79581  int i;
79582  u32 h;
79583
79584  UNUSED_PARAMETER(context);
79585  UNUSED_PARAMETER(argc);
79586  if( nEq==0 ) return;
79587  h = p->iPrn = p->iPrn*1103515245 + 12345;
79588  if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
79589    doInsert = isPSample = 1;
79590  }else if( p->nSample<p->mxSample ){
79591    doInsert = 1;
79592  }else{
79593    if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
79594      doInsert = 1;
79595    }
79596  }
79597  if( !doInsert ) return;
79598  if( p->nSample==p->mxSample ){
79599    assert( p->nSample - iMin - 1 >= 0 );
79600    memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
79601    pSample = &p->a[p->nSample-1];
79602  }else{
79603    pSample = &p->a[p->nSample++];
79604  }
79605  pSample->iRowid = rowid;
79606  pSample->nEq = nEq;
79607  pSample->nLt = nLt;
79608  pSample->nDLt = nDLt;
79609  pSample->iHash = h;
79610  pSample->isPSample = isPSample;
79611
79612  /* Find the new minimum */
79613  if( p->nSample==p->mxSample ){
79614    pSample = p->a;
79615    i = 0;
79616    while( pSample->isPSample ){
79617      i++;
79618      pSample++;
79619      assert( i<p->nSample );
79620    }
79621    nEq = pSample->nEq;
79622    h = pSample->iHash;
79623    iMin = i;
79624    for(i++, pSample++; i<p->nSample; i++, pSample++){
79625      if( pSample->isPSample ) continue;
79626      if( pSample->nEq<nEq
79627       || (pSample->nEq==nEq && pSample->iHash<h)
79628      ){
79629        iMin = i;
79630        nEq = pSample->nEq;
79631        h = pSample->iHash;
79632      }
79633    }
79634    p->iMin = iMin;
79635  }
79636}
79637static const FuncDef stat3PushFuncdef = {
79638  5,                /* nArg */
79639  SQLITE_UTF8,      /* iPrefEnc */
79640  0,                /* flags */
79641  0,                /* pUserData */
79642  0,                /* pNext */
79643  stat3Push,        /* xFunc */
79644  0,                /* xStep */
79645  0,                /* xFinalize */
79646  "stat3_push",     /* zName */
79647  0,                /* pHash */
79648  0                 /* pDestructor */
79649};
79650
79651/*
79652** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
79653** used to query the results.  Content is returned for the Nth sqlite_stat3
79654** row where N is between 0 and S-1 and S is the number of samples.  The
79655** value returned depends on the number of arguments.
79656**
79657**   argc==2    result:  rowid
79658**   argc==3    result:  nEq
79659**   argc==4    result:  nLt
79660**   argc==5    result:  nDLt
79661*/
79662static void stat3Get(
79663  sqlite3_context *context,
79664  int argc,
79665  sqlite3_value **argv
79666){
79667  int n = sqlite3_value_int(argv[1]);
79668  Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
79669
79670  assert( p!=0 );
79671  if( p->nSample<=n ) return;
79672  switch( argc ){
79673    case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
79674    case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
79675    case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
79676    default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
79677  }
79678}
79679static const FuncDef stat3GetFuncdef = {
79680  -1,               /* nArg */
79681  SQLITE_UTF8,      /* iPrefEnc */
79682  0,                /* flags */
79683  0,                /* pUserData */
79684  0,                /* pNext */
79685  stat3Get,         /* xFunc */
79686  0,                /* xStep */
79687  0,                /* xFinalize */
79688  "stat3_get",     /* zName */
79689  0,                /* pHash */
79690  0                 /* pDestructor */
79691};
79692#endif /* SQLITE_ENABLE_STAT3 */
79693
79694
79695
79696
79697/*
79698** Generate code to do an analysis of all indices associated with
79699** a single table.
79700*/
79701static void analyzeOneTable(
79702  Parse *pParse,   /* Parser context */
79703  Table *pTab,     /* Table whose indices are to be analyzed */
79704  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
79705  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
79706  int iMem         /* Available memory locations begin here */
79707){
79708  sqlite3 *db = pParse->db;    /* Database handle */
79709  Index *pIdx;                 /* An index to being analyzed */
79710  int iIdxCur;                 /* Cursor open on index being analyzed */
79711  Vdbe *v;                     /* The virtual machine being built up */
79712  int i;                       /* Loop counter */
79713  int topOfLoop;               /* The top of the loop */
79714  int endOfLoop;               /* The end of the loop */
79715  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
79716  int iDb;                     /* Index of database containing pTab */
79717  int regTabname = iMem++;     /* Register containing table name */
79718  int regIdxname = iMem++;     /* Register containing index name */
79719  int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
79720#ifdef SQLITE_ENABLE_STAT3
79721  int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
79722  int regNumLt = iMem++;       /* Number of keys less than regSample */
79723  int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
79724  int regSample = iMem++;      /* The next sample value */
79725  int regRowid = regSample;    /* Rowid of a sample */
79726  int regAccum = iMem++;       /* Register to hold Stat3Accum object */
79727  int regLoop = iMem++;        /* Loop counter */
79728  int regCount = iMem++;       /* Number of rows in the table or index */
79729  int regTemp1 = iMem++;       /* Intermediate register */
79730  int regTemp2 = iMem++;       /* Intermediate register */
79731  int once = 1;                /* One-time initialization */
79732  int shortJump = 0;           /* Instruction address */
79733  int iTabCur = pParse->nTab++; /* Table cursor */
79734#endif
79735  int regCol = iMem++;         /* Content of a column in analyzed table */
79736  int regRec = iMem++;         /* Register holding completed record */
79737  int regTemp = iMem++;        /* Temporary use register */
79738  int regNewRowid = iMem++;    /* Rowid for the inserted record */
79739
79740
79741  v = sqlite3GetVdbe(pParse);
79742  if( v==0 || NEVER(pTab==0) ){
79743    return;
79744  }
79745  if( pTab->tnum==0 ){
79746    /* Do not gather statistics on views or virtual tables */
79747    return;
79748  }
79749  if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
79750    /* Do not gather statistics on system tables */
79751    return;
79752  }
79753  assert( sqlite3BtreeHoldsAllMutexes(db) );
79754  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79755  assert( iDb>=0 );
79756  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79757#ifndef SQLITE_OMIT_AUTHORIZATION
79758  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
79759      db->aDb[iDb].zName ) ){
79760    return;
79761  }
79762#endif
79763
79764  /* Establish a read-lock on the table at the shared-cache level. */
79765  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
79766
79767  iIdxCur = pParse->nTab++;
79768  sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
79769  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79770    int nCol;
79771    KeyInfo *pKey;
79772    int addrIfNot = 0;           /* address of OP_IfNot */
79773    int *aChngAddr;              /* Array of jump instruction addresses */
79774
79775    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
79776    VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
79777    nCol = pIdx->nColumn;
79778    aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
79779    if( aChngAddr==0 ) continue;
79780    pKey = sqlite3IndexKeyinfo(pParse, pIdx);
79781    if( iMem+1+(nCol*2)>pParse->nMem ){
79782      pParse->nMem = iMem+1+(nCol*2);
79783    }
79784
79785    /* Open a cursor to the index to be analyzed. */
79786    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
79787    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
79788        (char *)pKey, P4_KEYINFO_HANDOFF);
79789    VdbeComment((v, "%s", pIdx->zName));
79790
79791    /* Populate the register containing the index name. */
79792    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
79793
79794#ifdef SQLITE_ENABLE_STAT3
79795    if( once ){
79796      once = 0;
79797      sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
79798    }
79799    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
79800    sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
79801    sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
79802    sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
79803    sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
79804    sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
79805    sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
79806                      (char*)&stat3InitFuncdef, P4_FUNCDEF);
79807    sqlite3VdbeChangeP5(v, 2);
79808#endif /* SQLITE_ENABLE_STAT3 */
79809
79810    /* The block of memory cells initialized here is used as follows.
79811    **
79812    **    iMem:
79813    **        The total number of rows in the table.
79814    **
79815    **    iMem+1 .. iMem+nCol:
79816    **        Number of distinct entries in index considering the
79817    **        left-most N columns only, where N is between 1 and nCol,
79818    **        inclusive.
79819    **
79820    **    iMem+nCol+1 .. Mem+2*nCol:
79821    **        Previous value of indexed columns, from left to right.
79822    **
79823    ** Cells iMem through iMem+nCol are initialized to 0. The others are
79824    ** initialized to contain an SQL NULL.
79825    */
79826    for(i=0; i<=nCol; i++){
79827      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
79828    }
79829    for(i=0; i<nCol; i++){
79830      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
79831    }
79832
79833    /* Start the analysis loop. This loop runs through all the entries in
79834    ** the index b-tree.  */
79835    endOfLoop = sqlite3VdbeMakeLabel(v);
79836    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
79837    topOfLoop = sqlite3VdbeCurrentAddr(v);
79838    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
79839
79840    for(i=0; i<nCol; i++){
79841      CollSeq *pColl;
79842      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
79843      if( i==0 ){
79844        /* Always record the very first row */
79845        addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
79846      }
79847      assert( pIdx->azColl!=0 );
79848      assert( pIdx->azColl[i]!=0 );
79849      pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
79850      aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
79851                                      (char*)pColl, P4_COLLSEQ);
79852      sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
79853      VdbeComment((v, "jump if column %d changed", i));
79854#ifdef SQLITE_ENABLE_STAT3
79855      if( i==0 ){
79856        sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
79857        VdbeComment((v, "incr repeat count"));
79858      }
79859#endif
79860    }
79861    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
79862    for(i=0; i<nCol; i++){
79863      sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
79864      if( i==0 ){
79865        sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
79866#ifdef SQLITE_ENABLE_STAT3
79867        sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79868                          (char*)&stat3PushFuncdef, P4_FUNCDEF);
79869        sqlite3VdbeChangeP5(v, 5);
79870        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
79871        sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
79872        sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
79873        sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
79874#endif
79875      }
79876      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
79877      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
79878    }
79879    sqlite3DbFree(db, aChngAddr);
79880
79881    /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
79882    sqlite3VdbeResolveLabel(v, endOfLoop);
79883
79884    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
79885    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
79886#ifdef SQLITE_ENABLE_STAT3
79887    sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79888                      (char*)&stat3PushFuncdef, P4_FUNCDEF);
79889    sqlite3VdbeChangeP5(v, 5);
79890    sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
79891    shortJump =
79892    sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
79893    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
79894                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
79895    sqlite3VdbeChangeP5(v, 2);
79896    sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
79897    sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
79898    sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
79899    sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
79900    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
79901                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
79902    sqlite3VdbeChangeP5(v, 3);
79903    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
79904                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
79905    sqlite3VdbeChangeP5(v, 4);
79906    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
79907                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
79908    sqlite3VdbeChangeP5(v, 5);
79909    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
79910    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
79911    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
79912    sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
79913    sqlite3VdbeJumpHere(v, shortJump+2);
79914#endif
79915
79916    /* Store the results in sqlite_stat1.
79917    **
79918    ** The result is a single row of the sqlite_stat1 table.  The first
79919    ** two columns are the names of the table and index.  The third column
79920    ** is a string composed of a list of integer statistics about the
79921    ** index.  The first integer in the list is the total number of entries
79922    ** in the index.  There is one additional integer in the list for each
79923    ** column of the table.  This additional integer is a guess of how many
79924    ** rows of the table the index will select.  If D is the count of distinct
79925    ** values and K is the total number of rows, then the integer is computed
79926    ** as:
79927    **
79928    **        I = (K+D-1)/D
79929    **
79930    ** If K==0 then no entry is made into the sqlite_stat1 table.
79931    ** If K>0 then it is always the case the D>0 so division by zero
79932    ** is never possible.
79933    */
79934    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
79935    if( jZeroRows<0 ){
79936      jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
79937    }
79938    for(i=0; i<nCol; i++){
79939      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
79940      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79941      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
79942      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
79943      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
79944      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
79945      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79946    }
79947    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79948    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79949    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79950    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79951  }
79952
79953  /* If the table has no indices, create a single sqlite_stat1 entry
79954  ** containing NULL as the index name and the row count as the content.
79955  */
79956  if( pTab->pIndex==0 ){
79957    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
79958    VdbeComment((v, "%s", pTab->zName));
79959    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
79960    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
79961    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
79962  }else{
79963    sqlite3VdbeJumpHere(v, jZeroRows);
79964    jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
79965  }
79966  sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
79967  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79968  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79969  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79970  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79971  if( pParse->nMem<regRec ) pParse->nMem = regRec;
79972  sqlite3VdbeJumpHere(v, jZeroRows);
79973}
79974
79975
79976/*
79977** Generate code that will cause the most recent index analysis to
79978** be loaded into internal hash tables where is can be used.
79979*/
79980static void loadAnalysis(Parse *pParse, int iDb){
79981  Vdbe *v = sqlite3GetVdbe(pParse);
79982  if( v ){
79983    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
79984  }
79985}
79986
79987/*
79988** Generate code that will do an analysis of an entire database
79989*/
79990static void analyzeDatabase(Parse *pParse, int iDb){
79991  sqlite3 *db = pParse->db;
79992  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
79993  HashElem *k;
79994  int iStatCur;
79995  int iMem;
79996
79997  sqlite3BeginWriteOperation(pParse, 0, iDb);
79998  iStatCur = pParse->nTab;
79999  pParse->nTab += 3;
80000  openStatTable(pParse, iDb, iStatCur, 0, 0);
80001  iMem = pParse->nMem+1;
80002  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80003  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
80004    Table *pTab = (Table*)sqliteHashData(k);
80005    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
80006  }
80007  loadAnalysis(pParse, iDb);
80008}
80009
80010/*
80011** Generate code that will do an analysis of a single table in
80012** a database.  If pOnlyIdx is not NULL then it is a single index
80013** in pTab that should be analyzed.
80014*/
80015static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
80016  int iDb;
80017  int iStatCur;
80018
80019  assert( pTab!=0 );
80020  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
80021  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80022  sqlite3BeginWriteOperation(pParse, 0, iDb);
80023  iStatCur = pParse->nTab;
80024  pParse->nTab += 3;
80025  if( pOnlyIdx ){
80026    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
80027  }else{
80028    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
80029  }
80030  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
80031  loadAnalysis(pParse, iDb);
80032}
80033
80034/*
80035** Generate code for the ANALYZE command.  The parser calls this routine
80036** when it recognizes an ANALYZE command.
80037**
80038**        ANALYZE                            -- 1
80039**        ANALYZE  <database>                -- 2
80040**        ANALYZE  ?<database>.?<tablename>  -- 3
80041**
80042** Form 1 causes all indices in all attached databases to be analyzed.
80043** Form 2 analyzes all indices the single database named.
80044** Form 3 analyzes all indices associated with the named table.
80045*/
80046SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
80047  sqlite3 *db = pParse->db;
80048  int iDb;
80049  int i;
80050  char *z, *zDb;
80051  Table *pTab;
80052  Index *pIdx;
80053  Token *pTableName;
80054
80055  /* Read the database schema. If an error occurs, leave an error message
80056  ** and code in pParse and return NULL. */
80057  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
80058  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
80059    return;
80060  }
80061
80062  assert( pName2!=0 || pName1==0 );
80063  if( pName1==0 ){
80064    /* Form 1:  Analyze everything */
80065    for(i=0; i<db->nDb; i++){
80066      if( i==1 ) continue;  /* Do not analyze the TEMP database */
80067      analyzeDatabase(pParse, i);
80068    }
80069  }else if( pName2->n==0 ){
80070    /* Form 2:  Analyze the database or table named */
80071    iDb = sqlite3FindDb(db, pName1);
80072    if( iDb>=0 ){
80073      analyzeDatabase(pParse, iDb);
80074    }else{
80075      z = sqlite3NameFromToken(db, pName1);
80076      if( z ){
80077        if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
80078          analyzeTable(pParse, pIdx->pTable, pIdx);
80079        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
80080          analyzeTable(pParse, pTab, 0);
80081        }
80082        sqlite3DbFree(db, z);
80083      }
80084    }
80085  }else{
80086    /* Form 3: Analyze the fully qualified table name */
80087    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
80088    if( iDb>=0 ){
80089      zDb = db->aDb[iDb].zName;
80090      z = sqlite3NameFromToken(db, pTableName);
80091      if( z ){
80092        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
80093          analyzeTable(pParse, pIdx->pTable, pIdx);
80094        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
80095          analyzeTable(pParse, pTab, 0);
80096        }
80097        sqlite3DbFree(db, z);
80098      }
80099    }
80100  }
80101}
80102
80103/*
80104** Used to pass information from the analyzer reader through to the
80105** callback routine.
80106*/
80107typedef struct analysisInfo analysisInfo;
80108struct analysisInfo {
80109  sqlite3 *db;
80110  const char *zDatabase;
80111};
80112
80113/*
80114** This callback is invoked once for each index when reading the
80115** sqlite_stat1 table.
80116**
80117**     argv[0] = name of the table
80118**     argv[1] = name of the index (might be NULL)
80119**     argv[2] = results of analysis - on integer for each column
80120**
80121** Entries for which argv[1]==NULL simply record the number of rows in
80122** the table.
80123*/
80124static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
80125  analysisInfo *pInfo = (analysisInfo*)pData;
80126  Index *pIndex;
80127  Table *pTable;
80128  int i, c, n;
80129  tRowcnt v;
80130  const char *z;
80131
80132  assert( argc==3 );
80133  UNUSED_PARAMETER2(NotUsed, argc);
80134
80135  if( argv==0 || argv[0]==0 || argv[2]==0 ){
80136    return 0;
80137  }
80138  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
80139  if( pTable==0 ){
80140    return 0;
80141  }
80142  if( argv[1] ){
80143    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
80144  }else{
80145    pIndex = 0;
80146  }
80147  n = pIndex ? pIndex->nColumn : 0;
80148  z = argv[2];
80149  for(i=0; *z && i<=n; i++){
80150    v = 0;
80151    while( (c=z[0])>='0' && c<='9' ){
80152      v = v*10 + c - '0';
80153      z++;
80154    }
80155    if( i==0 ) pTable->nRowEst = v;
80156    if( pIndex==0 ) break;
80157    pIndex->aiRowEst[i] = v;
80158    if( *z==' ' ) z++;
80159    if( memcmp(z, "unordered", 10)==0 ){
80160      pIndex->bUnordered = 1;
80161      break;
80162    }
80163  }
80164  return 0;
80165}
80166
80167/*
80168** If the Index.aSample variable is not NULL, delete the aSample[] array
80169** and its contents.
80170*/
80171SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
80172#ifdef SQLITE_ENABLE_STAT3
80173  if( pIdx->aSample ){
80174    int j;
80175    for(j=0; j<pIdx->nSample; j++){
80176      IndexSample *p = &pIdx->aSample[j];
80177      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
80178        sqlite3DbFree(db, p->u.z);
80179      }
80180    }
80181    sqlite3DbFree(db, pIdx->aSample);
80182  }
80183  if( db && db->pnBytesFreed==0 ){
80184    pIdx->nSample = 0;
80185    pIdx->aSample = 0;
80186  }
80187#else
80188  UNUSED_PARAMETER(db);
80189  UNUSED_PARAMETER(pIdx);
80190#endif
80191}
80192
80193#ifdef SQLITE_ENABLE_STAT3
80194/*
80195** Load content from the sqlite_stat3 table into the Index.aSample[]
80196** arrays of all indices.
80197*/
80198static int loadStat3(sqlite3 *db, const char *zDb){
80199  int rc;                       /* Result codes from subroutines */
80200  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
80201  char *zSql;                   /* Text of the SQL statement */
80202  Index *pPrevIdx = 0;          /* Previous index in the loop */
80203  int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
80204  int eType;                    /* Datatype of a sample */
80205  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
80206
80207  assert( db->lookaside.bEnabled==0 );
80208  if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
80209    return SQLITE_OK;
80210  }
80211
80212  zSql = sqlite3MPrintf(db,
80213      "SELECT idx,count(*) FROM %Q.sqlite_stat3"
80214      " GROUP BY idx", zDb);
80215  if( !zSql ){
80216    return SQLITE_NOMEM;
80217  }
80218  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
80219  sqlite3DbFree(db, zSql);
80220  if( rc ) return rc;
80221
80222  while( sqlite3_step(pStmt)==SQLITE_ROW ){
80223    char *zIndex;   /* Index name */
80224    Index *pIdx;    /* Pointer to the index object */
80225    int nSample;    /* Number of samples */
80226
80227    zIndex = (char *)sqlite3_column_text(pStmt, 0);
80228    if( zIndex==0 ) continue;
80229    nSample = sqlite3_column_int(pStmt, 1);
80230    pIdx = sqlite3FindIndex(db, zIndex, zDb);
80231    if( pIdx==0 ) continue;
80232    assert( pIdx->nSample==0 );
80233    pIdx->nSample = nSample;
80234    pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
80235    pIdx->avgEq = pIdx->aiRowEst[1];
80236    if( pIdx->aSample==0 ){
80237      db->mallocFailed = 1;
80238      sqlite3_finalize(pStmt);
80239      return SQLITE_NOMEM;
80240    }
80241  }
80242  rc = sqlite3_finalize(pStmt);
80243  if( rc ) return rc;
80244
80245  zSql = sqlite3MPrintf(db,
80246      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
80247  if( !zSql ){
80248    return SQLITE_NOMEM;
80249  }
80250  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
80251  sqlite3DbFree(db, zSql);
80252  if( rc ) return rc;
80253
80254  while( sqlite3_step(pStmt)==SQLITE_ROW ){
80255    char *zIndex;   /* Index name */
80256    Index *pIdx;    /* Pointer to the index object */
80257    int i;          /* Loop counter */
80258    tRowcnt sumEq;  /* Sum of the nEq values */
80259
80260    zIndex = (char *)sqlite3_column_text(pStmt, 0);
80261    if( zIndex==0 ) continue;
80262    pIdx = sqlite3FindIndex(db, zIndex, zDb);
80263    if( pIdx==0 ) continue;
80264    if( pIdx==pPrevIdx ){
80265      idx++;
80266    }else{
80267      pPrevIdx = pIdx;
80268      idx = 0;
80269    }
80270    assert( idx<pIdx->nSample );
80271    pSample = &pIdx->aSample[idx];
80272    pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
80273    pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
80274    pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
80275    if( idx==pIdx->nSample-1 ){
80276      if( pSample->nDLt>0 ){
80277        for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
80278        pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
80279      }
80280      if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
80281    }
80282    eType = sqlite3_column_type(pStmt, 4);
80283    pSample->eType = (u8)eType;
80284    switch( eType ){
80285      case SQLITE_INTEGER: {
80286        pSample->u.i = sqlite3_column_int64(pStmt, 4);
80287        break;
80288      }
80289      case SQLITE_FLOAT: {
80290        pSample->u.r = sqlite3_column_double(pStmt, 4);
80291        break;
80292      }
80293      case SQLITE_NULL: {
80294        break;
80295      }
80296      default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
80297        const char *z = (const char *)(
80298              (eType==SQLITE_BLOB) ?
80299              sqlite3_column_blob(pStmt, 4):
80300              sqlite3_column_text(pStmt, 4)
80301           );
80302        int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
80303        pSample->nByte = n;
80304        if( n < 1){
80305          pSample->u.z = 0;
80306        }else{
80307          pSample->u.z = sqlite3DbMallocRaw(db, n);
80308          if( pSample->u.z==0 ){
80309            db->mallocFailed = 1;
80310            sqlite3_finalize(pStmt);
80311            return SQLITE_NOMEM;
80312          }
80313          memcpy(pSample->u.z, z, n);
80314        }
80315      }
80316    }
80317  }
80318  return sqlite3_finalize(pStmt);
80319}
80320#endif /* SQLITE_ENABLE_STAT3 */
80321
80322/*
80323** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
80324** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
80325** arrays. The contents of sqlite_stat3 are used to populate the
80326** Index.aSample[] arrays.
80327**
80328** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
80329** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined
80330** during compilation and the sqlite_stat3 table is present, no data is
80331** read from it.
80332**
80333** If SQLITE_ENABLE_STAT3 was defined during compilation and the
80334** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
80335** returned. However, in this case, data is read from the sqlite_stat1
80336** table (if it is present) before returning.
80337**
80338** If an OOM error occurs, this function always sets db->mallocFailed.
80339** This means if the caller does not care about other errors, the return
80340** code may be ignored.
80341*/
80342SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
80343  analysisInfo sInfo;
80344  HashElem *i;
80345  char *zSql;
80346  int rc;
80347
80348  assert( iDb>=0 && iDb<db->nDb );
80349  assert( db->aDb[iDb].pBt!=0 );
80350
80351  /* Clear any prior statistics */
80352  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80353  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
80354    Index *pIdx = sqliteHashData(i);
80355    sqlite3DefaultRowEst(pIdx);
80356#ifdef SQLITE_ENABLE_STAT3
80357    sqlite3DeleteIndexSamples(db, pIdx);
80358    pIdx->aSample = 0;
80359#endif
80360  }
80361
80362  /* Check to make sure the sqlite_stat1 table exists */
80363  sInfo.db = db;
80364  sInfo.zDatabase = db->aDb[iDb].zName;
80365  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
80366    return SQLITE_ERROR;
80367  }
80368
80369  /* Load new statistics out of the sqlite_stat1 table */
80370  zSql = sqlite3MPrintf(db,
80371      "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
80372  if( zSql==0 ){
80373    rc = SQLITE_NOMEM;
80374  }else{
80375    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
80376    sqlite3DbFree(db, zSql);
80377  }
80378
80379
80380  /* Load the statistics from the sqlite_stat3 table. */
80381#ifdef SQLITE_ENABLE_STAT3
80382  if( rc==SQLITE_OK ){
80383    int lookasideEnabled = db->lookaside.bEnabled;
80384    db->lookaside.bEnabled = 0;
80385    rc = loadStat3(db, sInfo.zDatabase);
80386    db->lookaside.bEnabled = lookasideEnabled;
80387  }
80388#endif
80389
80390  if( rc==SQLITE_NOMEM ){
80391    db->mallocFailed = 1;
80392  }
80393  return rc;
80394}
80395
80396
80397#endif /* SQLITE_OMIT_ANALYZE */
80398
80399/************** End of analyze.c *********************************************/
80400/************** Begin file attach.c ******************************************/
80401/*
80402** 2003 April 6
80403**
80404** The author disclaims copyright to this source code.  In place of
80405** a legal notice, here is a blessing:
80406**
80407**    May you do good and not evil.
80408**    May you find forgiveness for yourself and forgive others.
80409**    May you share freely, never taking more than you give.
80410**
80411*************************************************************************
80412** This file contains code used to implement the ATTACH and DETACH commands.
80413*/
80414
80415#ifndef SQLITE_OMIT_ATTACH
80416/*
80417** Resolve an expression that was part of an ATTACH or DETACH statement. This
80418** is slightly different from resolving a normal SQL expression, because simple
80419** identifiers are treated as strings, not possible column names or aliases.
80420**
80421** i.e. if the parser sees:
80422**
80423**     ATTACH DATABASE abc AS def
80424**
80425** it treats the two expressions as literal strings 'abc' and 'def' instead of
80426** looking for columns of the same name.
80427**
80428** This only applies to the root node of pExpr, so the statement:
80429**
80430**     ATTACH DATABASE abc||def AS 'db2'
80431**
80432** will fail because neither abc or def can be resolved.
80433*/
80434static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
80435{
80436  int rc = SQLITE_OK;
80437  if( pExpr ){
80438    if( pExpr->op!=TK_ID ){
80439      rc = sqlite3ResolveExprNames(pName, pExpr);
80440      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
80441        sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
80442        return SQLITE_ERROR;
80443      }
80444    }else{
80445      pExpr->op = TK_STRING;
80446    }
80447  }
80448  return rc;
80449}
80450
80451/*
80452** An SQL user-function registered to do the work of an ATTACH statement. The
80453** three arguments to the function come directly from an attach statement:
80454**
80455**     ATTACH DATABASE x AS y KEY z
80456**
80457**     SELECT sqlite_attach(x, y, z)
80458**
80459** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
80460** third argument.
80461*/
80462static void attachFunc(
80463  sqlite3_context *context,
80464  int NotUsed,
80465  sqlite3_value **argv
80466){
80467  int i;
80468  int rc = 0;
80469  sqlite3 *db = sqlite3_context_db_handle(context);
80470  const char *zName;
80471  const char *zFile;
80472  char *zPath = 0;
80473  char *zErr = 0;
80474  unsigned int flags;
80475  Db *aNew;
80476  char *zErrDyn = 0;
80477  sqlite3_vfs *pVfs;
80478
80479  UNUSED_PARAMETER(NotUsed);
80480
80481  zFile = (const char *)sqlite3_value_text(argv[0]);
80482  zName = (const char *)sqlite3_value_text(argv[1]);
80483  if( zFile==0 ) zFile = "";
80484  if( zName==0 ) zName = "";
80485
80486  /* Check for the following errors:
80487  **
80488  **     * Too many attached databases,
80489  **     * Transaction currently open
80490  **     * Specified database name already being used.
80491  */
80492  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
80493    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
80494      db->aLimit[SQLITE_LIMIT_ATTACHED]
80495    );
80496    goto attach_error;
80497  }
80498  if( !db->autoCommit ){
80499    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
80500    goto attach_error;
80501  }
80502  for(i=0; i<db->nDb; i++){
80503    char *z = db->aDb[i].zName;
80504    assert( z && zName );
80505    if( sqlite3StrICmp(z, zName)==0 ){
80506      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
80507      goto attach_error;
80508    }
80509  }
80510
80511  /* Allocate the new entry in the db->aDb[] array and initialise the schema
80512  ** hash tables.
80513  */
80514  if( db->aDb==db->aDbStatic ){
80515    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
80516    if( aNew==0 ) return;
80517    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
80518  }else{
80519    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
80520    if( aNew==0 ) return;
80521  }
80522  db->aDb = aNew;
80523  aNew = &db->aDb[db->nDb];
80524  memset(aNew, 0, sizeof(*aNew));
80525
80526  /* Open the database file. If the btree is successfully opened, use
80527  ** it to obtain the database schema. At this point the schema may
80528  ** or may not be initialised.
80529  */
80530  flags = db->openFlags;
80531  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
80532  if( rc!=SQLITE_OK ){
80533    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
80534    sqlite3_result_error(context, zErr, -1);
80535    sqlite3_free(zErr);
80536    return;
80537  }
80538  assert( pVfs );
80539  flags |= SQLITE_OPEN_MAIN_DB;
80540  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
80541  sqlite3_free( zPath );
80542  db->nDb++;
80543  if( rc==SQLITE_CONSTRAINT ){
80544    rc = SQLITE_ERROR;
80545    zErrDyn = sqlite3MPrintf(db, "database is already attached");
80546  }else if( rc==SQLITE_OK ){
80547    Pager *pPager;
80548    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
80549    if( !aNew->pSchema ){
80550      rc = SQLITE_NOMEM;
80551    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
80552      zErrDyn = sqlite3MPrintf(db,
80553        "attached databases must use the same text encoding as main database");
80554      rc = SQLITE_ERROR;
80555    }
80556    pPager = sqlite3BtreePager(aNew->pBt);
80557    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
80558    sqlite3BtreeSecureDelete(aNew->pBt,
80559                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
80560  }
80561  aNew->safety_level = 3;
80562  aNew->zName = sqlite3DbStrDup(db, zName);
80563  if( rc==SQLITE_OK && aNew->zName==0 ){
80564    rc = SQLITE_NOMEM;
80565  }
80566
80567
80568#ifdef SQLITE_HAS_CODEC
80569  if( rc==SQLITE_OK ){
80570    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
80571    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
80572    int nKey;
80573    char *zKey;
80574    int t = sqlite3_value_type(argv[2]);
80575    switch( t ){
80576      case SQLITE_INTEGER:
80577      case SQLITE_FLOAT:
80578        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
80579        rc = SQLITE_ERROR;
80580        break;
80581
80582      case SQLITE_TEXT:
80583      case SQLITE_BLOB:
80584        nKey = sqlite3_value_bytes(argv[2]);
80585        zKey = (char *)sqlite3_value_blob(argv[2]);
80586        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
80587        break;
80588
80589      case SQLITE_NULL:
80590        /* No key specified.  Use the key from the main database */
80591        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
80592        if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
80593          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
80594        }
80595        break;
80596    }
80597  }
80598#endif
80599
80600  /* If the file was opened successfully, read the schema for the new database.
80601  ** If this fails, or if opening the file failed, then close the file and
80602  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
80603  ** we found it.
80604  */
80605  if( rc==SQLITE_OK ){
80606    sqlite3BtreeEnterAll(db);
80607    rc = sqlite3Init(db, &zErrDyn);
80608    sqlite3BtreeLeaveAll(db);
80609  }
80610  if( rc ){
80611    int iDb = db->nDb - 1;
80612    assert( iDb>=2 );
80613    if( db->aDb[iDb].pBt ){
80614      sqlite3BtreeClose(db->aDb[iDb].pBt);
80615      db->aDb[iDb].pBt = 0;
80616      db->aDb[iDb].pSchema = 0;
80617    }
80618    sqlite3ResetInternalSchema(db, -1);
80619    db->nDb = iDb;
80620    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
80621      db->mallocFailed = 1;
80622      sqlite3DbFree(db, zErrDyn);
80623      zErrDyn = sqlite3MPrintf(db, "out of memory");
80624    }else if( zErrDyn==0 ){
80625      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
80626    }
80627    goto attach_error;
80628  }
80629
80630  return;
80631
80632attach_error:
80633  /* Return an error if we get here */
80634  if( zErrDyn ){
80635    sqlite3_result_error(context, zErrDyn, -1);
80636    sqlite3DbFree(db, zErrDyn);
80637  }
80638  if( rc ) sqlite3_result_error_code(context, rc);
80639}
80640
80641/*
80642** An SQL user-function registered to do the work of an DETACH statement. The
80643** three arguments to the function come directly from a detach statement:
80644**
80645**     DETACH DATABASE x
80646**
80647**     SELECT sqlite_detach(x)
80648*/
80649static void detachFunc(
80650  sqlite3_context *context,
80651  int NotUsed,
80652  sqlite3_value **argv
80653){
80654  const char *zName = (const char *)sqlite3_value_text(argv[0]);
80655  sqlite3 *db = sqlite3_context_db_handle(context);
80656  int i;
80657  Db *pDb = 0;
80658  char zErr[128];
80659
80660  UNUSED_PARAMETER(NotUsed);
80661
80662  if( zName==0 ) zName = "";
80663  for(i=0; i<db->nDb; i++){
80664    pDb = &db->aDb[i];
80665    if( pDb->pBt==0 ) continue;
80666    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
80667  }
80668
80669  if( i>=db->nDb ){
80670    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
80671    goto detach_error;
80672  }
80673  if( i<2 ){
80674    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
80675    goto detach_error;
80676  }
80677  if( !db->autoCommit ){
80678    sqlite3_snprintf(sizeof(zErr), zErr,
80679                     "cannot DETACH database within transaction");
80680    goto detach_error;
80681  }
80682  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
80683    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
80684    goto detach_error;
80685  }
80686
80687  sqlite3BtreeClose(pDb->pBt);
80688  pDb->pBt = 0;
80689  pDb->pSchema = 0;
80690  sqlite3ResetInternalSchema(db, -1);
80691  return;
80692
80693detach_error:
80694  sqlite3_result_error(context, zErr, -1);
80695}
80696
80697/*
80698** This procedure generates VDBE code for a single invocation of either the
80699** sqlite_detach() or sqlite_attach() SQL user functions.
80700*/
80701static void codeAttach(
80702  Parse *pParse,       /* The parser context */
80703  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
80704  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
80705  Expr *pAuthArg,      /* Expression to pass to authorization callback */
80706  Expr *pFilename,     /* Name of database file */
80707  Expr *pDbname,       /* Name of the database to use internally */
80708  Expr *pKey           /* Database key for encryption extension */
80709){
80710  int rc;
80711  NameContext sName;
80712  Vdbe *v;
80713  sqlite3* db = pParse->db;
80714  int regArgs;
80715
80716  memset(&sName, 0, sizeof(NameContext));
80717  sName.pParse = pParse;
80718
80719  if(
80720      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
80721      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
80722      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
80723  ){
80724    pParse->nErr++;
80725    goto attach_end;
80726  }
80727
80728#ifndef SQLITE_OMIT_AUTHORIZATION
80729  if( pAuthArg ){
80730    char *zAuthArg;
80731    if( pAuthArg->op==TK_STRING ){
80732      zAuthArg = pAuthArg->u.zToken;
80733    }else{
80734      zAuthArg = 0;
80735    }
80736    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
80737    if(rc!=SQLITE_OK ){
80738      goto attach_end;
80739    }
80740  }
80741#endif /* SQLITE_OMIT_AUTHORIZATION */
80742
80743
80744  v = sqlite3GetVdbe(pParse);
80745  regArgs = sqlite3GetTempRange(pParse, 4);
80746  sqlite3ExprCode(pParse, pFilename, regArgs);
80747  sqlite3ExprCode(pParse, pDbname, regArgs+1);
80748  sqlite3ExprCode(pParse, pKey, regArgs+2);
80749
80750  assert( v || db->mallocFailed );
80751  if( v ){
80752    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
80753    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
80754    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
80755    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
80756
80757    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
80758    ** statement only). For DETACH, set it to false (expire all existing
80759    ** statements).
80760    */
80761    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
80762  }
80763
80764attach_end:
80765  sqlite3ExprDelete(db, pFilename);
80766  sqlite3ExprDelete(db, pDbname);
80767  sqlite3ExprDelete(db, pKey);
80768}
80769
80770/*
80771** Called by the parser to compile a DETACH statement.
80772**
80773**     DETACH pDbname
80774*/
80775SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
80776  static const FuncDef detach_func = {
80777    1,                /* nArg */
80778    SQLITE_UTF8,      /* iPrefEnc */
80779    0,                /* flags */
80780    0,                /* pUserData */
80781    0,                /* pNext */
80782    detachFunc,       /* xFunc */
80783    0,                /* xStep */
80784    0,                /* xFinalize */
80785    "sqlite_detach",  /* zName */
80786    0,                /* pHash */
80787    0                 /* pDestructor */
80788  };
80789  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
80790}
80791
80792/*
80793** Called by the parser to compile an ATTACH statement.
80794**
80795**     ATTACH p AS pDbname KEY pKey
80796*/
80797SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
80798  static const FuncDef attach_func = {
80799    3,                /* nArg */
80800    SQLITE_UTF8,      /* iPrefEnc */
80801    0,                /* flags */
80802    0,                /* pUserData */
80803    0,                /* pNext */
80804    attachFunc,       /* xFunc */
80805    0,                /* xStep */
80806    0,                /* xFinalize */
80807    "sqlite_attach",  /* zName */
80808    0,                /* pHash */
80809    0                 /* pDestructor */
80810  };
80811  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
80812}
80813#endif /* SQLITE_OMIT_ATTACH */
80814
80815/*
80816** Initialize a DbFixer structure.  This routine must be called prior
80817** to passing the structure to one of the sqliteFixAAAA() routines below.
80818**
80819** The return value indicates whether or not fixation is required.  TRUE
80820** means we do need to fix the database references, FALSE means we do not.
80821*/
80822SQLITE_PRIVATE int sqlite3FixInit(
80823  DbFixer *pFix,      /* The fixer to be initialized */
80824  Parse *pParse,      /* Error messages will be written here */
80825  int iDb,            /* This is the database that must be used */
80826  const char *zType,  /* "view", "trigger", or "index" */
80827  const Token *pName  /* Name of the view, trigger, or index */
80828){
80829  sqlite3 *db;
80830
80831  if( NEVER(iDb<0) || iDb==1 ) return 0;
80832  db = pParse->db;
80833  assert( db->nDb>iDb );
80834  pFix->pParse = pParse;
80835  pFix->zDb = db->aDb[iDb].zName;
80836  pFix->zType = zType;
80837  pFix->pName = pName;
80838  return 1;
80839}
80840
80841/*
80842** The following set of routines walk through the parse tree and assign
80843** a specific database to all table references where the database name
80844** was left unspecified in the original SQL statement.  The pFix structure
80845** must have been initialized by a prior call to sqlite3FixInit().
80846**
80847** These routines are used to make sure that an index, trigger, or
80848** view in one database does not refer to objects in a different database.
80849** (Exception: indices, triggers, and views in the TEMP database are
80850** allowed to refer to anything.)  If a reference is explicitly made
80851** to an object in a different database, an error message is added to
80852** pParse->zErrMsg and these routines return non-zero.  If everything
80853** checks out, these routines return 0.
80854*/
80855SQLITE_PRIVATE int sqlite3FixSrcList(
80856  DbFixer *pFix,       /* Context of the fixation */
80857  SrcList *pList       /* The Source list to check and modify */
80858){
80859  int i;
80860  const char *zDb;
80861  struct SrcList_item *pItem;
80862
80863  if( NEVER(pList==0) ) return 0;
80864  zDb = pFix->zDb;
80865  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
80866    if( pItem->zDatabase==0 ){
80867      pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
80868    }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
80869      sqlite3ErrorMsg(pFix->pParse,
80870         "%s %T cannot reference objects in database %s",
80871         pFix->zType, pFix->pName, pItem->zDatabase);
80872      return 1;
80873    }
80874#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
80875    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
80876    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
80877#endif
80878  }
80879  return 0;
80880}
80881#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
80882SQLITE_PRIVATE int sqlite3FixSelect(
80883  DbFixer *pFix,       /* Context of the fixation */
80884  Select *pSelect      /* The SELECT statement to be fixed to one database */
80885){
80886  while( pSelect ){
80887    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
80888      return 1;
80889    }
80890    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
80891      return 1;
80892    }
80893    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
80894      return 1;
80895    }
80896    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
80897      return 1;
80898    }
80899    pSelect = pSelect->pPrior;
80900  }
80901  return 0;
80902}
80903SQLITE_PRIVATE int sqlite3FixExpr(
80904  DbFixer *pFix,     /* Context of the fixation */
80905  Expr *pExpr        /* The expression to be fixed to one database */
80906){
80907  while( pExpr ){
80908    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
80909    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80910      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
80911    }else{
80912      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
80913    }
80914    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
80915      return 1;
80916    }
80917    pExpr = pExpr->pLeft;
80918  }
80919  return 0;
80920}
80921SQLITE_PRIVATE int sqlite3FixExprList(
80922  DbFixer *pFix,     /* Context of the fixation */
80923  ExprList *pList    /* The expression to be fixed to one database */
80924){
80925  int i;
80926  struct ExprList_item *pItem;
80927  if( pList==0 ) return 0;
80928  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
80929    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
80930      return 1;
80931    }
80932  }
80933  return 0;
80934}
80935#endif
80936
80937#ifndef SQLITE_OMIT_TRIGGER
80938SQLITE_PRIVATE int sqlite3FixTriggerStep(
80939  DbFixer *pFix,     /* Context of the fixation */
80940  TriggerStep *pStep /* The trigger step be fixed to one database */
80941){
80942  while( pStep ){
80943    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
80944      return 1;
80945    }
80946    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
80947      return 1;
80948    }
80949    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
80950      return 1;
80951    }
80952    pStep = pStep->pNext;
80953  }
80954  return 0;
80955}
80956#endif
80957
80958/************** End of attach.c **********************************************/
80959/************** Begin file auth.c ********************************************/
80960/*
80961** 2003 January 11
80962**
80963** The author disclaims copyright to this source code.  In place of
80964** a legal notice, here is a blessing:
80965**
80966**    May you do good and not evil.
80967**    May you find forgiveness for yourself and forgive others.
80968**    May you share freely, never taking more than you give.
80969**
80970*************************************************************************
80971** This file contains code used to implement the sqlite3_set_authorizer()
80972** API.  This facility is an optional feature of the library.  Embedded
80973** systems that do not need this facility may omit it by recompiling
80974** the library with -DSQLITE_OMIT_AUTHORIZATION=1
80975*/
80976
80977/*
80978** All of the code in this file may be omitted by defining a single
80979** macro.
80980*/
80981#ifndef SQLITE_OMIT_AUTHORIZATION
80982
80983/*
80984** Set or clear the access authorization function.
80985**
80986** The access authorization function is be called during the compilation
80987** phase to verify that the user has read and/or write access permission on
80988** various fields of the database.  The first argument to the auth function
80989** is a copy of the 3rd argument to this routine.  The second argument
80990** to the auth function is one of these constants:
80991**
80992**       SQLITE_CREATE_INDEX
80993**       SQLITE_CREATE_TABLE
80994**       SQLITE_CREATE_TEMP_INDEX
80995**       SQLITE_CREATE_TEMP_TABLE
80996**       SQLITE_CREATE_TEMP_TRIGGER
80997**       SQLITE_CREATE_TEMP_VIEW
80998**       SQLITE_CREATE_TRIGGER
80999**       SQLITE_CREATE_VIEW
81000**       SQLITE_DELETE
81001**       SQLITE_DROP_INDEX
81002**       SQLITE_DROP_TABLE
81003**       SQLITE_DROP_TEMP_INDEX
81004**       SQLITE_DROP_TEMP_TABLE
81005**       SQLITE_DROP_TEMP_TRIGGER
81006**       SQLITE_DROP_TEMP_VIEW
81007**       SQLITE_DROP_TRIGGER
81008**       SQLITE_DROP_VIEW
81009**       SQLITE_INSERT
81010**       SQLITE_PRAGMA
81011**       SQLITE_READ
81012**       SQLITE_SELECT
81013**       SQLITE_TRANSACTION
81014**       SQLITE_UPDATE
81015**
81016** The third and fourth arguments to the auth function are the name of
81017** the table and the column that are being accessed.  The auth function
81018** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
81019** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
81020** means that the SQL statement will never-run - the sqlite3_exec() call
81021** will return with an error.  SQLITE_IGNORE means that the SQL statement
81022** should run but attempts to read the specified column will return NULL
81023** and attempts to write the column will be ignored.
81024**
81025** Setting the auth function to NULL disables this hook.  The default
81026** setting of the auth function is NULL.
81027*/
81028SQLITE_API int sqlite3_set_authorizer(
81029  sqlite3 *db,
81030  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
81031  void *pArg
81032){
81033  sqlite3_mutex_enter(db->mutex);
81034  db->xAuth = xAuth;
81035  db->pAuthArg = pArg;
81036  sqlite3ExpirePreparedStatements(db);
81037  sqlite3_mutex_leave(db->mutex);
81038  return SQLITE_OK;
81039}
81040
81041/*
81042** Write an error message into pParse->zErrMsg that explains that the
81043** user-supplied authorization function returned an illegal value.
81044*/
81045static void sqliteAuthBadReturnCode(Parse *pParse){
81046  sqlite3ErrorMsg(pParse, "authorizer malfunction");
81047  pParse->rc = SQLITE_ERROR;
81048}
81049
81050/*
81051** Invoke the authorization callback for permission to read column zCol from
81052** table zTab in database zDb. This function assumes that an authorization
81053** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
81054**
81055** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
81056** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
81057** is treated as SQLITE_DENY. In this case an error is left in pParse.
81058*/
81059SQLITE_PRIVATE int sqlite3AuthReadCol(
81060  Parse *pParse,                  /* The parser context */
81061  const char *zTab,               /* Table name */
81062  const char *zCol,               /* Column name */
81063  int iDb                         /* Index of containing database. */
81064){
81065  sqlite3 *db = pParse->db;       /* Database handle */
81066  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
81067  int rc;                         /* Auth callback return code */
81068
81069  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
81070  if( rc==SQLITE_DENY ){
81071    if( db->nDb>2 || iDb!=0 ){
81072      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
81073    }else{
81074      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
81075    }
81076    pParse->rc = SQLITE_AUTH;
81077  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
81078    sqliteAuthBadReturnCode(pParse);
81079  }
81080  return rc;
81081}
81082
81083/*
81084** The pExpr should be a TK_COLUMN expression.  The table referred to
81085** is in pTabList or else it is the NEW or OLD table of a trigger.
81086** Check to see if it is OK to read this particular column.
81087**
81088** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
81089** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
81090** then generate an error.
81091*/
81092SQLITE_PRIVATE void sqlite3AuthRead(
81093  Parse *pParse,        /* The parser context */
81094  Expr *pExpr,          /* The expression to check authorization on */
81095  Schema *pSchema,      /* The schema of the expression */
81096  SrcList *pTabList     /* All table that pExpr might refer to */
81097){
81098  sqlite3 *db = pParse->db;
81099  Table *pTab = 0;      /* The table being read */
81100  const char *zCol;     /* Name of the column of the table */
81101  int iSrc;             /* Index in pTabList->a[] of table being read */
81102  int iDb;              /* The index of the database the expression refers to */
81103  int iCol;             /* Index of column in table */
81104
81105  if( db->xAuth==0 ) return;
81106  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
81107  if( iDb<0 ){
81108    /* An attempt to read a column out of a subquery or other
81109    ** temporary table. */
81110    return;
81111  }
81112
81113  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
81114  if( pExpr->op==TK_TRIGGER ){
81115    pTab = pParse->pTriggerTab;
81116  }else{
81117    assert( pTabList );
81118    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
81119      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
81120        pTab = pTabList->a[iSrc].pTab;
81121        break;
81122      }
81123    }
81124  }
81125  iCol = pExpr->iColumn;
81126  if( NEVER(pTab==0) ) return;
81127
81128  if( iCol>=0 ){
81129    assert( iCol<pTab->nCol );
81130    zCol = pTab->aCol[iCol].zName;
81131  }else if( pTab->iPKey>=0 ){
81132    assert( pTab->iPKey<pTab->nCol );
81133    zCol = pTab->aCol[pTab->iPKey].zName;
81134  }else{
81135    zCol = "ROWID";
81136  }
81137  assert( iDb>=0 && iDb<db->nDb );
81138  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
81139    pExpr->op = TK_NULL;
81140  }
81141}
81142
81143/*
81144** Do an authorization check using the code and arguments given.  Return
81145** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
81146** is returned, then the error count and error message in pParse are
81147** modified appropriately.
81148*/
81149SQLITE_PRIVATE int sqlite3AuthCheck(
81150  Parse *pParse,
81151  int code,
81152  const char *zArg1,
81153  const char *zArg2,
81154  const char *zArg3
81155){
81156  sqlite3 *db = pParse->db;
81157  int rc;
81158
81159  /* Don't do any authorization checks if the database is initialising
81160  ** or if the parser is being invoked from within sqlite3_declare_vtab.
81161  */
81162  if( db->init.busy || IN_DECLARE_VTAB ){
81163    return SQLITE_OK;
81164  }
81165
81166  if( db->xAuth==0 ){
81167    return SQLITE_OK;
81168  }
81169  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
81170  if( rc==SQLITE_DENY ){
81171    sqlite3ErrorMsg(pParse, "not authorized");
81172    pParse->rc = SQLITE_AUTH;
81173  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
81174    rc = SQLITE_DENY;
81175    sqliteAuthBadReturnCode(pParse);
81176  }
81177  return rc;
81178}
81179
81180/*
81181** Push an authorization context.  After this routine is called, the
81182** zArg3 argument to authorization callbacks will be zContext until
81183** popped.  Or if pParse==0, this routine is a no-op.
81184*/
81185SQLITE_PRIVATE void sqlite3AuthContextPush(
81186  Parse *pParse,
81187  AuthContext *pContext,
81188  const char *zContext
81189){
81190  assert( pParse );
81191  pContext->pParse = pParse;
81192  pContext->zAuthContext = pParse->zAuthContext;
81193  pParse->zAuthContext = zContext;
81194}
81195
81196/*
81197** Pop an authorization context that was previously pushed
81198** by sqlite3AuthContextPush
81199*/
81200SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
81201  if( pContext->pParse ){
81202    pContext->pParse->zAuthContext = pContext->zAuthContext;
81203    pContext->pParse = 0;
81204  }
81205}
81206
81207#endif /* SQLITE_OMIT_AUTHORIZATION */
81208
81209/************** End of auth.c ************************************************/
81210/************** Begin file build.c *******************************************/
81211/*
81212** 2001 September 15
81213**
81214** The author disclaims copyright to this source code.  In place of
81215** a legal notice, here is a blessing:
81216**
81217**    May you do good and not evil.
81218**    May you find forgiveness for yourself and forgive others.
81219**    May you share freely, never taking more than you give.
81220**
81221*************************************************************************
81222** This file contains C code routines that are called by the SQLite parser
81223** when syntax rules are reduced.  The routines in this file handle the
81224** following kinds of SQL syntax:
81225**
81226**     CREATE TABLE
81227**     DROP TABLE
81228**     CREATE INDEX
81229**     DROP INDEX
81230**     creating ID lists
81231**     BEGIN TRANSACTION
81232**     COMMIT
81233**     ROLLBACK
81234*/
81235
81236/*
81237** This routine is called when a new SQL statement is beginning to
81238** be parsed.  Initialize the pParse structure as needed.
81239*/
81240SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
81241  pParse->explain = (u8)explainFlag;
81242  pParse->nVar = 0;
81243}
81244
81245#ifndef SQLITE_OMIT_SHARED_CACHE
81246/*
81247** The TableLock structure is only used by the sqlite3TableLock() and
81248** codeTableLocks() functions.
81249*/
81250struct TableLock {
81251  int iDb;             /* The database containing the table to be locked */
81252  int iTab;            /* The root page of the table to be locked */
81253  u8 isWriteLock;      /* True for write lock.  False for a read lock */
81254  const char *zName;   /* Name of the table */
81255};
81256
81257/*
81258** Record the fact that we want to lock a table at run-time.
81259**
81260** The table to be locked has root page iTab and is found in database iDb.
81261** A read or a write lock can be taken depending on isWritelock.
81262**
81263** This routine just records the fact that the lock is desired.  The
81264** code to make the lock occur is generated by a later call to
81265** codeTableLocks() which occurs during sqlite3FinishCoding().
81266*/
81267SQLITE_PRIVATE void sqlite3TableLock(
81268  Parse *pParse,     /* Parsing context */
81269  int iDb,           /* Index of the database containing the table to lock */
81270  int iTab,          /* Root page number of the table to be locked */
81271  u8 isWriteLock,    /* True for a write lock */
81272  const char *zName  /* Name of the table to be locked */
81273){
81274  Parse *pToplevel = sqlite3ParseToplevel(pParse);
81275  int i;
81276  int nBytes;
81277  TableLock *p;
81278  assert( iDb>=0 );
81279
81280  for(i=0; i<pToplevel->nTableLock; i++){
81281    p = &pToplevel->aTableLock[i];
81282    if( p->iDb==iDb && p->iTab==iTab ){
81283      p->isWriteLock = (p->isWriteLock || isWriteLock);
81284      return;
81285    }
81286  }
81287
81288  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
81289  pToplevel->aTableLock =
81290      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
81291  if( pToplevel->aTableLock ){
81292    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
81293    p->iDb = iDb;
81294    p->iTab = iTab;
81295    p->isWriteLock = isWriteLock;
81296    p->zName = zName;
81297  }else{
81298    pToplevel->nTableLock = 0;
81299    pToplevel->db->mallocFailed = 1;
81300  }
81301}
81302
81303/*
81304** Code an OP_TableLock instruction for each table locked by the
81305** statement (configured by calls to sqlite3TableLock()).
81306*/
81307static void codeTableLocks(Parse *pParse){
81308  int i;
81309  Vdbe *pVdbe;
81310
81311  pVdbe = sqlite3GetVdbe(pParse);
81312  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
81313
81314  for(i=0; i<pParse->nTableLock; i++){
81315    TableLock *p = &pParse->aTableLock[i];
81316    int p1 = p->iDb;
81317    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
81318                      p->zName, P4_STATIC);
81319  }
81320}
81321#else
81322  #define codeTableLocks(x)
81323#endif
81324
81325/*
81326** This routine is called after a single SQL statement has been
81327** parsed and a VDBE program to execute that statement has been
81328** prepared.  This routine puts the finishing touches on the
81329** VDBE program and resets the pParse structure for the next
81330** parse.
81331**
81332** Note that if an error occurred, it might be the case that
81333** no VDBE code was generated.
81334*/
81335SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
81336  sqlite3 *db;
81337  Vdbe *v;
81338
81339  db = pParse->db;
81340  if( db->mallocFailed ) return;
81341  if( pParse->nested ) return;
81342  if( pParse->nErr ) return;
81343
81344  /* Begin by generating some termination code at the end of the
81345  ** vdbe program
81346  */
81347  v = sqlite3GetVdbe(pParse);
81348  assert( !pParse->isMultiWrite
81349       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
81350  if( v ){
81351    sqlite3VdbeAddOp0(v, OP_Halt);
81352
81353    /* The cookie mask contains one bit for each database file open.
81354    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
81355    ** set for each database that is used.  Generate code to start a
81356    ** transaction on each used database and to verify the schema cookie
81357    ** on each used database.
81358    */
81359    if( pParse->cookieGoto>0 ){
81360      yDbMask mask;
81361      int iDb;
81362      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
81363      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
81364        if( (mask & pParse->cookieMask)==0 ) continue;
81365        sqlite3VdbeUsesBtree(v, iDb);
81366        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
81367        if( db->init.busy==0 ){
81368          assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81369          sqlite3VdbeAddOp3(v, OP_VerifyCookie,
81370                            iDb, pParse->cookieValue[iDb],
81371                            db->aDb[iDb].pSchema->iGeneration);
81372        }
81373      }
81374#ifndef SQLITE_OMIT_VIRTUALTABLE
81375      {
81376        int i;
81377        for(i=0; i<pParse->nVtabLock; i++){
81378          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
81379          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
81380        }
81381        pParse->nVtabLock = 0;
81382      }
81383#endif
81384
81385      /* Once all the cookies have been verified and transactions opened,
81386      ** obtain the required table-locks. This is a no-op unless the
81387      ** shared-cache feature is enabled.
81388      */
81389      codeTableLocks(pParse);
81390
81391      /* Initialize any AUTOINCREMENT data structures required.
81392      */
81393      sqlite3AutoincrementBegin(pParse);
81394
81395      /* Finally, jump back to the beginning of the executable code. */
81396      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
81397    }
81398  }
81399
81400
81401  /* Get the VDBE program ready for execution
81402  */
81403  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
81404#ifdef SQLITE_DEBUG
81405    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
81406    sqlite3VdbeTrace(v, trace);
81407#endif
81408    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
81409    /* A minimum of one cursor is required if autoincrement is used
81410    *  See ticket [a696379c1f08866] */
81411    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
81412    sqlite3VdbeMakeReady(v, pParse);
81413    pParse->rc = SQLITE_DONE;
81414    pParse->colNamesSet = 0;
81415  }else{
81416    pParse->rc = SQLITE_ERROR;
81417  }
81418  pParse->nTab = 0;
81419  pParse->nMem = 0;
81420  pParse->nSet = 0;
81421  pParse->nVar = 0;
81422  pParse->cookieMask = 0;
81423  pParse->cookieGoto = 0;
81424}
81425
81426/*
81427** Run the parser and code generator recursively in order to generate
81428** code for the SQL statement given onto the end of the pParse context
81429** currently under construction.  When the parser is run recursively
81430** this way, the final OP_Halt is not appended and other initialization
81431** and finalization steps are omitted because those are handling by the
81432** outermost parser.
81433**
81434** Not everything is nestable.  This facility is designed to permit
81435** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
81436** care if you decide to try to use this routine for some other purposes.
81437*/
81438SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
81439  va_list ap;
81440  char *zSql;
81441  char *zErrMsg = 0;
81442  sqlite3 *db = pParse->db;
81443# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
81444  char saveBuf[SAVE_SZ];
81445
81446  if( pParse->nErr ) return;
81447  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
81448  va_start(ap, zFormat);
81449  zSql = sqlite3VMPrintf(db, zFormat, ap);
81450  va_end(ap);
81451  if( zSql==0 ){
81452    return;   /* A malloc must have failed */
81453  }
81454  pParse->nested++;
81455  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
81456  memset(&pParse->nVar, 0, SAVE_SZ);
81457  sqlite3RunParser(pParse, zSql, &zErrMsg);
81458  sqlite3DbFree(db, zErrMsg);
81459  sqlite3DbFree(db, zSql);
81460  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
81461  pParse->nested--;
81462}
81463
81464/*
81465** Locate the in-memory structure that describes a particular database
81466** table given the name of that table and (optionally) the name of the
81467** database containing the table.  Return NULL if not found.
81468**
81469** If zDatabase is 0, all databases are searched for the table and the
81470** first matching table is returned.  (No checking for duplicate table
81471** names is done.)  The search order is TEMP first, then MAIN, then any
81472** auxiliary databases added using the ATTACH command.
81473**
81474** See also sqlite3LocateTable().
81475*/
81476SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
81477  Table *p = 0;
81478  int i;
81479  int nName;
81480  assert( zName!=0 );
81481  nName = sqlite3Strlen30(zName);
81482  /* All mutexes are required for schema access.  Make sure we hold them. */
81483  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
81484  for(i=OMIT_TEMPDB; i<db->nDb; i++){
81485    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
81486    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
81487    assert( sqlite3SchemaMutexHeld(db, j, 0) );
81488    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
81489    if( p ) break;
81490  }
81491  return p;
81492}
81493
81494/*
81495** Locate the in-memory structure that describes a particular database
81496** table given the name of that table and (optionally) the name of the
81497** database containing the table.  Return NULL if not found.  Also leave an
81498** error message in pParse->zErrMsg.
81499**
81500** The difference between this routine and sqlite3FindTable() is that this
81501** routine leaves an error message in pParse->zErrMsg where
81502** sqlite3FindTable() does not.
81503*/
81504SQLITE_PRIVATE Table *sqlite3LocateTable(
81505  Parse *pParse,         /* context in which to report errors */
81506  int isView,            /* True if looking for a VIEW rather than a TABLE */
81507  const char *zName,     /* Name of the table we are looking for */
81508  const char *zDbase     /* Name of the database.  Might be NULL */
81509){
81510  Table *p;
81511
81512  /* Read the database schema. If an error occurs, leave an error message
81513  ** and code in pParse and return NULL. */
81514  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81515    return 0;
81516  }
81517
81518  p = sqlite3FindTable(pParse->db, zName, zDbase);
81519  if( p==0 ){
81520    const char *zMsg = isView ? "no such view" : "no such table";
81521    if( zDbase ){
81522      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
81523    }else{
81524      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
81525    }
81526    pParse->checkSchema = 1;
81527  }
81528  return p;
81529}
81530
81531/*
81532** Locate the in-memory structure that describes
81533** a particular index given the name of that index
81534** and the name of the database that contains the index.
81535** Return NULL if not found.
81536**
81537** If zDatabase is 0, all databases are searched for the
81538** table and the first matching index is returned.  (No checking
81539** for duplicate index names is done.)  The search order is
81540** TEMP first, then MAIN, then any auxiliary databases added
81541** using the ATTACH command.
81542*/
81543SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
81544  Index *p = 0;
81545  int i;
81546  int nName = sqlite3Strlen30(zName);
81547  /* All mutexes are required for schema access.  Make sure we hold them. */
81548  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
81549  for(i=OMIT_TEMPDB; i<db->nDb; i++){
81550    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
81551    Schema *pSchema = db->aDb[j].pSchema;
81552    assert( pSchema );
81553    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
81554    assert( sqlite3SchemaMutexHeld(db, j, 0) );
81555    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
81556    if( p ) break;
81557  }
81558  return p;
81559}
81560
81561/*
81562** Reclaim the memory used by an index
81563*/
81564static void freeIndex(sqlite3 *db, Index *p){
81565#ifndef SQLITE_OMIT_ANALYZE
81566  sqlite3DeleteIndexSamples(db, p);
81567#endif
81568  sqlite3DbFree(db, p->zColAff);
81569  sqlite3DbFree(db, p);
81570}
81571
81572/*
81573** For the index called zIdxName which is found in the database iDb,
81574** unlike that index from its Table then remove the index from
81575** the index hash table and free all memory structures associated
81576** with the index.
81577*/
81578SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
81579  Index *pIndex;
81580  int len;
81581  Hash *pHash;
81582
81583  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81584  pHash = &db->aDb[iDb].pSchema->idxHash;
81585  len = sqlite3Strlen30(zIdxName);
81586  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
81587  if( ALWAYS(pIndex) ){
81588    if( pIndex->pTable->pIndex==pIndex ){
81589      pIndex->pTable->pIndex = pIndex->pNext;
81590    }else{
81591      Index *p;
81592      /* Justification of ALWAYS();  The index must be on the list of
81593      ** indices. */
81594      p = pIndex->pTable->pIndex;
81595      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
81596      if( ALWAYS(p && p->pNext==pIndex) ){
81597        p->pNext = pIndex->pNext;
81598      }
81599    }
81600    freeIndex(db, pIndex);
81601  }
81602  db->flags |= SQLITE_InternChanges;
81603}
81604
81605/*
81606** Erase all schema information from the in-memory hash tables of
81607** a single database.  This routine is called to reclaim memory
81608** before the database closes.  It is also called during a rollback
81609** if there were schema changes during the transaction or if a
81610** schema-cookie mismatch occurs.
81611**
81612** If iDb<0 then reset the internal schema tables for all database
81613** files.  If iDb>=0 then reset the internal schema for only the
81614** single file indicated.
81615*/
81616SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
81617  int i, j;
81618  assert( iDb<db->nDb );
81619
81620  if( iDb>=0 ){
81621    /* Case 1:  Reset the single schema identified by iDb */
81622    Db *pDb = &db->aDb[iDb];
81623    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81624    assert( pDb->pSchema!=0 );
81625    sqlite3SchemaClear(pDb->pSchema);
81626
81627    /* If any database other than TEMP is reset, then also reset TEMP
81628    ** since TEMP might be holding triggers that reference tables in the
81629    ** other database.
81630    */
81631    if( iDb!=1 ){
81632      pDb = &db->aDb[1];
81633      assert( pDb->pSchema!=0 );
81634      sqlite3SchemaClear(pDb->pSchema);
81635    }
81636    return;
81637  }
81638  /* Case 2 (from here to the end): Reset all schemas for all attached
81639  ** databases. */
81640  assert( iDb<0 );
81641  sqlite3BtreeEnterAll(db);
81642  for(i=0; i<db->nDb; i++){
81643    Db *pDb = &db->aDb[i];
81644    if( pDb->pSchema ){
81645      sqlite3SchemaClear(pDb->pSchema);
81646    }
81647  }
81648  db->flags &= ~SQLITE_InternChanges;
81649  sqlite3VtabUnlockList(db);
81650  sqlite3BtreeLeaveAll(db);
81651
81652  /* If one or more of the auxiliary database files has been closed,
81653  ** then remove them from the auxiliary database list.  We take the
81654  ** opportunity to do this here since we have just deleted all of the
81655  ** schema hash tables and therefore do not have to make any changes
81656  ** to any of those tables.
81657  */
81658  for(i=j=2; i<db->nDb; i++){
81659    struct Db *pDb = &db->aDb[i];
81660    if( pDb->pBt==0 ){
81661      sqlite3DbFree(db, pDb->zName);
81662      pDb->zName = 0;
81663      continue;
81664    }
81665    if( j<i ){
81666      db->aDb[j] = db->aDb[i];
81667    }
81668    j++;
81669  }
81670  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
81671  db->nDb = j;
81672  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
81673    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
81674    sqlite3DbFree(db, db->aDb);
81675    db->aDb = db->aDbStatic;
81676  }
81677}
81678
81679/*
81680** This routine is called when a commit occurs.
81681*/
81682SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
81683  db->flags &= ~SQLITE_InternChanges;
81684}
81685
81686/*
81687** Delete memory allocated for the column names of a table or view (the
81688** Table.aCol[] array).
81689*/
81690static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
81691  int i;
81692  Column *pCol;
81693  assert( pTable!=0 );
81694  if( (pCol = pTable->aCol)!=0 ){
81695    for(i=0; i<pTable->nCol; i++, pCol++){
81696      sqlite3DbFree(db, pCol->zName);
81697      sqlite3ExprDelete(db, pCol->pDflt);
81698      sqlite3DbFree(db, pCol->zDflt);
81699      sqlite3DbFree(db, pCol->zType);
81700      sqlite3DbFree(db, pCol->zColl);
81701    }
81702    sqlite3DbFree(db, pTable->aCol);
81703  }
81704}
81705
81706/*
81707** Remove the memory data structures associated with the given
81708** Table.  No changes are made to disk by this routine.
81709**
81710** This routine just deletes the data structure.  It does not unlink
81711** the table data structure from the hash table.  But it does destroy
81712** memory structures of the indices and foreign keys associated with
81713** the table.
81714*/
81715SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
81716  Index *pIndex, *pNext;
81717
81718  assert( !pTable || pTable->nRef>0 );
81719
81720  /* Do not delete the table until the reference count reaches zero. */
81721  if( !pTable ) return;
81722  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
81723
81724  /* Delete all indices associated with this table. */
81725  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
81726    pNext = pIndex->pNext;
81727    assert( pIndex->pSchema==pTable->pSchema );
81728    if( !db || db->pnBytesFreed==0 ){
81729      char *zName = pIndex->zName;
81730      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
81731	  &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
81732      );
81733      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
81734      assert( pOld==pIndex || pOld==0 );
81735    }
81736    freeIndex(db, pIndex);
81737  }
81738
81739  /* Delete any foreign keys attached to this table. */
81740  sqlite3FkDelete(db, pTable);
81741
81742  /* Delete the Table structure itself.
81743  */
81744  sqliteDeleteColumnNames(db, pTable);
81745  sqlite3DbFree(db, pTable->zName);
81746  sqlite3DbFree(db, pTable->zColAff);
81747  sqlite3SelectDelete(db, pTable->pSelect);
81748#ifndef SQLITE_OMIT_CHECK
81749  sqlite3ExprDelete(db, pTable->pCheck);
81750#endif
81751#ifndef SQLITE_OMIT_VIRTUALTABLE
81752  sqlite3VtabClear(db, pTable);
81753#endif
81754  sqlite3DbFree(db, pTable);
81755}
81756
81757/*
81758** Unlink the given table from the hash tables and the delete the
81759** table structure with all its indices and foreign keys.
81760*/
81761SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
81762  Table *p;
81763  Db *pDb;
81764
81765  assert( db!=0 );
81766  assert( iDb>=0 && iDb<db->nDb );
81767  assert( zTabName );
81768  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81769  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
81770  pDb = &db->aDb[iDb];
81771  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
81772                        sqlite3Strlen30(zTabName),0);
81773  sqlite3DeleteTable(db, p);
81774  db->flags |= SQLITE_InternChanges;
81775}
81776
81777/*
81778** Given a token, return a string that consists of the text of that
81779** token.  Space to hold the returned string
81780** is obtained from sqliteMalloc() and must be freed by the calling
81781** function.
81782**
81783** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
81784** surround the body of the token are removed.
81785**
81786** Tokens are often just pointers into the original SQL text and so
81787** are not \000 terminated and are not persistent.  The returned string
81788** is \000 terminated and is persistent.
81789*/
81790SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
81791  char *zName;
81792  if( pName ){
81793    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
81794    sqlite3Dequote(zName);
81795  }else{
81796    zName = 0;
81797  }
81798  return zName;
81799}
81800
81801/*
81802** Open the sqlite_master table stored in database number iDb for
81803** writing. The table is opened using cursor 0.
81804*/
81805SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
81806  Vdbe *v = sqlite3GetVdbe(p);
81807  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
81808  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
81809  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
81810  if( p->nTab==0 ){
81811    p->nTab = 1;
81812  }
81813}
81814
81815/*
81816** Parameter zName points to a nul-terminated buffer containing the name
81817** of a database ("main", "temp" or the name of an attached db). This
81818** function returns the index of the named database in db->aDb[], or
81819** -1 if the named db cannot be found.
81820*/
81821SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
81822  int i = -1;         /* Database number */
81823  if( zName ){
81824    Db *pDb;
81825    int n = sqlite3Strlen30(zName);
81826    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
81827      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
81828          0==sqlite3StrICmp(pDb->zName, zName) ){
81829        break;
81830      }
81831    }
81832  }
81833  return i;
81834}
81835
81836/*
81837** The token *pName contains the name of a database (either "main" or
81838** "temp" or the name of an attached db). This routine returns the
81839** index of the named database in db->aDb[], or -1 if the named db
81840** does not exist.
81841*/
81842SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
81843  int i;                               /* Database number */
81844  char *zName;                         /* Name we are searching for */
81845  zName = sqlite3NameFromToken(db, pName);
81846  i = sqlite3FindDbName(db, zName);
81847  sqlite3DbFree(db, zName);
81848  return i;
81849}
81850
81851/* The table or view or trigger name is passed to this routine via tokens
81852** pName1 and pName2. If the table name was fully qualified, for example:
81853**
81854** CREATE TABLE xxx.yyy (...);
81855**
81856** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81857** the table name is not fully qualified, i.e.:
81858**
81859** CREATE TABLE yyy(...);
81860**
81861** Then pName1 is set to "yyy" and pName2 is "".
81862**
81863** This routine sets the *ppUnqual pointer to point at the token (pName1 or
81864** pName2) that stores the unqualified table name.  The index of the
81865** database "xxx" is returned.
81866*/
81867SQLITE_PRIVATE int sqlite3TwoPartName(
81868  Parse *pParse,      /* Parsing and code generating context */
81869  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
81870  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
81871  Token **pUnqual     /* Write the unqualified object name here */
81872){
81873  int iDb;                    /* Database holding the object */
81874  sqlite3 *db = pParse->db;
81875
81876  if( ALWAYS(pName2!=0) && pName2->n>0 ){
81877    if( db->init.busy ) {
81878      sqlite3ErrorMsg(pParse, "corrupt database");
81879      pParse->nErr++;
81880      return -1;
81881    }
81882    *pUnqual = pName2;
81883    iDb = sqlite3FindDb(db, pName1);
81884    if( iDb<0 ){
81885      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
81886      pParse->nErr++;
81887      return -1;
81888    }
81889  }else{
81890    assert( db->init.iDb==0 || db->init.busy );
81891    iDb = db->init.iDb;
81892    *pUnqual = pName1;
81893  }
81894  return iDb;
81895}
81896
81897/*
81898** This routine is used to check if the UTF-8 string zName is a legal
81899** unqualified name for a new schema object (table, index, view or
81900** trigger). All names are legal except those that begin with the string
81901** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
81902** is reserved for internal use.
81903*/
81904SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
81905  if( !pParse->db->init.busy && pParse->nested==0
81906          && (pParse->db->flags & SQLITE_WriteSchema)==0
81907          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
81908    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
81909    return SQLITE_ERROR;
81910  }
81911  return SQLITE_OK;
81912}
81913
81914/*
81915** Begin constructing a new table representation in memory.  This is
81916** the first of several action routines that get called in response
81917** to a CREATE TABLE statement.  In particular, this routine is called
81918** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
81919** flag is true if the table should be stored in the auxiliary database
81920** file instead of in the main database file.  This is normally the case
81921** when the "TEMP" or "TEMPORARY" keyword occurs in between
81922** CREATE and TABLE.
81923**
81924** The new table record is initialized and put in pParse->pNewTable.
81925** As more of the CREATE TABLE statement is parsed, additional action
81926** routines will be called to add more information to this record.
81927** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
81928** is called to complete the construction of the new table record.
81929*/
81930SQLITE_PRIVATE void sqlite3StartTable(
81931  Parse *pParse,   /* Parser context */
81932  Token *pName1,   /* First part of the name of the table or view */
81933  Token *pName2,   /* Second part of the name of the table or view */
81934  int isTemp,      /* True if this is a TEMP table */
81935  int isView,      /* True if this is a VIEW */
81936  int isVirtual,   /* True if this is a VIRTUAL table */
81937  int noErr        /* Do nothing if table already exists */
81938){
81939  Table *pTable;
81940  char *zName = 0; /* The name of the new table */
81941  sqlite3 *db = pParse->db;
81942  Vdbe *v;
81943  int iDb;         /* Database number to create the table in */
81944  Token *pName;    /* Unqualified name of the table to create */
81945
81946  /* The table or view name to create is passed to this routine via tokens
81947  ** pName1 and pName2. If the table name was fully qualified, for example:
81948  **
81949  ** CREATE TABLE xxx.yyy (...);
81950  **
81951  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81952  ** the table name is not fully qualified, i.e.:
81953  **
81954  ** CREATE TABLE yyy(...);
81955  **
81956  ** Then pName1 is set to "yyy" and pName2 is "".
81957  **
81958  ** The call below sets the pName pointer to point at the token (pName1 or
81959  ** pName2) that stores the unqualified table name. The variable iDb is
81960  ** set to the index of the database that the table or view is to be
81961  ** created in.
81962  */
81963  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
81964  if( iDb<0 ) return;
81965  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
81966    /* If creating a temp table, the name may not be qualified. Unless
81967    ** the database name is "temp" anyway.  */
81968    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
81969    return;
81970  }
81971  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
81972
81973  pParse->sNameToken = *pName;
81974  zName = sqlite3NameFromToken(db, pName);
81975  if( zName==0 ) return;
81976  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
81977    goto begin_table_error;
81978  }
81979  if( db->init.iDb==1 ) isTemp = 1;
81980#ifndef SQLITE_OMIT_AUTHORIZATION
81981  assert( (isTemp & 1)==isTemp );
81982  {
81983    int code;
81984    char *zDb = db->aDb[iDb].zName;
81985    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
81986      goto begin_table_error;
81987    }
81988    if( isView ){
81989      if( !OMIT_TEMPDB && isTemp ){
81990        code = SQLITE_CREATE_TEMP_VIEW;
81991      }else{
81992        code = SQLITE_CREATE_VIEW;
81993      }
81994    }else{
81995      if( !OMIT_TEMPDB && isTemp ){
81996        code = SQLITE_CREATE_TEMP_TABLE;
81997      }else{
81998        code = SQLITE_CREATE_TABLE;
81999      }
82000    }
82001    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
82002      goto begin_table_error;
82003    }
82004  }
82005#endif
82006
82007  /* Make sure the new table name does not collide with an existing
82008  ** index or table name in the same database.  Issue an error message if
82009  ** it does. The exception is if the statement being parsed was passed
82010  ** to an sqlite3_declare_vtab() call. In that case only the column names
82011  ** and types will be used, so there is no need to test for namespace
82012  ** collisions.
82013  */
82014  if( !IN_DECLARE_VTAB ){
82015    char *zDb = db->aDb[iDb].zName;
82016    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82017      goto begin_table_error;
82018    }
82019    pTable = sqlite3FindTable(db, zName, zDb);
82020    if( pTable ){
82021      if( !noErr ){
82022        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
82023      }else{
82024        assert( !db->init.busy );
82025        sqlite3CodeVerifySchema(pParse, iDb);
82026      }
82027      goto begin_table_error;
82028    }
82029    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
82030      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
82031      goto begin_table_error;
82032    }
82033  }
82034
82035  pTable = sqlite3DbMallocZero(db, sizeof(Table));
82036  if( pTable==0 ){
82037    db->mallocFailed = 1;
82038    pParse->rc = SQLITE_NOMEM;
82039    pParse->nErr++;
82040    goto begin_table_error;
82041  }
82042  pTable->zName = zName;
82043  pTable->iPKey = -1;
82044  pTable->pSchema = db->aDb[iDb].pSchema;
82045  pTable->nRef = 1;
82046  pTable->nRowEst = 1000000;
82047  assert( pParse->pNewTable==0 );
82048  pParse->pNewTable = pTable;
82049
82050  /* If this is the magic sqlite_sequence table used by autoincrement,
82051  ** then record a pointer to this table in the main database structure
82052  ** so that INSERT can find the table easily.
82053  */
82054#ifndef SQLITE_OMIT_AUTOINCREMENT
82055  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
82056    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82057    pTable->pSchema->pSeqTab = pTable;
82058  }
82059#endif
82060
82061  /* Begin generating the code that will insert the table record into
82062  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
82063  ** and allocate the record number for the table entry now.  Before any
82064  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
82065  ** indices to be created and the table record must come before the
82066  ** indices.  Hence, the record number for the table must be allocated
82067  ** now.
82068  */
82069  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
82070    int j1;
82071    int fileFormat;
82072    int reg1, reg2, reg3;
82073    sqlite3BeginWriteOperation(pParse, 0, iDb);
82074
82075#ifndef SQLITE_OMIT_VIRTUALTABLE
82076    if( isVirtual ){
82077      sqlite3VdbeAddOp0(v, OP_VBegin);
82078    }
82079#endif
82080
82081    /* If the file format and encoding in the database have not been set,
82082    ** set them now.
82083    */
82084    reg1 = pParse->regRowid = ++pParse->nMem;
82085    reg2 = pParse->regRoot = ++pParse->nMem;
82086    reg3 = ++pParse->nMem;
82087    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
82088    sqlite3VdbeUsesBtree(v, iDb);
82089    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
82090    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
82091                  1 : SQLITE_MAX_FILE_FORMAT;
82092    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
82093    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
82094    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
82095    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
82096    sqlite3VdbeJumpHere(v, j1);
82097
82098    /* This just creates a place-holder record in the sqlite_master table.
82099    ** The record created does not contain anything yet.  It will be replaced
82100    ** by the real entry in code generated at sqlite3EndTable().
82101    **
82102    ** The rowid for the new entry is left in register pParse->regRowid.
82103    ** The root page number of the new table is left in reg pParse->regRoot.
82104    ** The rowid and root page number values are needed by the code that
82105    ** sqlite3EndTable will generate.
82106    */
82107#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
82108    if( isView || isVirtual ){
82109      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
82110    }else
82111#endif
82112    {
82113      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
82114    }
82115    sqlite3OpenMasterTable(pParse, iDb);
82116    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
82117    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
82118    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
82119    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
82120    sqlite3VdbeAddOp0(v, OP_Close);
82121  }
82122
82123  /* Normal (non-error) return. */
82124  return;
82125
82126  /* If an error occurs, we jump here */
82127begin_table_error:
82128  sqlite3DbFree(db, zName);
82129  return;
82130}
82131
82132/*
82133** This macro is used to compare two strings in a case-insensitive manner.
82134** It is slightly faster than calling sqlite3StrICmp() directly, but
82135** produces larger code.
82136**
82137** WARNING: This macro is not compatible with the strcmp() family. It
82138** returns true if the two strings are equal, otherwise false.
82139*/
82140#define STRICMP(x, y) (\
82141sqlite3UpperToLower[*(unsigned char *)(x)]==   \
82142sqlite3UpperToLower[*(unsigned char *)(y)]     \
82143&& sqlite3StrICmp((x)+1,(y)+1)==0 )
82144
82145/*
82146** Add a new column to the table currently being constructed.
82147**
82148** The parser calls this routine once for each column declaration
82149** in a CREATE TABLE statement.  sqlite3StartTable() gets called
82150** first to get things going.  Then this routine is called for each
82151** column.
82152*/
82153SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
82154  Table *p;
82155  int i;
82156  char *z;
82157  Column *pCol;
82158  sqlite3 *db = pParse->db;
82159  if( (p = pParse->pNewTable)==0 ) return;
82160#if SQLITE_MAX_COLUMN
82161  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
82162    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
82163    return;
82164  }
82165#endif
82166  z = sqlite3NameFromToken(db, pName);
82167  if( z==0 ) return;
82168  for(i=0; i<p->nCol; i++){
82169    if( STRICMP(z, p->aCol[i].zName) ){
82170      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
82171      sqlite3DbFree(db, z);
82172      return;
82173    }
82174  }
82175  if( (p->nCol & 0x7)==0 ){
82176    Column *aNew;
82177    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
82178    if( aNew==0 ){
82179      sqlite3DbFree(db, z);
82180      return;
82181    }
82182    p->aCol = aNew;
82183  }
82184  pCol = &p->aCol[p->nCol];
82185  memset(pCol, 0, sizeof(p->aCol[0]));
82186  pCol->zName = z;
82187
82188  /* If there is no type specified, columns have the default affinity
82189  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
82190  ** be called next to set pCol->affinity correctly.
82191  */
82192  pCol->affinity = SQLITE_AFF_NONE;
82193  p->nCol++;
82194}
82195
82196/*
82197** This routine is called by the parser while in the middle of
82198** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
82199** been seen on a column.  This routine sets the notNull flag on
82200** the column currently under construction.
82201*/
82202SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
82203  Table *p;
82204  p = pParse->pNewTable;
82205  if( p==0 || NEVER(p->nCol<1) ) return;
82206  p->aCol[p->nCol-1].notNull = (u8)onError;
82207}
82208
82209/*
82210** Scan the column type name zType (length nType) and return the
82211** associated affinity type.
82212**
82213** This routine does a case-independent search of zType for the
82214** substrings in the following table. If one of the substrings is
82215** found, the corresponding affinity is returned. If zType contains
82216** more than one of the substrings, entries toward the top of
82217** the table take priority. For example, if zType is 'BLOBINT',
82218** SQLITE_AFF_INTEGER is returned.
82219**
82220** Substring     | Affinity
82221** --------------------------------
82222** 'INT'         | SQLITE_AFF_INTEGER
82223** 'CHAR'        | SQLITE_AFF_TEXT
82224** 'CLOB'        | SQLITE_AFF_TEXT
82225** 'TEXT'        | SQLITE_AFF_TEXT
82226** 'BLOB'        | SQLITE_AFF_NONE
82227** 'REAL'        | SQLITE_AFF_REAL
82228** 'FLOA'        | SQLITE_AFF_REAL
82229** 'DOUB'        | SQLITE_AFF_REAL
82230**
82231** If none of the substrings in the above table are found,
82232** SQLITE_AFF_NUMERIC is returned.
82233*/
82234SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
82235  u32 h = 0;
82236  char aff = SQLITE_AFF_NUMERIC;
82237
82238  if( zIn ) while( zIn[0] ){
82239    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
82240    zIn++;
82241    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
82242      aff = SQLITE_AFF_TEXT;
82243    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
82244      aff = SQLITE_AFF_TEXT;
82245    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
82246      aff = SQLITE_AFF_TEXT;
82247    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
82248        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
82249      aff = SQLITE_AFF_NONE;
82250#ifndef SQLITE_OMIT_FLOATING_POINT
82251    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
82252        && aff==SQLITE_AFF_NUMERIC ){
82253      aff = SQLITE_AFF_REAL;
82254    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
82255        && aff==SQLITE_AFF_NUMERIC ){
82256      aff = SQLITE_AFF_REAL;
82257    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
82258        && aff==SQLITE_AFF_NUMERIC ){
82259      aff = SQLITE_AFF_REAL;
82260#endif
82261    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
82262      aff = SQLITE_AFF_INTEGER;
82263      break;
82264    }
82265  }
82266
82267  return aff;
82268}
82269
82270/*
82271** This routine is called by the parser while in the middle of
82272** parsing a CREATE TABLE statement.  The pFirst token is the first
82273** token in the sequence of tokens that describe the type of the
82274** column currently under construction.   pLast is the last token
82275** in the sequence.  Use this information to construct a string
82276** that contains the typename of the column and store that string
82277** in zType.
82278*/
82279SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
82280  Table *p;
82281  Column *pCol;
82282
82283  p = pParse->pNewTable;
82284  if( p==0 || NEVER(p->nCol<1) ) return;
82285  pCol = &p->aCol[p->nCol-1];
82286  assert( pCol->zType==0 );
82287  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
82288  pCol->affinity = sqlite3AffinityType(pCol->zType);
82289}
82290
82291/*
82292** The expression is the default value for the most recently added column
82293** of the table currently under construction.
82294**
82295** Default value expressions must be constant.  Raise an exception if this
82296** is not the case.
82297**
82298** This routine is called by the parser while in the middle of
82299** parsing a CREATE TABLE statement.
82300*/
82301SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
82302  Table *p;
82303  Column *pCol;
82304  sqlite3 *db = pParse->db;
82305  p = pParse->pNewTable;
82306  if( p!=0 ){
82307    pCol = &(p->aCol[p->nCol-1]);
82308    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
82309      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
82310          pCol->zName);
82311    }else{
82312      /* A copy of pExpr is used instead of the original, as pExpr contains
82313      ** tokens that point to volatile memory. The 'span' of the expression
82314      ** is required by pragma table_info.
82315      */
82316      sqlite3ExprDelete(db, pCol->pDflt);
82317      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
82318      sqlite3DbFree(db, pCol->zDflt);
82319      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
82320                                     (int)(pSpan->zEnd - pSpan->zStart));
82321    }
82322  }
82323  sqlite3ExprDelete(db, pSpan->pExpr);
82324}
82325
82326/*
82327** Designate the PRIMARY KEY for the table.  pList is a list of names
82328** of columns that form the primary key.  If pList is NULL, then the
82329** most recently added column of the table is the primary key.
82330**
82331** A table can have at most one primary key.  If the table already has
82332** a primary key (and this is the second primary key) then create an
82333** error.
82334**
82335** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
82336** then we will try to use that column as the rowid.  Set the Table.iPKey
82337** field of the table under construction to be the index of the
82338** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
82339** no INTEGER PRIMARY KEY.
82340**
82341** If the key is not an INTEGER PRIMARY KEY, then create a unique
82342** index for the key.  No index is created for INTEGER PRIMARY KEYs.
82343*/
82344SQLITE_PRIVATE void sqlite3AddPrimaryKey(
82345  Parse *pParse,    /* Parsing context */
82346  ExprList *pList,  /* List of field names to be indexed */
82347  int onError,      /* What to do with a uniqueness conflict */
82348  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
82349  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
82350){
82351  Table *pTab = pParse->pNewTable;
82352  char *zType = 0;
82353  int iCol = -1, i;
82354  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
82355  if( pTab->tabFlags & TF_HasPrimaryKey ){
82356    sqlite3ErrorMsg(pParse,
82357      "table \"%s\" has more than one primary key", pTab->zName);
82358    goto primary_key_exit;
82359  }
82360  pTab->tabFlags |= TF_HasPrimaryKey;
82361  if( pList==0 ){
82362    iCol = pTab->nCol - 1;
82363    pTab->aCol[iCol].isPrimKey = 1;
82364  }else{
82365    for(i=0; i<pList->nExpr; i++){
82366      for(iCol=0; iCol<pTab->nCol; iCol++){
82367        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
82368          break;
82369        }
82370      }
82371      if( iCol<pTab->nCol ){
82372        pTab->aCol[iCol].isPrimKey = 1;
82373      }
82374    }
82375    if( pList->nExpr>1 ) iCol = -1;
82376  }
82377  if( iCol>=0 && iCol<pTab->nCol ){
82378    zType = pTab->aCol[iCol].zType;
82379  }
82380  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
82381        && sortOrder==SQLITE_SO_ASC ){
82382    pTab->iPKey = iCol;
82383    pTab->keyConf = (u8)onError;
82384    assert( autoInc==0 || autoInc==1 );
82385    pTab->tabFlags |= autoInc*TF_Autoincrement;
82386  }else if( autoInc ){
82387#ifndef SQLITE_OMIT_AUTOINCREMENT
82388    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
82389       "INTEGER PRIMARY KEY");
82390#endif
82391  }else{
82392    Index *p;
82393    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
82394    if( p ){
82395      p->autoIndex = 2;
82396    }
82397    pList = 0;
82398  }
82399
82400primary_key_exit:
82401  sqlite3ExprListDelete(pParse->db, pList);
82402  return;
82403}
82404
82405/*
82406** Add a new CHECK constraint to the table currently under construction.
82407*/
82408SQLITE_PRIVATE void sqlite3AddCheckConstraint(
82409  Parse *pParse,    /* Parsing context */
82410  Expr *pCheckExpr  /* The check expression */
82411){
82412  sqlite3 *db = pParse->db;
82413#ifndef SQLITE_OMIT_CHECK
82414  Table *pTab = pParse->pNewTable;
82415  if( pTab && !IN_DECLARE_VTAB ){
82416    pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
82417  }else
82418#endif
82419  {
82420    sqlite3ExprDelete(db, pCheckExpr);
82421  }
82422}
82423
82424/*
82425** Set the collation function of the most recently parsed table column
82426** to the CollSeq given.
82427*/
82428SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
82429  Table *p;
82430  int i;
82431  char *zColl;              /* Dequoted name of collation sequence */
82432  sqlite3 *db;
82433
82434  if( (p = pParse->pNewTable)==0 ) return;
82435  i = p->nCol-1;
82436  db = pParse->db;
82437  zColl = sqlite3NameFromToken(db, pToken);
82438  if( !zColl ) return;
82439
82440  if( sqlite3LocateCollSeq(pParse, zColl) ){
82441    Index *pIdx;
82442    p->aCol[i].zColl = zColl;
82443
82444    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
82445    ** then an index may have been created on this column before the
82446    ** collation type was added. Correct this if it is the case.
82447    */
82448    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
82449      assert( pIdx->nColumn==1 );
82450      if( pIdx->aiColumn[0]==i ){
82451        pIdx->azColl[0] = p->aCol[i].zColl;
82452      }
82453    }
82454  }else{
82455    sqlite3DbFree(db, zColl);
82456  }
82457}
82458
82459/*
82460** This function returns the collation sequence for database native text
82461** encoding identified by the string zName, length nName.
82462**
82463** If the requested collation sequence is not available, or not available
82464** in the database native encoding, the collation factory is invoked to
82465** request it. If the collation factory does not supply such a sequence,
82466** and the sequence is available in another text encoding, then that is
82467** returned instead.
82468**
82469** If no versions of the requested collations sequence are available, or
82470** another error occurs, NULL is returned and an error message written into
82471** pParse.
82472**
82473** This routine is a wrapper around sqlite3FindCollSeq().  This routine
82474** invokes the collation factory if the named collation cannot be found
82475** and generates an error message.
82476**
82477** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
82478*/
82479SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
82480  sqlite3 *db = pParse->db;
82481  u8 enc = ENC(db);
82482  u8 initbusy = db->init.busy;
82483  CollSeq *pColl;
82484
82485  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
82486  if( !initbusy && (!pColl || !pColl->xCmp) ){
82487    pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
82488    if( !pColl ){
82489      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
82490    }
82491  }
82492
82493  return pColl;
82494}
82495
82496
82497/*
82498** Generate code that will increment the schema cookie.
82499**
82500** The schema cookie is used to determine when the schema for the
82501** database changes.  After each schema change, the cookie value
82502** changes.  When a process first reads the schema it records the
82503** cookie.  Thereafter, whenever it goes to access the database,
82504** it checks the cookie to make sure the schema has not changed
82505** since it was last read.
82506**
82507** This plan is not completely bullet-proof.  It is possible for
82508** the schema to change multiple times and for the cookie to be
82509** set back to prior value.  But schema changes are infrequent
82510** and the probability of hitting the same cookie value is only
82511** 1 chance in 2^32.  So we're safe enough.
82512*/
82513SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
82514  int r1 = sqlite3GetTempReg(pParse);
82515  sqlite3 *db = pParse->db;
82516  Vdbe *v = pParse->pVdbe;
82517  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82518  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
82519  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
82520  sqlite3ReleaseTempReg(pParse, r1);
82521}
82522
82523/*
82524** Measure the number of characters needed to output the given
82525** identifier.  The number returned includes any quotes used
82526** but does not include the null terminator.
82527**
82528** The estimate is conservative.  It might be larger that what is
82529** really needed.
82530*/
82531static int identLength(const char *z){
82532  int n;
82533  for(n=0; *z; n++, z++){
82534    if( *z=='"' ){ n++; }
82535  }
82536  return n + 2;
82537}
82538
82539/*
82540** The first parameter is a pointer to an output buffer. The second
82541** parameter is a pointer to an integer that contains the offset at
82542** which to write into the output buffer. This function copies the
82543** nul-terminated string pointed to by the third parameter, zSignedIdent,
82544** to the specified offset in the buffer and updates *pIdx to refer
82545** to the first byte after the last byte written before returning.
82546**
82547** If the string zSignedIdent consists entirely of alpha-numeric
82548** characters, does not begin with a digit and is not an SQL keyword,
82549** then it is copied to the output buffer exactly as it is. Otherwise,
82550** it is quoted using double-quotes.
82551*/
82552static void identPut(char *z, int *pIdx, char *zSignedIdent){
82553  unsigned char *zIdent = (unsigned char*)zSignedIdent;
82554  int i, j, needQuote;
82555  i = *pIdx;
82556
82557  for(j=0; zIdent[j]; j++){
82558    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
82559  }
82560  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
82561  if( !needQuote ){
82562    needQuote = zIdent[j];
82563  }
82564
82565  if( needQuote ) z[i++] = '"';
82566  for(j=0; zIdent[j]; j++){
82567    z[i++] = zIdent[j];
82568    if( zIdent[j]=='"' ) z[i++] = '"';
82569  }
82570  if( needQuote ) z[i++] = '"';
82571  z[i] = 0;
82572  *pIdx = i;
82573}
82574
82575/*
82576** Generate a CREATE TABLE statement appropriate for the given
82577** table.  Memory to hold the text of the statement is obtained
82578** from sqliteMalloc() and must be freed by the calling function.
82579*/
82580static char *createTableStmt(sqlite3 *db, Table *p){
82581  int i, k, n;
82582  char *zStmt;
82583  char *zSep, *zSep2, *zEnd;
82584  Column *pCol;
82585  n = 0;
82586  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
82587    n += identLength(pCol->zName) + 5;
82588  }
82589  n += identLength(p->zName);
82590  if( n<50 ){
82591    zSep = "";
82592    zSep2 = ",";
82593    zEnd = ")";
82594  }else{
82595    zSep = "\n  ";
82596    zSep2 = ",\n  ";
82597    zEnd = "\n)";
82598  }
82599  n += 35 + 6*p->nCol;
82600  zStmt = sqlite3DbMallocRaw(0, n);
82601  if( zStmt==0 ){
82602    db->mallocFailed = 1;
82603    return 0;
82604  }
82605  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
82606  k = sqlite3Strlen30(zStmt);
82607  identPut(zStmt, &k, p->zName);
82608  zStmt[k++] = '(';
82609  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
82610    static const char * const azType[] = {
82611        /* SQLITE_AFF_TEXT    */ " TEXT",
82612        /* SQLITE_AFF_NONE    */ "",
82613        /* SQLITE_AFF_NUMERIC */ " NUM",
82614        /* SQLITE_AFF_INTEGER */ " INT",
82615        /* SQLITE_AFF_REAL    */ " REAL"
82616    };
82617    int len;
82618    const char *zType;
82619
82620    sqlite3_snprintf(n-k, &zStmt[k], zSep);
82621    k += sqlite3Strlen30(&zStmt[k]);
82622    zSep = zSep2;
82623    identPut(zStmt, &k, pCol->zName);
82624    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
82625    assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
82626    testcase( pCol->affinity==SQLITE_AFF_TEXT );
82627    testcase( pCol->affinity==SQLITE_AFF_NONE );
82628    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
82629    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
82630    testcase( pCol->affinity==SQLITE_AFF_REAL );
82631
82632    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
82633    len = sqlite3Strlen30(zType);
82634    assert( pCol->affinity==SQLITE_AFF_NONE
82635            || pCol->affinity==sqlite3AffinityType(zType) );
82636    memcpy(&zStmt[k], zType, len);
82637    k += len;
82638    assert( k<=n );
82639  }
82640  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
82641  return zStmt;
82642}
82643
82644/*
82645** This routine is called to report the final ")" that terminates
82646** a CREATE TABLE statement.
82647**
82648** The table structure that other action routines have been building
82649** is added to the internal hash tables, assuming no errors have
82650** occurred.
82651**
82652** An entry for the table is made in the master table on disk, unless
82653** this is a temporary table or db->init.busy==1.  When db->init.busy==1
82654** it means we are reading the sqlite_master table because we just
82655** connected to the database or because the sqlite_master table has
82656** recently changed, so the entry for this table already exists in
82657** the sqlite_master table.  We do not want to create it again.
82658**
82659** If the pSelect argument is not NULL, it means that this routine
82660** was called to create a table generated from a
82661** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
82662** the new table will match the result set of the SELECT.
82663*/
82664SQLITE_PRIVATE void sqlite3EndTable(
82665  Parse *pParse,          /* Parse context */
82666  Token *pCons,           /* The ',' token after the last column defn. */
82667  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
82668  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
82669){
82670  Table *p;
82671  sqlite3 *db = pParse->db;
82672  int iDb;
82673
82674  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
82675    return;
82676  }
82677  p = pParse->pNewTable;
82678  if( p==0 ) return;
82679
82680  assert( !db->init.busy || !pSelect );
82681
82682  iDb = sqlite3SchemaToIndex(db, p->pSchema);
82683
82684#ifndef SQLITE_OMIT_CHECK
82685  /* Resolve names in all CHECK constraint expressions.
82686  */
82687  if( p->pCheck ){
82688    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
82689    NameContext sNC;                /* Name context for pParse->pNewTable */
82690
82691    memset(&sNC, 0, sizeof(sNC));
82692    memset(&sSrc, 0, sizeof(sSrc));
82693    sSrc.nSrc = 1;
82694    sSrc.a[0].zName = p->zName;
82695    sSrc.a[0].pTab = p;
82696    sSrc.a[0].iCursor = -1;
82697    sNC.pParse = pParse;
82698    sNC.pSrcList = &sSrc;
82699    sNC.isCheck = 1;
82700    if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
82701      return;
82702    }
82703  }
82704#endif /* !defined(SQLITE_OMIT_CHECK) */
82705
82706  /* If the db->init.busy is 1 it means we are reading the SQL off the
82707  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
82708  ** So do not write to the disk again.  Extract the root page number
82709  ** for the table from the db->init.newTnum field.  (The page number
82710  ** should have been put there by the sqliteOpenCb routine.)
82711  */
82712  if( db->init.busy ){
82713    p->tnum = db->init.newTnum;
82714  }
82715
82716  /* If not initializing, then create a record for the new table
82717  ** in the SQLITE_MASTER table of the database.
82718  **
82719  ** If this is a TEMPORARY table, write the entry into the auxiliary
82720  ** file instead of into the main database file.
82721  */
82722  if( !db->init.busy ){
82723    int n;
82724    Vdbe *v;
82725    char *zType;    /* "view" or "table" */
82726    char *zType2;   /* "VIEW" or "TABLE" */
82727    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
82728
82729    v = sqlite3GetVdbe(pParse);
82730    if( NEVER(v==0) ) return;
82731
82732    sqlite3VdbeAddOp1(v, OP_Close, 0);
82733
82734    /*
82735    ** Initialize zType for the new view or table.
82736    */
82737    if( p->pSelect==0 ){
82738      /* A regular table */
82739      zType = "table";
82740      zType2 = "TABLE";
82741#ifndef SQLITE_OMIT_VIEW
82742    }else{
82743      /* A view */
82744      zType = "view";
82745      zType2 = "VIEW";
82746#endif
82747    }
82748
82749    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
82750    ** statement to populate the new table. The root-page number for the
82751    ** new table is in register pParse->regRoot.
82752    **
82753    ** Once the SELECT has been coded by sqlite3Select(), it is in a
82754    ** suitable state to query for the column names and types to be used
82755    ** by the new table.
82756    **
82757    ** A shared-cache write-lock is not required to write to the new table,
82758    ** as a schema-lock must have already been obtained to create it. Since
82759    ** a schema-lock excludes all other database users, the write-lock would
82760    ** be redundant.
82761    */
82762    if( pSelect ){
82763      SelectDest dest;
82764      Table *pSelTab;
82765
82766      assert(pParse->nTab==1);
82767      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
82768      sqlite3VdbeChangeP5(v, 1);
82769      pParse->nTab = 2;
82770      sqlite3SelectDestInit(&dest, SRT_Table, 1);
82771      sqlite3Select(pParse, pSelect, &dest);
82772      sqlite3VdbeAddOp1(v, OP_Close, 1);
82773      if( pParse->nErr==0 ){
82774        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
82775        if( pSelTab==0 ) return;
82776        assert( p->aCol==0 );
82777        p->nCol = pSelTab->nCol;
82778        p->aCol = pSelTab->aCol;
82779        pSelTab->nCol = 0;
82780        pSelTab->aCol = 0;
82781        sqlite3DeleteTable(db, pSelTab);
82782      }
82783    }
82784
82785    /* Compute the complete text of the CREATE statement */
82786    if( pSelect ){
82787      zStmt = createTableStmt(db, p);
82788    }else{
82789      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
82790      zStmt = sqlite3MPrintf(db,
82791          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
82792      );
82793    }
82794
82795    /* A slot for the record has already been allocated in the
82796    ** SQLITE_MASTER table.  We just need to update that slot with all
82797    ** the information we've collected.
82798    */
82799    sqlite3NestedParse(pParse,
82800      "UPDATE %Q.%s "
82801         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
82802       "WHERE rowid=#%d",
82803      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
82804      zType,
82805      p->zName,
82806      p->zName,
82807      pParse->regRoot,
82808      zStmt,
82809      pParse->regRowid
82810    );
82811    sqlite3DbFree(db, zStmt);
82812    sqlite3ChangeCookie(pParse, iDb);
82813
82814#ifndef SQLITE_OMIT_AUTOINCREMENT
82815    /* Check to see if we need to create an sqlite_sequence table for
82816    ** keeping track of autoincrement keys.
82817    */
82818    if( p->tabFlags & TF_Autoincrement ){
82819      Db *pDb = &db->aDb[iDb];
82820      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82821      if( pDb->pSchema->pSeqTab==0 ){
82822        sqlite3NestedParse(pParse,
82823          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
82824          pDb->zName
82825        );
82826      }
82827    }
82828#endif
82829
82830    /* Reparse everything to update our internal data structures */
82831    sqlite3VdbeAddParseSchemaOp(v, iDb,
82832               sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
82833  }
82834
82835
82836  /* Add the table to the in-memory representation of the database.
82837  */
82838  if( db->init.busy ){
82839    Table *pOld;
82840    Schema *pSchema = p->pSchema;
82841    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82842    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
82843                             sqlite3Strlen30(p->zName),p);
82844    if( pOld ){
82845      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
82846      db->mallocFailed = 1;
82847      return;
82848    }
82849    pParse->pNewTable = 0;
82850    db->flags |= SQLITE_InternChanges;
82851
82852#ifndef SQLITE_OMIT_ALTERTABLE
82853    if( !p->pSelect ){
82854      const char *zName = (const char *)pParse->sNameToken.z;
82855      int nName;
82856      assert( !pSelect && pCons && pEnd );
82857      if( pCons->z==0 ){
82858        pCons = pEnd;
82859      }
82860      nName = (int)((const char *)pCons->z - zName);
82861      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
82862    }
82863#endif
82864  }
82865}
82866
82867#ifndef SQLITE_OMIT_VIEW
82868/*
82869** The parser calls this routine in order to create a new VIEW
82870*/
82871SQLITE_PRIVATE void sqlite3CreateView(
82872  Parse *pParse,     /* The parsing context */
82873  Token *pBegin,     /* The CREATE token that begins the statement */
82874  Token *pName1,     /* The token that holds the name of the view */
82875  Token *pName2,     /* The token that holds the name of the view */
82876  Select *pSelect,   /* A SELECT statement that will become the new view */
82877  int isTemp,        /* TRUE for a TEMPORARY view */
82878  int noErr          /* Suppress error messages if VIEW already exists */
82879){
82880  Table *p;
82881  int n;
82882  const char *z;
82883  Token sEnd;
82884  DbFixer sFix;
82885  Token *pName = 0;
82886  int iDb;
82887  sqlite3 *db = pParse->db;
82888
82889  if( pParse->nVar>0 ){
82890    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
82891    sqlite3SelectDelete(db, pSelect);
82892    return;
82893  }
82894  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
82895  p = pParse->pNewTable;
82896  if( p==0 || pParse->nErr ){
82897    sqlite3SelectDelete(db, pSelect);
82898    return;
82899  }
82900  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
82901  iDb = sqlite3SchemaToIndex(db, p->pSchema);
82902  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
82903    && sqlite3FixSelect(&sFix, pSelect)
82904  ){
82905    sqlite3SelectDelete(db, pSelect);
82906    return;
82907  }
82908
82909  /* Make a copy of the entire SELECT statement that defines the view.
82910  ** This will force all the Expr.token.z values to be dynamically
82911  ** allocated rather than point to the input string - which means that
82912  ** they will persist after the current sqlite3_exec() call returns.
82913  */
82914  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
82915  sqlite3SelectDelete(db, pSelect);
82916  if( db->mallocFailed ){
82917    return;
82918  }
82919  if( !db->init.busy ){
82920    sqlite3ViewGetColumnNames(pParse, p);
82921  }
82922
82923  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
82924  ** the end.
82925  */
82926  sEnd = pParse->sLastToken;
82927  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
82928    sEnd.z += sEnd.n;
82929  }
82930  sEnd.n = 0;
82931  n = (int)(sEnd.z - pBegin->z);
82932  z = pBegin->z;
82933  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
82934  sEnd.z = &z[n-1];
82935  sEnd.n = 1;
82936
82937  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
82938  sqlite3EndTable(pParse, 0, &sEnd, 0);
82939  return;
82940}
82941#endif /* SQLITE_OMIT_VIEW */
82942
82943#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
82944/*
82945** The Table structure pTable is really a VIEW.  Fill in the names of
82946** the columns of the view in the pTable structure.  Return the number
82947** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
82948*/
82949SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
82950  Table *pSelTab;   /* A fake table from which we get the result set */
82951  Select *pSel;     /* Copy of the SELECT that implements the view */
82952  int nErr = 0;     /* Number of errors encountered */
82953  int n;            /* Temporarily holds the number of cursors assigned */
82954  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
82955  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
82956
82957  assert( pTable );
82958
82959#ifndef SQLITE_OMIT_VIRTUALTABLE
82960  if( sqlite3VtabCallConnect(pParse, pTable) ){
82961    return SQLITE_ERROR;
82962  }
82963  if( IsVirtual(pTable) ) return 0;
82964#endif
82965
82966#ifndef SQLITE_OMIT_VIEW
82967  /* A positive nCol means the columns names for this view are
82968  ** already known.
82969  */
82970  if( pTable->nCol>0 ) return 0;
82971
82972  /* A negative nCol is a special marker meaning that we are currently
82973  ** trying to compute the column names.  If we enter this routine with
82974  ** a negative nCol, it means two or more views form a loop, like this:
82975  **
82976  **     CREATE VIEW one AS SELECT * FROM two;
82977  **     CREATE VIEW two AS SELECT * FROM one;
82978  **
82979  ** Actually, the error above is now caught prior to reaching this point.
82980  ** But the following test is still important as it does come up
82981  ** in the following:
82982  **
82983  **     CREATE TABLE main.ex1(a);
82984  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
82985  **     SELECT * FROM temp.ex1;
82986  */
82987  if( pTable->nCol<0 ){
82988    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
82989    return 1;
82990  }
82991  assert( pTable->nCol>=0 );
82992
82993  /* If we get this far, it means we need to compute the table names.
82994  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
82995  ** "*" elements in the results set of the view and will assign cursors
82996  ** to the elements of the FROM clause.  But we do not want these changes
82997  ** to be permanent.  So the computation is done on a copy of the SELECT
82998  ** statement that defines the view.
82999  */
83000  assert( pTable->pSelect );
83001  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
83002  if( pSel ){
83003    u8 enableLookaside = db->lookaside.bEnabled;
83004    n = pParse->nTab;
83005    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
83006    pTable->nCol = -1;
83007    db->lookaside.bEnabled = 0;
83008#ifndef SQLITE_OMIT_AUTHORIZATION
83009    xAuth = db->xAuth;
83010    db->xAuth = 0;
83011    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
83012    db->xAuth = xAuth;
83013#else
83014    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
83015#endif
83016    db->lookaside.bEnabled = enableLookaside;
83017    pParse->nTab = n;
83018    if( pSelTab ){
83019      assert( pTable->aCol==0 );
83020      pTable->nCol = pSelTab->nCol;
83021      pTable->aCol = pSelTab->aCol;
83022      pSelTab->nCol = 0;
83023      pSelTab->aCol = 0;
83024      sqlite3DeleteTable(db, pSelTab);
83025      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
83026      pTable->pSchema->flags |= DB_UnresetViews;
83027    }else{
83028      pTable->nCol = 0;
83029      nErr++;
83030    }
83031    sqlite3SelectDelete(db, pSel);
83032  } else {
83033    nErr++;
83034  }
83035#endif /* SQLITE_OMIT_VIEW */
83036  return nErr;
83037}
83038#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
83039
83040#ifndef SQLITE_OMIT_VIEW
83041/*
83042** Clear the column names from every VIEW in database idx.
83043*/
83044static void sqliteViewResetAll(sqlite3 *db, int idx){
83045  HashElem *i;
83046  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
83047  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
83048  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
83049    Table *pTab = sqliteHashData(i);
83050    if( pTab->pSelect ){
83051      sqliteDeleteColumnNames(db, pTab);
83052      pTab->aCol = 0;
83053      pTab->nCol = 0;
83054    }
83055  }
83056  DbClearProperty(db, idx, DB_UnresetViews);
83057}
83058#else
83059# define sqliteViewResetAll(A,B)
83060#endif /* SQLITE_OMIT_VIEW */
83061
83062/*
83063** This function is called by the VDBE to adjust the internal schema
83064** used by SQLite when the btree layer moves a table root page. The
83065** root-page of a table or index in database iDb has changed from iFrom
83066** to iTo.
83067**
83068** Ticket #1728:  The symbol table might still contain information
83069** on tables and/or indices that are the process of being deleted.
83070** If you are unlucky, one of those deleted indices or tables might
83071** have the same rootpage number as the real table or index that is
83072** being moved.  So we cannot stop searching after the first match
83073** because the first match might be for one of the deleted indices
83074** or tables and not the table/index that is actually being moved.
83075** We must continue looping until all tables and indices with
83076** rootpage==iFrom have been converted to have a rootpage of iTo
83077** in order to be certain that we got the right one.
83078*/
83079#ifndef SQLITE_OMIT_AUTOVACUUM
83080SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
83081  HashElem *pElem;
83082  Hash *pHash;
83083  Db *pDb;
83084
83085  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83086  pDb = &db->aDb[iDb];
83087  pHash = &pDb->pSchema->tblHash;
83088  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
83089    Table *pTab = sqliteHashData(pElem);
83090    if( pTab->tnum==iFrom ){
83091      pTab->tnum = iTo;
83092    }
83093  }
83094  pHash = &pDb->pSchema->idxHash;
83095  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
83096    Index *pIdx = sqliteHashData(pElem);
83097    if( pIdx->tnum==iFrom ){
83098      pIdx->tnum = iTo;
83099    }
83100  }
83101}
83102#endif
83103
83104/*
83105** Write code to erase the table with root-page iTable from database iDb.
83106** Also write code to modify the sqlite_master table and internal schema
83107** if a root-page of another table is moved by the btree-layer whilst
83108** erasing iTable (this can happen with an auto-vacuum database).
83109*/
83110static void destroyRootPage(Parse *pParse, int iTable, int iDb){
83111  Vdbe *v = sqlite3GetVdbe(pParse);
83112  int r1 = sqlite3GetTempReg(pParse);
83113  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
83114  sqlite3MayAbort(pParse);
83115#ifndef SQLITE_OMIT_AUTOVACUUM
83116  /* OP_Destroy stores an in integer r1. If this integer
83117  ** is non-zero, then it is the root page number of a table moved to
83118  ** location iTable. The following code modifies the sqlite_master table to
83119  ** reflect this.
83120  **
83121  ** The "#NNN" in the SQL is a special constant that means whatever value
83122  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
83123  ** token for additional information.
83124  */
83125  sqlite3NestedParse(pParse,
83126     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
83127     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
83128#endif
83129  sqlite3ReleaseTempReg(pParse, r1);
83130}
83131
83132/*
83133** Write VDBE code to erase table pTab and all associated indices on disk.
83134** Code to update the sqlite_master tables and internal schema definitions
83135** in case a root-page belonging to another table is moved by the btree layer
83136** is also added (this can happen with an auto-vacuum database).
83137*/
83138static void destroyTable(Parse *pParse, Table *pTab){
83139#ifdef SQLITE_OMIT_AUTOVACUUM
83140  Index *pIdx;
83141  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83142  destroyRootPage(pParse, pTab->tnum, iDb);
83143  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83144    destroyRootPage(pParse, pIdx->tnum, iDb);
83145  }
83146#else
83147  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
83148  ** is not defined), then it is important to call OP_Destroy on the
83149  ** table and index root-pages in order, starting with the numerically
83150  ** largest root-page number. This guarantees that none of the root-pages
83151  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
83152  ** following were coded:
83153  **
83154  ** OP_Destroy 4 0
83155  ** ...
83156  ** OP_Destroy 5 0
83157  **
83158  ** and root page 5 happened to be the largest root-page number in the
83159  ** database, then root page 5 would be moved to page 4 by the
83160  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
83161  ** a free-list page.
83162  */
83163  int iTab = pTab->tnum;
83164  int iDestroyed = 0;
83165
83166  while( 1 ){
83167    Index *pIdx;
83168    int iLargest = 0;
83169
83170    if( iDestroyed==0 || iTab<iDestroyed ){
83171      iLargest = iTab;
83172    }
83173    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83174      int iIdx = pIdx->tnum;
83175      assert( pIdx->pSchema==pTab->pSchema );
83176      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
83177        iLargest = iIdx;
83178      }
83179    }
83180    if( iLargest==0 ){
83181      return;
83182    }else{
83183      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83184      destroyRootPage(pParse, iLargest, iDb);
83185      iDestroyed = iLargest;
83186    }
83187  }
83188#endif
83189}
83190
83191/*
83192** Remove entries from the sqlite_statN tables (for N in (1,2,3))
83193** after a DROP INDEX or DROP TABLE command.
83194*/
83195static void sqlite3ClearStatTables(
83196  Parse *pParse,         /* The parsing context */
83197  int iDb,               /* The database number */
83198  const char *zType,     /* "idx" or "tbl" */
83199  const char *zName      /* Name of index or table */
83200){
83201  int i;
83202  const char *zDbName = pParse->db->aDb[iDb].zName;
83203  for(i=1; i<=3; i++){
83204    char zTab[24];
83205    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
83206    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
83207      sqlite3NestedParse(pParse,
83208        "DELETE FROM %Q.%s WHERE %s=%Q",
83209        zDbName, zTab, zType, zName
83210      );
83211    }
83212  }
83213}
83214
83215/*
83216** Generate code to drop a table.
83217*/
83218SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
83219  Vdbe *v;
83220  sqlite3 *db = pParse->db;
83221  Trigger *pTrigger;
83222  Db *pDb = &db->aDb[iDb];
83223
83224  v = sqlite3GetVdbe(pParse);
83225  assert( v!=0 );
83226  sqlite3BeginWriteOperation(pParse, 1, iDb);
83227
83228#ifndef SQLITE_OMIT_VIRTUALTABLE
83229  if( IsVirtual(pTab) ){
83230    sqlite3VdbeAddOp0(v, OP_VBegin);
83231  }
83232#endif
83233
83234  /* Drop all triggers associated with the table being dropped. Code
83235  ** is generated to remove entries from sqlite_master and/or
83236  ** sqlite_temp_master if required.
83237  */
83238  pTrigger = sqlite3TriggerList(pParse, pTab);
83239  while( pTrigger ){
83240    assert( pTrigger->pSchema==pTab->pSchema ||
83241        pTrigger->pSchema==db->aDb[1].pSchema );
83242    sqlite3DropTriggerPtr(pParse, pTrigger);
83243    pTrigger = pTrigger->pNext;
83244  }
83245
83246#ifndef SQLITE_OMIT_AUTOINCREMENT
83247  /* Remove any entries of the sqlite_sequence table associated with
83248  ** the table being dropped. This is done before the table is dropped
83249  ** at the btree level, in case the sqlite_sequence table needs to
83250  ** move as a result of the drop (can happen in auto-vacuum mode).
83251  */
83252  if( pTab->tabFlags & TF_Autoincrement ){
83253    sqlite3NestedParse(pParse,
83254      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
83255      pDb->zName, pTab->zName
83256    );
83257  }
83258#endif
83259
83260  /* Drop all SQLITE_MASTER table and index entries that refer to the
83261  ** table. The program name loops through the master table and deletes
83262  ** every row that refers to a table of the same name as the one being
83263  ** dropped. Triggers are handled seperately because a trigger can be
83264  ** created in the temp database that refers to a table in another
83265  ** database.
83266  */
83267  sqlite3NestedParse(pParse,
83268      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
83269      pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
83270  if( !isView && !IsVirtual(pTab) ){
83271    destroyTable(pParse, pTab);
83272  }
83273
83274  /* Remove the table entry from SQLite's internal schema and modify
83275  ** the schema cookie.
83276  */
83277  if( IsVirtual(pTab) ){
83278    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
83279  }
83280  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
83281  sqlite3ChangeCookie(pParse, iDb);
83282  sqliteViewResetAll(db, iDb);
83283}
83284
83285/*
83286** This routine is called to do the work of a DROP TABLE statement.
83287** pName is the name of the table to be dropped.
83288*/
83289SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
83290  Table *pTab;
83291  Vdbe *v;
83292  sqlite3 *db = pParse->db;
83293  int iDb;
83294
83295  if( db->mallocFailed ){
83296    goto exit_drop_table;
83297  }
83298  assert( pParse->nErr==0 );
83299  assert( pName->nSrc==1 );
83300  if( noErr ) db->suppressErr++;
83301  pTab = sqlite3LocateTable(pParse, isView,
83302                            pName->a[0].zName, pName->a[0].zDatabase);
83303  if( noErr ) db->suppressErr--;
83304
83305  if( pTab==0 ){
83306    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
83307    goto exit_drop_table;
83308  }
83309  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83310  assert( iDb>=0 && iDb<db->nDb );
83311
83312  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
83313  ** it is initialized.
83314  */
83315  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
83316    goto exit_drop_table;
83317  }
83318#ifndef SQLITE_OMIT_AUTHORIZATION
83319  {
83320    int code;
83321    const char *zTab = SCHEMA_TABLE(iDb);
83322    const char *zDb = db->aDb[iDb].zName;
83323    const char *zArg2 = 0;
83324    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
83325      goto exit_drop_table;
83326    }
83327    if( isView ){
83328      if( !OMIT_TEMPDB && iDb==1 ){
83329        code = SQLITE_DROP_TEMP_VIEW;
83330      }else{
83331        code = SQLITE_DROP_VIEW;
83332      }
83333#ifndef SQLITE_OMIT_VIRTUALTABLE
83334    }else if( IsVirtual(pTab) ){
83335      code = SQLITE_DROP_VTABLE;
83336      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
83337#endif
83338    }else{
83339      if( !OMIT_TEMPDB && iDb==1 ){
83340        code = SQLITE_DROP_TEMP_TABLE;
83341      }else{
83342        code = SQLITE_DROP_TABLE;
83343      }
83344    }
83345    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
83346      goto exit_drop_table;
83347    }
83348    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
83349      goto exit_drop_table;
83350    }
83351  }
83352#endif
83353  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
83354    && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
83355    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
83356    goto exit_drop_table;
83357  }
83358
83359#ifndef SQLITE_OMIT_VIEW
83360  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
83361  ** on a table.
83362  */
83363  if( isView && pTab->pSelect==0 ){
83364    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
83365    goto exit_drop_table;
83366  }
83367  if( !isView && pTab->pSelect ){
83368    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
83369    goto exit_drop_table;
83370  }
83371#endif
83372
83373  /* Generate code to remove the table from the master table
83374  ** on disk.
83375  */
83376  v = sqlite3GetVdbe(pParse);
83377  if( v ){
83378    sqlite3BeginWriteOperation(pParse, 1, iDb);
83379    sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
83380    sqlite3FkDropTable(pParse, pName, pTab);
83381    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
83382  }
83383
83384exit_drop_table:
83385  sqlite3SrcListDelete(db, pName);
83386}
83387
83388/*
83389** This routine is called to create a new foreign key on the table
83390** currently under construction.  pFromCol determines which columns
83391** in the current table point to the foreign key.  If pFromCol==0 then
83392** connect the key to the last column inserted.  pTo is the name of
83393** the table referred to.  pToCol is a list of tables in the other
83394** pTo table that the foreign key points to.  flags contains all
83395** information about the conflict resolution algorithms specified
83396** in the ON DELETE, ON UPDATE and ON INSERT clauses.
83397**
83398** An FKey structure is created and added to the table currently
83399** under construction in the pParse->pNewTable field.
83400**
83401** The foreign key is set for IMMEDIATE processing.  A subsequent call
83402** to sqlite3DeferForeignKey() might change this to DEFERRED.
83403*/
83404SQLITE_PRIVATE void sqlite3CreateForeignKey(
83405  Parse *pParse,       /* Parsing context */
83406  ExprList *pFromCol,  /* Columns in this table that point to other table */
83407  Token *pTo,          /* Name of the other table */
83408  ExprList *pToCol,    /* Columns in the other table */
83409  int flags            /* Conflict resolution algorithms. */
83410){
83411  sqlite3 *db = pParse->db;
83412#ifndef SQLITE_OMIT_FOREIGN_KEY
83413  FKey *pFKey = 0;
83414  FKey *pNextTo;
83415  Table *p = pParse->pNewTable;
83416  int nByte;
83417  int i;
83418  int nCol;
83419  char *z;
83420
83421  assert( pTo!=0 );
83422  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
83423  if( pFromCol==0 ){
83424    int iCol = p->nCol-1;
83425    if( NEVER(iCol<0) ) goto fk_end;
83426    if( pToCol && pToCol->nExpr!=1 ){
83427      sqlite3ErrorMsg(pParse, "foreign key on %s"
83428         " should reference only one column of table %T",
83429         p->aCol[iCol].zName, pTo);
83430      goto fk_end;
83431    }
83432    nCol = 1;
83433  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
83434    sqlite3ErrorMsg(pParse,
83435        "number of columns in foreign key does not match the number of "
83436        "columns in the referenced table");
83437    goto fk_end;
83438  }else{
83439    nCol = pFromCol->nExpr;
83440  }
83441  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
83442  if( pToCol ){
83443    for(i=0; i<pToCol->nExpr; i++){
83444      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
83445    }
83446  }
83447  pFKey = sqlite3DbMallocZero(db, nByte );
83448  if( pFKey==0 ){
83449    goto fk_end;
83450  }
83451  pFKey->pFrom = p;
83452  pFKey->pNextFrom = p->pFKey;
83453  z = (char*)&pFKey->aCol[nCol];
83454  pFKey->zTo = z;
83455  memcpy(z, pTo->z, pTo->n);
83456  z[pTo->n] = 0;
83457  sqlite3Dequote(z);
83458  z += pTo->n+1;
83459  pFKey->nCol = nCol;
83460  if( pFromCol==0 ){
83461    pFKey->aCol[0].iFrom = p->nCol-1;
83462  }else{
83463    for(i=0; i<nCol; i++){
83464      int j;
83465      for(j=0; j<p->nCol; j++){
83466        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
83467          pFKey->aCol[i].iFrom = j;
83468          break;
83469        }
83470      }
83471      if( j>=p->nCol ){
83472        sqlite3ErrorMsg(pParse,
83473          "unknown column \"%s\" in foreign key definition",
83474          pFromCol->a[i].zName);
83475        goto fk_end;
83476      }
83477    }
83478  }
83479  if( pToCol ){
83480    for(i=0; i<nCol; i++){
83481      int n = sqlite3Strlen30(pToCol->a[i].zName);
83482      pFKey->aCol[i].zCol = z;
83483      memcpy(z, pToCol->a[i].zName, n);
83484      z[n] = 0;
83485      z += n+1;
83486    }
83487  }
83488  pFKey->isDeferred = 0;
83489  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
83490  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
83491
83492  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
83493  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
83494      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
83495  );
83496  if( pNextTo==pFKey ){
83497    db->mallocFailed = 1;
83498    goto fk_end;
83499  }
83500  if( pNextTo ){
83501    assert( pNextTo->pPrevTo==0 );
83502    pFKey->pNextTo = pNextTo;
83503    pNextTo->pPrevTo = pFKey;
83504  }
83505
83506  /* Link the foreign key to the table as the last step.
83507  */
83508  p->pFKey = pFKey;
83509  pFKey = 0;
83510
83511fk_end:
83512  sqlite3DbFree(db, pFKey);
83513#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
83514  sqlite3ExprListDelete(db, pFromCol);
83515  sqlite3ExprListDelete(db, pToCol);
83516}
83517
83518/*
83519** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
83520** clause is seen as part of a foreign key definition.  The isDeferred
83521** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
83522** The behavior of the most recently created foreign key is adjusted
83523** accordingly.
83524*/
83525SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
83526#ifndef SQLITE_OMIT_FOREIGN_KEY
83527  Table *pTab;
83528  FKey *pFKey;
83529  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
83530  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
83531  pFKey->isDeferred = (u8)isDeferred;
83532#endif
83533}
83534
83535/*
83536** Generate code that will erase and refill index *pIdx.  This is
83537** used to initialize a newly created index or to recompute the
83538** content of an index in response to a REINDEX command.
83539**
83540** if memRootPage is not negative, it means that the index is newly
83541** created.  The register specified by memRootPage contains the
83542** root page number of the index.  If memRootPage is negative, then
83543** the index already exists and must be cleared before being refilled and
83544** the root page number of the index is taken from pIndex->tnum.
83545*/
83546static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
83547  Table *pTab = pIndex->pTable;  /* The table that is indexed */
83548  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
83549  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
83550  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
83551  int addr1;                     /* Address of top of loop */
83552  int addr2;                     /* Address to jump to for next iteration */
83553  int tnum;                      /* Root page of index */
83554  Vdbe *v;                       /* Generate code into this virtual machine */
83555  KeyInfo *pKey;                 /* KeyInfo for index */
83556#ifdef SQLITE_OMIT_MERGE_SORT
83557  int regIdxKey;                 /* Registers containing the index key */
83558#endif
83559  int regRecord;                 /* Register holding assemblied index record */
83560  sqlite3 *db = pParse->db;      /* The database connection */
83561  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
83562
83563#ifndef SQLITE_OMIT_AUTHORIZATION
83564  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
83565      db->aDb[iDb].zName ) ){
83566    return;
83567  }
83568#endif
83569
83570  /* Require a write-lock on the table to perform this operation */
83571  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
83572
83573  v = sqlite3GetVdbe(pParse);
83574  if( v==0 ) return;
83575  if( memRootPage>=0 ){
83576    tnum = memRootPage;
83577  }else{
83578    tnum = pIndex->tnum;
83579    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
83580  }
83581  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
83582  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
83583                    (char *)pKey, P4_KEYINFO_HANDOFF);
83584  if( memRootPage>=0 ){
83585    sqlite3VdbeChangeP5(v, 1);
83586  }
83587
83588#ifndef SQLITE_OMIT_MERGE_SORT
83589  /* Open the sorter cursor if we are to use one. */
83590  iSorter = pParse->nTab++;
83591  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
83592#else
83593  iSorter = iTab;
83594#endif
83595
83596  /* Open the table. Loop through all rows of the table, inserting index
83597  ** records into the sorter. */
83598  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
83599  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
83600  regRecord = sqlite3GetTempReg(pParse);
83601
83602#ifndef SQLITE_OMIT_MERGE_SORT
83603  sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83604  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
83605  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
83606  sqlite3VdbeJumpHere(v, addr1);
83607  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
83608  if( pIndex->onError!=OE_None ){
83609    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
83610    sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
83611    addr2 = sqlite3VdbeCurrentAddr(v);
83612    sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
83613    sqlite3HaltConstraint(
83614        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
83615    );
83616  }else{
83617    addr2 = sqlite3VdbeCurrentAddr(v);
83618  }
83619  sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
83620  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
83621  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83622#else
83623  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83624  addr2 = addr1 + 1;
83625  if( pIndex->onError!=OE_None ){
83626    const int regRowid = regIdxKey + pIndex->nColumn;
83627    const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
83628    void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
83629
83630    /* The registers accessed by the OP_IsUnique opcode were allocated
83631    ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
83632    ** call above. Just before that function was freed they were released
83633    ** (made available to the compiler for reuse) using
83634    ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
83635    ** opcode use the values stored within seems dangerous. However, since
83636    ** we can be sure that no other temp registers have been allocated
83637    ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
83638    */
83639    sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
83640    sqlite3HaltConstraint(
83641        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
83642  }
83643  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
83644  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83645#endif
83646  sqlite3ReleaseTempReg(pParse, regRecord);
83647  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
83648  sqlite3VdbeJumpHere(v, addr1);
83649
83650  sqlite3VdbeAddOp1(v, OP_Close, iTab);
83651  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
83652  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
83653}
83654
83655/*
83656** Create a new index for an SQL table.  pName1.pName2 is the name of the index
83657** and pTblList is the name of the table that is to be indexed.  Both will
83658** be NULL for a primary key or an index that is created to satisfy a
83659** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
83660** as the table to be indexed.  pParse->pNewTable is a table that is
83661** currently being constructed by a CREATE TABLE statement.
83662**
83663** pList is a list of columns to be indexed.  pList will be NULL if this
83664** is a primary key or unique-constraint on the most recent column added
83665** to the table currently under construction.
83666**
83667** If the index is created successfully, return a pointer to the new Index
83668** structure. This is used by sqlite3AddPrimaryKey() to mark the index
83669** as the tables primary key (Index.autoIndex==2).
83670*/
83671SQLITE_PRIVATE Index *sqlite3CreateIndex(
83672  Parse *pParse,     /* All information about this parse */
83673  Token *pName1,     /* First part of index name. May be NULL */
83674  Token *pName2,     /* Second part of index name. May be NULL */
83675  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
83676  ExprList *pList,   /* A list of columns to be indexed */
83677  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
83678  Token *pStart,     /* The CREATE token that begins this statement */
83679  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
83680  int sortOrder,     /* Sort order of primary key when pList==NULL */
83681  int ifNotExist     /* Omit error if index already exists */
83682){
83683  Index *pRet = 0;     /* Pointer to return */
83684  Table *pTab = 0;     /* Table to be indexed */
83685  Index *pIndex = 0;   /* The index to be created */
83686  char *zName = 0;     /* Name of the index */
83687  int nName;           /* Number of characters in zName */
83688  int i, j;
83689  Token nullId;        /* Fake token for an empty ID list */
83690  DbFixer sFix;        /* For assigning database names to pTable */
83691  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
83692  sqlite3 *db = pParse->db;
83693  Db *pDb;             /* The specific table containing the indexed database */
83694  int iDb;             /* Index of the database that is being written */
83695  Token *pName = 0;    /* Unqualified name of the index to create */
83696  struct ExprList_item *pListItem; /* For looping over pList */
83697  int nCol;
83698  int nExtra = 0;
83699  char *zExtra;
83700
83701  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
83702  assert( pParse->nErr==0 );      /* Never called with prior errors */
83703  if( db->mallocFailed || IN_DECLARE_VTAB ){
83704    goto exit_create_index;
83705  }
83706  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83707    goto exit_create_index;
83708  }
83709
83710  /*
83711  ** Find the table that is to be indexed.  Return early if not found.
83712  */
83713  if( pTblName!=0 ){
83714
83715    /* Use the two-part index name to determine the database
83716    ** to search for the table. 'Fix' the table name to this db
83717    ** before looking up the table.
83718    */
83719    assert( pName1 && pName2 );
83720    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83721    if( iDb<0 ) goto exit_create_index;
83722    assert( pName && pName->z );
83723
83724#ifndef SQLITE_OMIT_TEMPDB
83725    /* If the index name was unqualified, check if the the table
83726    ** is a temp table. If so, set the database to 1. Do not do this
83727    ** if initialising a database schema.
83728    */
83729    if( !db->init.busy ){
83730      pTab = sqlite3SrcListLookup(pParse, pTblName);
83731      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83732        iDb = 1;
83733      }
83734    }
83735#endif
83736
83737    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
83738        sqlite3FixSrcList(&sFix, pTblName)
83739    ){
83740      /* Because the parser constructs pTblName from a single identifier,
83741      ** sqlite3FixSrcList can never fail. */
83742      assert(0);
83743    }
83744    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
83745        pTblName->a[0].zDatabase);
83746    if( !pTab || db->mallocFailed ) goto exit_create_index;
83747    assert( db->aDb[iDb].pSchema==pTab->pSchema );
83748  }else{
83749    assert( pName==0 );
83750    assert( pStart==0 );
83751    pTab = pParse->pNewTable;
83752    if( !pTab ) goto exit_create_index;
83753    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83754  }
83755  pDb = &db->aDb[iDb];
83756
83757  assert( pTab!=0 );
83758  assert( pParse->nErr==0 );
83759  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
83760       && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
83761    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
83762    goto exit_create_index;
83763  }
83764#ifndef SQLITE_OMIT_VIEW
83765  if( pTab->pSelect ){
83766    sqlite3ErrorMsg(pParse, "views may not be indexed");
83767    goto exit_create_index;
83768  }
83769#endif
83770#ifndef SQLITE_OMIT_VIRTUALTABLE
83771  if( IsVirtual(pTab) ){
83772    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
83773    goto exit_create_index;
83774  }
83775#endif
83776
83777  /*
83778  ** Find the name of the index.  Make sure there is not already another
83779  ** index or table with the same name.
83780  **
83781  ** Exception:  If we are reading the names of permanent indices from the
83782  ** sqlite_master table (because some other process changed the schema) and
83783  ** one of the index names collides with the name of a temporary table or
83784  ** index, then we will continue to process this index.
83785  **
83786  ** If pName==0 it means that we are
83787  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
83788  ** own name.
83789  */
83790  if( pName ){
83791    zName = sqlite3NameFromToken(db, pName);
83792    if( zName==0 ) goto exit_create_index;
83793    assert( pName->z!=0 );
83794    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83795      goto exit_create_index;
83796    }
83797    if( !db->init.busy ){
83798      if( sqlite3FindTable(db, zName, 0)!=0 ){
83799        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
83800        goto exit_create_index;
83801      }
83802    }
83803    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
83804      if( !ifNotExist ){
83805        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
83806      }else{
83807        assert( !db->init.busy );
83808        sqlite3CodeVerifySchema(pParse, iDb);
83809      }
83810      goto exit_create_index;
83811    }
83812  }else{
83813    int n;
83814    Index *pLoop;
83815    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
83816    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
83817    if( zName==0 ){
83818      goto exit_create_index;
83819    }
83820  }
83821
83822  /* Check for authorization to create an index.
83823  */
83824#ifndef SQLITE_OMIT_AUTHORIZATION
83825  {
83826    const char *zDb = pDb->zName;
83827    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
83828      goto exit_create_index;
83829    }
83830    i = SQLITE_CREATE_INDEX;
83831    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
83832    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
83833      goto exit_create_index;
83834    }
83835  }
83836#endif
83837
83838  /* If pList==0, it means this routine was called to make a primary
83839  ** key out of the last column added to the table under construction.
83840  ** So create a fake list to simulate this.
83841  */
83842  if( pList==0 ){
83843    nullId.z = pTab->aCol[pTab->nCol-1].zName;
83844    nullId.n = sqlite3Strlen30((char*)nullId.z);
83845    pList = sqlite3ExprListAppend(pParse, 0, 0);
83846    if( pList==0 ) goto exit_create_index;
83847    sqlite3ExprListSetName(pParse, pList, &nullId, 0);
83848    pList->a[0].sortOrder = (u8)sortOrder;
83849  }
83850
83851  /* Figure out how many bytes of space are required to store explicitly
83852  ** specified collation sequence names.
83853  */
83854  for(i=0; i<pList->nExpr; i++){
83855    Expr *pExpr = pList->a[i].pExpr;
83856    if( pExpr ){
83857      CollSeq *pColl = pExpr->pColl;
83858      /* Either pColl!=0 or there was an OOM failure.  But if an OOM
83859      ** failure we have quit before reaching this point. */
83860      if( ALWAYS(pColl) ){
83861        nExtra += (1 + sqlite3Strlen30(pColl->zName));
83862      }
83863    }
83864  }
83865
83866  /*
83867  ** Allocate the index structure.
83868  */
83869  nName = sqlite3Strlen30(zName);
83870  nCol = pList->nExpr;
83871  pIndex = sqlite3DbMallocZero(db,
83872      ROUND8(sizeof(Index)) +              /* Index structure  */
83873      ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
83874      sizeof(char *)*nCol +                /* Index.azColl     */
83875      sizeof(int)*nCol +                   /* Index.aiColumn   */
83876      sizeof(u8)*nCol +                    /* Index.aSortOrder */
83877      nName + 1 +                          /* Index.zName      */
83878      nExtra                               /* Collation sequence names */
83879  );
83880  if( db->mallocFailed ){
83881    goto exit_create_index;
83882  }
83883  zExtra = (char*)pIndex;
83884  pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
83885  pIndex->azColl = (char**)
83886     ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
83887  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
83888  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
83889  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
83890  pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
83891  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
83892  zExtra = (char *)(&pIndex->zName[nName+1]);
83893  memcpy(pIndex->zName, zName, nName+1);
83894  pIndex->pTable = pTab;
83895  pIndex->nColumn = pList->nExpr;
83896  pIndex->onError = (u8)onError;
83897  pIndex->autoIndex = (u8)(pName==0);
83898  pIndex->pSchema = db->aDb[iDb].pSchema;
83899  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83900
83901  /* Check to see if we should honor DESC requests on index columns
83902  */
83903  if( pDb->pSchema->file_format>=4 ){
83904    sortOrderMask = -1;   /* Honor DESC */
83905  }else{
83906    sortOrderMask = 0;    /* Ignore DESC */
83907  }
83908
83909  /* Scan the names of the columns of the table to be indexed and
83910  ** load the column indices into the Index structure.  Report an error
83911  ** if any column is not found.
83912  **
83913  ** TODO:  Add a test to make sure that the same column is not named
83914  ** more than once within the same index.  Only the first instance of
83915  ** the column will ever be used by the optimizer.  Note that using the
83916  ** same column more than once cannot be an error because that would
83917  ** break backwards compatibility - it needs to be a warning.
83918  */
83919  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
83920    const char *zColName = pListItem->zName;
83921    Column *pTabCol;
83922    int requestedSortOrder;
83923    char *zColl;                   /* Collation sequence name */
83924
83925    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
83926      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
83927    }
83928    if( j>=pTab->nCol ){
83929      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
83930        pTab->zName, zColName);
83931      pParse->checkSchema = 1;
83932      goto exit_create_index;
83933    }
83934    pIndex->aiColumn[i] = j;
83935    /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
83936    ** the way the "idxlist" non-terminal is constructed by the parser,
83937    ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
83938    ** must exist or else there must have been an OOM error.  But if there
83939    ** was an OOM error, we would never reach this point. */
83940    if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
83941      int nColl;
83942      zColl = pListItem->pExpr->pColl->zName;
83943      nColl = sqlite3Strlen30(zColl) + 1;
83944      assert( nExtra>=nColl );
83945      memcpy(zExtra, zColl, nColl);
83946      zColl = zExtra;
83947      zExtra += nColl;
83948      nExtra -= nColl;
83949    }else{
83950      zColl = pTab->aCol[j].zColl;
83951      if( !zColl ){
83952        zColl = db->pDfltColl->zName;
83953      }
83954    }
83955    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
83956      goto exit_create_index;
83957    }
83958    pIndex->azColl[i] = zColl;
83959    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
83960    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
83961  }
83962  sqlite3DefaultRowEst(pIndex);
83963
83964  if( pTab==pParse->pNewTable ){
83965    /* This routine has been called to create an automatic index as a
83966    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
83967    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
83968    ** i.e. one of:
83969    **
83970    ** CREATE TABLE t(x PRIMARY KEY, y);
83971    ** CREATE TABLE t(x, y, UNIQUE(x, y));
83972    **
83973    ** Either way, check to see if the table already has such an index. If
83974    ** so, don't bother creating this one. This only applies to
83975    ** automatically created indices. Users can do as they wish with
83976    ** explicit indices.
83977    **
83978    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
83979    ** (and thus suppressing the second one) even if they have different
83980    ** sort orders.
83981    **
83982    ** If there are different collating sequences or if the columns of
83983    ** the constraint occur in different orders, then the constraints are
83984    ** considered distinct and both result in separate indices.
83985    */
83986    Index *pIdx;
83987    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83988      int k;
83989      assert( pIdx->onError!=OE_None );
83990      assert( pIdx->autoIndex );
83991      assert( pIndex->onError!=OE_None );
83992
83993      if( pIdx->nColumn!=pIndex->nColumn ) continue;
83994      for(k=0; k<pIdx->nColumn; k++){
83995        const char *z1;
83996        const char *z2;
83997        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
83998        z1 = pIdx->azColl[k];
83999        z2 = pIndex->azColl[k];
84000        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
84001      }
84002      if( k==pIdx->nColumn ){
84003        if( pIdx->onError!=pIndex->onError ){
84004          /* This constraint creates the same index as a previous
84005          ** constraint specified somewhere in the CREATE TABLE statement.
84006          ** However the ON CONFLICT clauses are different. If both this
84007          ** constraint and the previous equivalent constraint have explicit
84008          ** ON CONFLICT clauses this is an error. Otherwise, use the
84009          ** explicitly specified behaviour for the index.
84010          */
84011          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
84012            sqlite3ErrorMsg(pParse,
84013                "conflicting ON CONFLICT clauses specified", 0);
84014          }
84015          if( pIdx->onError==OE_Default ){
84016            pIdx->onError = pIndex->onError;
84017          }
84018        }
84019        goto exit_create_index;
84020      }
84021    }
84022  }
84023
84024  /* Link the new Index structure to its table and to the other
84025  ** in-memory database structures.
84026  */
84027  if( db->init.busy ){
84028    Index *p;
84029    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
84030    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
84031                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
84032                          pIndex);
84033    if( p ){
84034      assert( p==pIndex );  /* Malloc must have failed */
84035      db->mallocFailed = 1;
84036      goto exit_create_index;
84037    }
84038    db->flags |= SQLITE_InternChanges;
84039    if( pTblName!=0 ){
84040      pIndex->tnum = db->init.newTnum;
84041    }
84042  }
84043
84044  /* If the db->init.busy is 0 then create the index on disk.  This
84045  ** involves writing the index into the master table and filling in the
84046  ** index with the current table contents.
84047  **
84048  ** The db->init.busy is 0 when the user first enters a CREATE INDEX
84049  ** command.  db->init.busy is 1 when a database is opened and
84050  ** CREATE INDEX statements are read out of the master table.  In
84051  ** the latter case the index already exists on disk, which is why
84052  ** we don't want to recreate it.
84053  **
84054  ** If pTblName==0 it means this index is generated as a primary key
84055  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
84056  ** has just been created, it contains no data and the index initialization
84057  ** step can be skipped.
84058  */
84059  else{ /* if( db->init.busy==0 ) */
84060    Vdbe *v;
84061    char *zStmt;
84062    int iMem = ++pParse->nMem;
84063
84064    v = sqlite3GetVdbe(pParse);
84065    if( v==0 ) goto exit_create_index;
84066
84067
84068    /* Create the rootpage for the index
84069    */
84070    sqlite3BeginWriteOperation(pParse, 1, iDb);
84071    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
84072
84073    /* Gather the complete text of the CREATE INDEX statement into
84074    ** the zStmt variable
84075    */
84076    if( pStart ){
84077      assert( pEnd!=0 );
84078      /* A named index with an explicit CREATE INDEX statement */
84079      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
84080        onError==OE_None ? "" : " UNIQUE",
84081        (int)(pEnd->z - pName->z) + 1,
84082        pName->z);
84083    }else{
84084      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
84085      /* zStmt = sqlite3MPrintf(""); */
84086      zStmt = 0;
84087    }
84088
84089    /* Add an entry in sqlite_master for this index
84090    */
84091    sqlite3NestedParse(pParse,
84092        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
84093        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
84094        pIndex->zName,
84095        pTab->zName,
84096        iMem,
84097        zStmt
84098    );
84099    sqlite3DbFree(db, zStmt);
84100
84101    /* Fill the index with data and reparse the schema. Code an OP_Expire
84102    ** to invalidate all pre-compiled statements.
84103    */
84104    if( pTblName ){
84105      sqlite3RefillIndex(pParse, pIndex, iMem);
84106      sqlite3ChangeCookie(pParse, iDb);
84107      sqlite3VdbeAddParseSchemaOp(v, iDb,
84108         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
84109      sqlite3VdbeAddOp1(v, OP_Expire, 0);
84110    }
84111  }
84112
84113  /* When adding an index to the list of indices for a table, make
84114  ** sure all indices labeled OE_Replace come after all those labeled
84115  ** OE_Ignore.  This is necessary for the correct constraint check
84116  ** processing (in sqlite3GenerateConstraintChecks()) as part of
84117  ** UPDATE and INSERT statements.
84118  */
84119  if( db->init.busy || pTblName==0 ){
84120    if( onError!=OE_Replace || pTab->pIndex==0
84121         || pTab->pIndex->onError==OE_Replace){
84122      pIndex->pNext = pTab->pIndex;
84123      pTab->pIndex = pIndex;
84124    }else{
84125      Index *pOther = pTab->pIndex;
84126      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
84127        pOther = pOther->pNext;
84128      }
84129      pIndex->pNext = pOther->pNext;
84130      pOther->pNext = pIndex;
84131    }
84132    pRet = pIndex;
84133    pIndex = 0;
84134  }
84135
84136  /* Clean up before exiting */
84137exit_create_index:
84138  if( pIndex ){
84139    sqlite3DbFree(db, pIndex->zColAff);
84140    sqlite3DbFree(db, pIndex);
84141  }
84142  sqlite3ExprListDelete(db, pList);
84143  sqlite3SrcListDelete(db, pTblName);
84144  sqlite3DbFree(db, zName);
84145  return pRet;
84146}
84147
84148/*
84149** Fill the Index.aiRowEst[] array with default information - information
84150** to be used when we have not run the ANALYZE command.
84151**
84152** aiRowEst[0] is suppose to contain the number of elements in the index.
84153** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
84154** number of rows in the table that match any particular value of the
84155** first column of the index.  aiRowEst[2] is an estimate of the number
84156** of rows that match any particular combiniation of the first 2 columns
84157** of the index.  And so forth.  It must always be the case that
84158*
84159**           aiRowEst[N]<=aiRowEst[N-1]
84160**           aiRowEst[N]>=1
84161**
84162** Apart from that, we have little to go on besides intuition as to
84163** how aiRowEst[] should be initialized.  The numbers generated here
84164** are based on typical values found in actual indices.
84165*/
84166SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
84167  tRowcnt *a = pIdx->aiRowEst;
84168  int i;
84169  tRowcnt n;
84170  assert( a!=0 );
84171  a[0] = pIdx->pTable->nRowEst;
84172  if( a[0]<10 ) a[0] = 10;
84173  n = 10;
84174  for(i=1; i<=pIdx->nColumn; i++){
84175    a[i] = n;
84176    if( n>5 ) n--;
84177  }
84178  if( pIdx->onError!=OE_None ){
84179    a[pIdx->nColumn] = 1;
84180  }
84181}
84182
84183/*
84184** This routine will drop an existing named index.  This routine
84185** implements the DROP INDEX statement.
84186*/
84187SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
84188  Index *pIndex;
84189  Vdbe *v;
84190  sqlite3 *db = pParse->db;
84191  int iDb;
84192
84193  assert( pParse->nErr==0 );   /* Never called with prior errors */
84194  if( db->mallocFailed ){
84195    goto exit_drop_index;
84196  }
84197  assert( pName->nSrc==1 );
84198  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84199    goto exit_drop_index;
84200  }
84201  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
84202  if( pIndex==0 ){
84203    if( !ifExists ){
84204      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
84205    }else{
84206      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
84207    }
84208    pParse->checkSchema = 1;
84209    goto exit_drop_index;
84210  }
84211  if( pIndex->autoIndex ){
84212    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
84213      "or PRIMARY KEY constraint cannot be dropped", 0);
84214    goto exit_drop_index;
84215  }
84216  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
84217#ifndef SQLITE_OMIT_AUTHORIZATION
84218  {
84219    int code = SQLITE_DROP_INDEX;
84220    Table *pTab = pIndex->pTable;
84221    const char *zDb = db->aDb[iDb].zName;
84222    const char *zTab = SCHEMA_TABLE(iDb);
84223    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
84224      goto exit_drop_index;
84225    }
84226    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
84227    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
84228      goto exit_drop_index;
84229    }
84230  }
84231#endif
84232
84233  /* Generate code to remove the index and from the master table */
84234  v = sqlite3GetVdbe(pParse);
84235  if( v ){
84236    sqlite3BeginWriteOperation(pParse, 1, iDb);
84237    sqlite3NestedParse(pParse,
84238       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
84239       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
84240    );
84241    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
84242    sqlite3ChangeCookie(pParse, iDb);
84243    destroyRootPage(pParse, pIndex->tnum, iDb);
84244    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
84245  }
84246
84247exit_drop_index:
84248  sqlite3SrcListDelete(db, pName);
84249}
84250
84251/*
84252** pArray is a pointer to an array of objects.  Each object in the
84253** array is szEntry bytes in size.  This routine allocates a new
84254** object on the end of the array.
84255**
84256** *pnEntry is the number of entries already in use.  *pnAlloc is
84257** the previously allocated size of the array.  initSize is the
84258** suggested initial array size allocation.
84259**
84260** The index of the new entry is returned in *pIdx.
84261**
84262** This routine returns a pointer to the array of objects.  This
84263** might be the same as the pArray parameter or it might be a different
84264** pointer if the array was resized.
84265*/
84266SQLITE_PRIVATE void *sqlite3ArrayAllocate(
84267  sqlite3 *db,      /* Connection to notify of malloc failures */
84268  void *pArray,     /* Array of objects.  Might be reallocated */
84269  int szEntry,      /* Size of each object in the array */
84270  int *pnEntry,     /* Number of objects currently in use */
84271  int *pIdx         /* Write the index of a new slot here */
84272){
84273  char *z;
84274  int n = *pnEntry;
84275  if( (n & (n-1))==0 ){
84276    int sz = (n==0) ? 1 : 2*n;
84277    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
84278    if( pNew==0 ){
84279      *pIdx = -1;
84280      return pArray;
84281    }
84282    pArray = pNew;
84283  }
84284  z = (char*)pArray;
84285  memset(&z[n * szEntry], 0, szEntry);
84286  *pIdx = n;
84287  ++*pnEntry;
84288  return pArray;
84289}
84290
84291/*
84292** Append a new element to the given IdList.  Create a new IdList if
84293** need be.
84294**
84295** A new IdList is returned, or NULL if malloc() fails.
84296*/
84297SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
84298  int i;
84299  if( pList==0 ){
84300    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
84301    if( pList==0 ) return 0;
84302  }
84303  pList->a = sqlite3ArrayAllocate(
84304      db,
84305      pList->a,
84306      sizeof(pList->a[0]),
84307      &pList->nId,
84308      &i
84309  );
84310  if( i<0 ){
84311    sqlite3IdListDelete(db, pList);
84312    return 0;
84313  }
84314  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
84315  return pList;
84316}
84317
84318/*
84319** Delete an IdList.
84320*/
84321SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
84322  int i;
84323  if( pList==0 ) return;
84324  for(i=0; i<pList->nId; i++){
84325    sqlite3DbFree(db, pList->a[i].zName);
84326  }
84327  sqlite3DbFree(db, pList->a);
84328  sqlite3DbFree(db, pList);
84329}
84330
84331/*
84332** Return the index in pList of the identifier named zId.  Return -1
84333** if not found.
84334*/
84335SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
84336  int i;
84337  if( pList==0 ) return -1;
84338  for(i=0; i<pList->nId; i++){
84339    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
84340  }
84341  return -1;
84342}
84343
84344/*
84345** Expand the space allocated for the given SrcList object by
84346** creating nExtra new slots beginning at iStart.  iStart is zero based.
84347** New slots are zeroed.
84348**
84349** For example, suppose a SrcList initially contains two entries: A,B.
84350** To append 3 new entries onto the end, do this:
84351**
84352**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
84353**
84354** After the call above it would contain:  A, B, nil, nil, nil.
84355** If the iStart argument had been 1 instead of 2, then the result
84356** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
84357** the iStart value would be 0.  The result then would
84358** be: nil, nil, nil, A, B.
84359**
84360** If a memory allocation fails the SrcList is unchanged.  The
84361** db->mallocFailed flag will be set to true.
84362*/
84363SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
84364  sqlite3 *db,       /* Database connection to notify of OOM errors */
84365  SrcList *pSrc,     /* The SrcList to be enlarged */
84366  int nExtra,        /* Number of new slots to add to pSrc->a[] */
84367  int iStart         /* Index in pSrc->a[] of first new slot */
84368){
84369  int i;
84370
84371  /* Sanity checking on calling parameters */
84372  assert( iStart>=0 );
84373  assert( nExtra>=1 );
84374  assert( pSrc!=0 );
84375  assert( iStart<=pSrc->nSrc );
84376
84377  /* Allocate additional space if needed */
84378  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
84379    SrcList *pNew;
84380    int nAlloc = pSrc->nSrc+nExtra;
84381    int nGot;
84382    pNew = sqlite3DbRealloc(db, pSrc,
84383               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
84384    if( pNew==0 ){
84385      assert( db->mallocFailed );
84386      return pSrc;
84387    }
84388    pSrc = pNew;
84389    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
84390    pSrc->nAlloc = (u16)nGot;
84391  }
84392
84393  /* Move existing slots that come after the newly inserted slots
84394  ** out of the way */
84395  for(i=pSrc->nSrc-1; i>=iStart; i--){
84396    pSrc->a[i+nExtra] = pSrc->a[i];
84397  }
84398  pSrc->nSrc += (i16)nExtra;
84399
84400  /* Zero the newly allocated slots */
84401  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
84402  for(i=iStart; i<iStart+nExtra; i++){
84403    pSrc->a[i].iCursor = -1;
84404  }
84405
84406  /* Return a pointer to the enlarged SrcList */
84407  return pSrc;
84408}
84409
84410
84411/*
84412** Append a new table name to the given SrcList.  Create a new SrcList if
84413** need be.  A new entry is created in the SrcList even if pTable is NULL.
84414**
84415** A SrcList is returned, or NULL if there is an OOM error.  The returned
84416** SrcList might be the same as the SrcList that was input or it might be
84417** a new one.  If an OOM error does occurs, then the prior value of pList
84418** that is input to this routine is automatically freed.
84419**
84420** If pDatabase is not null, it means that the table has an optional
84421** database name prefix.  Like this:  "database.table".  The pDatabase
84422** points to the table name and the pTable points to the database name.
84423** The SrcList.a[].zName field is filled with the table name which might
84424** come from pTable (if pDatabase is NULL) or from pDatabase.
84425** SrcList.a[].zDatabase is filled with the database name from pTable,
84426** or with NULL if no database is specified.
84427**
84428** In other words, if call like this:
84429**
84430**         sqlite3SrcListAppend(D,A,B,0);
84431**
84432** Then B is a table name and the database name is unspecified.  If called
84433** like this:
84434**
84435**         sqlite3SrcListAppend(D,A,B,C);
84436**
84437** Then C is the table name and B is the database name.  If C is defined
84438** then so is B.  In other words, we never have a case where:
84439**
84440**         sqlite3SrcListAppend(D,A,0,C);
84441**
84442** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
84443** before being added to the SrcList.
84444*/
84445SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
84446  sqlite3 *db,        /* Connection to notify of malloc failures */
84447  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
84448  Token *pTable,      /* Table to append */
84449  Token *pDatabase    /* Database of the table */
84450){
84451  struct SrcList_item *pItem;
84452  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
84453  if( pList==0 ){
84454    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
84455    if( pList==0 ) return 0;
84456    pList->nAlloc = 1;
84457  }
84458  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
84459  if( db->mallocFailed ){
84460    sqlite3SrcListDelete(db, pList);
84461    return 0;
84462  }
84463  pItem = &pList->a[pList->nSrc-1];
84464  if( pDatabase && pDatabase->z==0 ){
84465    pDatabase = 0;
84466  }
84467  if( pDatabase ){
84468    Token *pTemp = pDatabase;
84469    pDatabase = pTable;
84470    pTable = pTemp;
84471  }
84472  pItem->zName = sqlite3NameFromToken(db, pTable);
84473  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
84474  return pList;
84475}
84476
84477/*
84478** Assign VdbeCursor index numbers to all tables in a SrcList
84479*/
84480SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
84481  int i;
84482  struct SrcList_item *pItem;
84483  assert(pList || pParse->db->mallocFailed );
84484  if( pList ){
84485    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
84486      if( pItem->iCursor>=0 ) break;
84487      pItem->iCursor = pParse->nTab++;
84488      if( pItem->pSelect ){
84489        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
84490      }
84491    }
84492  }
84493}
84494
84495/*
84496** Delete an entire SrcList including all its substructure.
84497*/
84498SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
84499  int i;
84500  struct SrcList_item *pItem;
84501  if( pList==0 ) return;
84502  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
84503    sqlite3DbFree(db, pItem->zDatabase);
84504    sqlite3DbFree(db, pItem->zName);
84505    sqlite3DbFree(db, pItem->zAlias);
84506    sqlite3DbFree(db, pItem->zIndex);
84507    sqlite3DeleteTable(db, pItem->pTab);
84508    sqlite3SelectDelete(db, pItem->pSelect);
84509    sqlite3ExprDelete(db, pItem->pOn);
84510    sqlite3IdListDelete(db, pItem->pUsing);
84511  }
84512  sqlite3DbFree(db, pList);
84513}
84514
84515/*
84516** This routine is called by the parser to add a new term to the
84517** end of a growing FROM clause.  The "p" parameter is the part of
84518** the FROM clause that has already been constructed.  "p" is NULL
84519** if this is the first term of the FROM clause.  pTable and pDatabase
84520** are the name of the table and database named in the FROM clause term.
84521** pDatabase is NULL if the database name qualifier is missing - the
84522** usual case.  If the term has a alias, then pAlias points to the
84523** alias token.  If the term is a subquery, then pSubquery is the
84524** SELECT statement that the subquery encodes.  The pTable and
84525** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
84526** parameters are the content of the ON and USING clauses.
84527**
84528** Return a new SrcList which encodes is the FROM with the new
84529** term added.
84530*/
84531SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
84532  Parse *pParse,          /* Parsing context */
84533  SrcList *p,             /* The left part of the FROM clause already seen */
84534  Token *pTable,          /* Name of the table to add to the FROM clause */
84535  Token *pDatabase,       /* Name of the database containing pTable */
84536  Token *pAlias,          /* The right-hand side of the AS subexpression */
84537  Select *pSubquery,      /* A subquery used in place of a table name */
84538  Expr *pOn,              /* The ON clause of a join */
84539  IdList *pUsing          /* The USING clause of a join */
84540){
84541  struct SrcList_item *pItem;
84542  sqlite3 *db = pParse->db;
84543  if( !p && (pOn || pUsing) ){
84544    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
84545      (pOn ? "ON" : "USING")
84546    );
84547    goto append_from_error;
84548  }
84549  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
84550  if( p==0 || NEVER(p->nSrc==0) ){
84551    goto append_from_error;
84552  }
84553  pItem = &p->a[p->nSrc-1];
84554  assert( pAlias!=0 );
84555  if( pAlias->n ){
84556    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
84557  }
84558  pItem->pSelect = pSubquery;
84559  pItem->pOn = pOn;
84560  pItem->pUsing = pUsing;
84561  return p;
84562
84563 append_from_error:
84564  assert( p==0 );
84565  sqlite3ExprDelete(db, pOn);
84566  sqlite3IdListDelete(db, pUsing);
84567  sqlite3SelectDelete(db, pSubquery);
84568  return 0;
84569}
84570
84571/*
84572** Add an INDEXED BY or NOT INDEXED clause to the most recently added
84573** element of the source-list passed as the second argument.
84574*/
84575SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
84576  assert( pIndexedBy!=0 );
84577  if( p && ALWAYS(p->nSrc>0) ){
84578    struct SrcList_item *pItem = &p->a[p->nSrc-1];
84579    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
84580    if( pIndexedBy->n==1 && !pIndexedBy->z ){
84581      /* A "NOT INDEXED" clause was supplied. See parse.y
84582      ** construct "indexed_opt" for details. */
84583      pItem->notIndexed = 1;
84584    }else{
84585      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
84586    }
84587  }
84588}
84589
84590/*
84591** When building up a FROM clause in the parser, the join operator
84592** is initially attached to the left operand.  But the code generator
84593** expects the join operator to be on the right operand.  This routine
84594** Shifts all join operators from left to right for an entire FROM
84595** clause.
84596**
84597** Example: Suppose the join is like this:
84598**
84599**           A natural cross join B
84600**
84601** The operator is "natural cross join".  The A and B operands are stored
84602** in p->a[0] and p->a[1], respectively.  The parser initially stores the
84603** operator with A.  This routine shifts that operator over to B.
84604*/
84605SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
84606  if( p ){
84607    int i;
84608    assert( p->a || p->nSrc==0 );
84609    for(i=p->nSrc-1; i>0; i--){
84610      p->a[i].jointype = p->a[i-1].jointype;
84611    }
84612    p->a[0].jointype = 0;
84613  }
84614}
84615
84616/*
84617** Begin a transaction
84618*/
84619SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
84620  sqlite3 *db;
84621  Vdbe *v;
84622  int i;
84623
84624  assert( pParse!=0 );
84625  db = pParse->db;
84626  assert( db!=0 );
84627/*  if( db->aDb[0].pBt==0 ) return; */
84628  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
84629    return;
84630  }
84631  v = sqlite3GetVdbe(pParse);
84632  if( !v ) return;
84633  if( type!=TK_DEFERRED ){
84634    for(i=0; i<db->nDb; i++){
84635      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
84636      sqlite3VdbeUsesBtree(v, i);
84637    }
84638  }
84639  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
84640}
84641
84642/*
84643** Commit a transaction
84644*/
84645SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
84646  Vdbe *v;
84647
84648  assert( pParse!=0 );
84649  assert( pParse->db!=0 );
84650  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
84651    return;
84652  }
84653  v = sqlite3GetVdbe(pParse);
84654  if( v ){
84655    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
84656  }
84657}
84658
84659/*
84660** Rollback a transaction
84661*/
84662SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
84663  Vdbe *v;
84664
84665  assert( pParse!=0 );
84666  assert( pParse->db!=0 );
84667  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
84668    return;
84669  }
84670  v = sqlite3GetVdbe(pParse);
84671  if( v ){
84672    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
84673  }
84674}
84675
84676/*
84677** This function is called by the parser when it parses a command to create,
84678** release or rollback an SQL savepoint.
84679*/
84680SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
84681  char *zName = sqlite3NameFromToken(pParse->db, pName);
84682  if( zName ){
84683    Vdbe *v = sqlite3GetVdbe(pParse);
84684#ifndef SQLITE_OMIT_AUTHORIZATION
84685    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
84686    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
84687#endif
84688    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
84689      sqlite3DbFree(pParse->db, zName);
84690      return;
84691    }
84692    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
84693  }
84694}
84695
84696/*
84697** Make sure the TEMP database is open and available for use.  Return
84698** the number of errors.  Leave any error messages in the pParse structure.
84699*/
84700SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
84701  sqlite3 *db = pParse->db;
84702  if( db->aDb[1].pBt==0 && !pParse->explain ){
84703    int rc;
84704    Btree *pBt;
84705    static const int flags =
84706          SQLITE_OPEN_READWRITE |
84707          SQLITE_OPEN_CREATE |
84708          SQLITE_OPEN_EXCLUSIVE |
84709          SQLITE_OPEN_DELETEONCLOSE |
84710          SQLITE_OPEN_TEMP_DB;
84711
84712    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
84713    if( rc!=SQLITE_OK ){
84714      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
84715        "file for storing temporary tables");
84716      pParse->rc = rc;
84717      return 1;
84718    }
84719    db->aDb[1].pBt = pBt;
84720    assert( db->aDb[1].pSchema );
84721    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
84722      db->mallocFailed = 1;
84723      return 1;
84724    }
84725  }
84726  return 0;
84727}
84728
84729/*
84730** Generate VDBE code that will verify the schema cookie and start
84731** a read-transaction for all named database files.
84732**
84733** It is important that all schema cookies be verified and all
84734** read transactions be started before anything else happens in
84735** the VDBE program.  But this routine can be called after much other
84736** code has been generated.  So here is what we do:
84737**
84738** The first time this routine is called, we code an OP_Goto that
84739** will jump to a subroutine at the end of the program.  Then we
84740** record every database that needs its schema verified in the
84741** pParse->cookieMask field.  Later, after all other code has been
84742** generated, the subroutine that does the cookie verifications and
84743** starts the transactions will be coded and the OP_Goto P2 value
84744** will be made to point to that subroutine.  The generation of the
84745** cookie verification subroutine code happens in sqlite3FinishCoding().
84746**
84747** If iDb<0 then code the OP_Goto only - don't set flag to verify the
84748** schema on any databases.  This can be used to position the OP_Goto
84749** early in the code, before we know if any database tables will be used.
84750*/
84751SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
84752  Parse *pToplevel = sqlite3ParseToplevel(pParse);
84753
84754  if( pToplevel->cookieGoto==0 ){
84755    Vdbe *v = sqlite3GetVdbe(pToplevel);
84756    if( v==0 ) return;  /* This only happens if there was a prior error */
84757    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
84758  }
84759  if( iDb>=0 ){
84760    sqlite3 *db = pToplevel->db;
84761    yDbMask mask;
84762
84763    assert( iDb<db->nDb );
84764    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
84765    assert( iDb<SQLITE_MAX_ATTACHED+2 );
84766    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84767    mask = ((yDbMask)1)<<iDb;
84768    if( (pToplevel->cookieMask & mask)==0 ){
84769      pToplevel->cookieMask |= mask;
84770      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
84771      if( !OMIT_TEMPDB && iDb==1 ){
84772        sqlite3OpenTempDatabase(pToplevel);
84773      }
84774    }
84775  }
84776}
84777
84778/*
84779** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
84780** attached database. Otherwise, invoke it for the database named zDb only.
84781*/
84782SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
84783  sqlite3 *db = pParse->db;
84784  int i;
84785  for(i=0; i<db->nDb; i++){
84786    Db *pDb = &db->aDb[i];
84787    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
84788      sqlite3CodeVerifySchema(pParse, i);
84789    }
84790  }
84791}
84792
84793/*
84794** Generate VDBE code that prepares for doing an operation that
84795** might change the database.
84796**
84797** This routine starts a new transaction if we are not already within
84798** a transaction.  If we are already within a transaction, then a checkpoint
84799** is set if the setStatement parameter is true.  A checkpoint should
84800** be set for operations that might fail (due to a constraint) part of
84801** the way through and which will need to undo some writes without having to
84802** rollback the whole transaction.  For operations where all constraints
84803** can be checked before any changes are made to the database, it is never
84804** necessary to undo a write and the checkpoint should not be set.
84805*/
84806SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
84807  Parse *pToplevel = sqlite3ParseToplevel(pParse);
84808  sqlite3CodeVerifySchema(pParse, iDb);
84809  pToplevel->writeMask |= ((yDbMask)1)<<iDb;
84810  pToplevel->isMultiWrite |= setStatement;
84811}
84812
84813/*
84814** Indicate that the statement currently under construction might write
84815** more than one entry (example: deleting one row then inserting another,
84816** inserting multiple rows in a table, or inserting a row and index entries.)
84817** If an abort occurs after some of these writes have completed, then it will
84818** be necessary to undo the completed writes.
84819*/
84820SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
84821  Parse *pToplevel = sqlite3ParseToplevel(pParse);
84822  pToplevel->isMultiWrite = 1;
84823}
84824
84825/*
84826** The code generator calls this routine if is discovers that it is
84827** possible to abort a statement prior to completion.  In order to
84828** perform this abort without corrupting the database, we need to make
84829** sure that the statement is protected by a statement transaction.
84830**
84831** Technically, we only need to set the mayAbort flag if the
84832** isMultiWrite flag was previously set.  There is a time dependency
84833** such that the abort must occur after the multiwrite.  This makes
84834** some statements involving the REPLACE conflict resolution algorithm
84835** go a little faster.  But taking advantage of this time dependency
84836** makes it more difficult to prove that the code is correct (in
84837** particular, it prevents us from writing an effective
84838** implementation of sqlite3AssertMayAbort()) and so we have chosen
84839** to take the safe route and skip the optimization.
84840*/
84841SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
84842  Parse *pToplevel = sqlite3ParseToplevel(pParse);
84843  pToplevel->mayAbort = 1;
84844}
84845
84846/*
84847** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
84848** error. The onError parameter determines which (if any) of the statement
84849** and/or current transaction is rolled back.
84850*/
84851SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
84852  Vdbe *v = sqlite3GetVdbe(pParse);
84853  if( onError==OE_Abort ){
84854    sqlite3MayAbort(pParse);
84855  }
84856  sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
84857}
84858
84859/*
84860** Check to see if pIndex uses the collating sequence pColl.  Return
84861** true if it does and false if it does not.
84862*/
84863#ifndef SQLITE_OMIT_REINDEX
84864static int collationMatch(const char *zColl, Index *pIndex){
84865  int i;
84866  assert( zColl!=0 );
84867  for(i=0; i<pIndex->nColumn; i++){
84868    const char *z = pIndex->azColl[i];
84869    assert( z!=0 );
84870    if( 0==sqlite3StrICmp(z, zColl) ){
84871      return 1;
84872    }
84873  }
84874  return 0;
84875}
84876#endif
84877
84878/*
84879** Recompute all indices of pTab that use the collating sequence pColl.
84880** If pColl==0 then recompute all indices of pTab.
84881*/
84882#ifndef SQLITE_OMIT_REINDEX
84883static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
84884  Index *pIndex;              /* An index associated with pTab */
84885
84886  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84887    if( zColl==0 || collationMatch(zColl, pIndex) ){
84888      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84889      sqlite3BeginWriteOperation(pParse, 0, iDb);
84890      sqlite3RefillIndex(pParse, pIndex, -1);
84891    }
84892  }
84893}
84894#endif
84895
84896/*
84897** Recompute all indices of all tables in all databases where the
84898** indices use the collating sequence pColl.  If pColl==0 then recompute
84899** all indices everywhere.
84900*/
84901#ifndef SQLITE_OMIT_REINDEX
84902static void reindexDatabases(Parse *pParse, char const *zColl){
84903  Db *pDb;                    /* A single database */
84904  int iDb;                    /* The database index number */
84905  sqlite3 *db = pParse->db;   /* The database connection */
84906  HashElem *k;                /* For looping over tables in pDb */
84907  Table *pTab;                /* A table in the database */
84908
84909  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
84910  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
84911    assert( pDb!=0 );
84912    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
84913      pTab = (Table*)sqliteHashData(k);
84914      reindexTable(pParse, pTab, zColl);
84915    }
84916  }
84917}
84918#endif
84919
84920/*
84921** Generate code for the REINDEX command.
84922**
84923**        REINDEX                            -- 1
84924**        REINDEX  <collation>               -- 2
84925**        REINDEX  ?<database>.?<tablename>  -- 3
84926**        REINDEX  ?<database>.?<indexname>  -- 4
84927**
84928** Form 1 causes all indices in all attached databases to be rebuilt.
84929** Form 2 rebuilds all indices in all databases that use the named
84930** collating function.  Forms 3 and 4 rebuild the named index or all
84931** indices associated with the named table.
84932*/
84933#ifndef SQLITE_OMIT_REINDEX
84934SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
84935  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
84936  char *z;                    /* Name of a table or index */
84937  const char *zDb;            /* Name of the database */
84938  Table *pTab;                /* A table in the database */
84939  Index *pIndex;              /* An index associated with pTab */
84940  int iDb;                    /* The database index number */
84941  sqlite3 *db = pParse->db;   /* The database connection */
84942  Token *pObjName;            /* Name of the table or index to be reindexed */
84943
84944  /* Read the database schema. If an error occurs, leave an error message
84945  ** and code in pParse and return NULL. */
84946  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84947    return;
84948  }
84949
84950  if( pName1==0 ){
84951    reindexDatabases(pParse, 0);
84952    return;
84953  }else if( NEVER(pName2==0) || pName2->z==0 ){
84954    char *zColl;
84955    assert( pName1->z );
84956    zColl = sqlite3NameFromToken(pParse->db, pName1);
84957    if( !zColl ) return;
84958    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
84959    if( pColl ){
84960      reindexDatabases(pParse, zColl);
84961      sqlite3DbFree(db, zColl);
84962      return;
84963    }
84964    sqlite3DbFree(db, zColl);
84965  }
84966  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
84967  if( iDb<0 ) return;
84968  z = sqlite3NameFromToken(db, pObjName);
84969  if( z==0 ) return;
84970  zDb = db->aDb[iDb].zName;
84971  pTab = sqlite3FindTable(db, z, zDb);
84972  if( pTab ){
84973    reindexTable(pParse, pTab, 0);
84974    sqlite3DbFree(db, z);
84975    return;
84976  }
84977  pIndex = sqlite3FindIndex(db, z, zDb);
84978  sqlite3DbFree(db, z);
84979  if( pIndex ){
84980    sqlite3BeginWriteOperation(pParse, 0, iDb);
84981    sqlite3RefillIndex(pParse, pIndex, -1);
84982    return;
84983  }
84984  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
84985}
84986#endif
84987
84988/*
84989** Return a dynamicly allocated KeyInfo structure that can be used
84990** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
84991**
84992** If successful, a pointer to the new structure is returned. In this case
84993** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
84994** pointer. If an error occurs (out of memory or missing collation
84995** sequence), NULL is returned and the state of pParse updated to reflect
84996** the error.
84997*/
84998SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
84999  int i;
85000  int nCol = pIdx->nColumn;
85001  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
85002  sqlite3 *db = pParse->db;
85003  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
85004
85005  if( pKey ){
85006    pKey->db = pParse->db;
85007    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
85008    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
85009    for(i=0; i<nCol; i++){
85010      char *zColl = pIdx->azColl[i];
85011      assert( zColl );
85012      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
85013      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
85014    }
85015    pKey->nField = (u16)nCol;
85016  }
85017
85018  if( pParse->nErr ){
85019    sqlite3DbFree(db, pKey);
85020    pKey = 0;
85021  }
85022  return pKey;
85023}
85024
85025/************** End of build.c ***********************************************/
85026/************** Begin file callback.c ****************************************/
85027/*
85028** 2005 May 23
85029**
85030** The author disclaims copyright to this source code.  In place of
85031** a legal notice, here is a blessing:
85032**
85033**    May you do good and not evil.
85034**    May you find forgiveness for yourself and forgive others.
85035**    May you share freely, never taking more than you give.
85036**
85037*************************************************************************
85038**
85039** This file contains functions used to access the internal hash tables
85040** of user defined functions and collation sequences.
85041*/
85042
85043
85044/*
85045** Invoke the 'collation needed' callback to request a collation sequence
85046** in the encoding enc of name zName, length nName.
85047*/
85048static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
85049  assert( !db->xCollNeeded || !db->xCollNeeded16 );
85050  if( db->xCollNeeded ){
85051    char *zExternal = sqlite3DbStrDup(db, zName);
85052    if( !zExternal ) return;
85053    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
85054    sqlite3DbFree(db, zExternal);
85055  }
85056#ifndef SQLITE_OMIT_UTF16
85057  if( db->xCollNeeded16 ){
85058    char const *zExternal;
85059    sqlite3_value *pTmp = sqlite3ValueNew(db);
85060    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
85061    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
85062    if( zExternal ){
85063      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
85064    }
85065    sqlite3ValueFree(pTmp);
85066  }
85067#endif
85068}
85069
85070/*
85071** This routine is called if the collation factory fails to deliver a
85072** collation function in the best encoding but there may be other versions
85073** of this collation function (for other text encodings) available. Use one
85074** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
85075** possible.
85076*/
85077static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
85078  CollSeq *pColl2;
85079  char *z = pColl->zName;
85080  int i;
85081  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
85082  for(i=0; i<3; i++){
85083    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
85084    if( pColl2->xCmp!=0 ){
85085      memcpy(pColl, pColl2, sizeof(CollSeq));
85086      pColl->xDel = 0;         /* Do not copy the destructor */
85087      return SQLITE_OK;
85088    }
85089  }
85090  return SQLITE_ERROR;
85091}
85092
85093/*
85094** This function is responsible for invoking the collation factory callback
85095** or substituting a collation sequence of a different encoding when the
85096** requested collation sequence is not available in the desired encoding.
85097**
85098** If it is not NULL, then pColl must point to the database native encoding
85099** collation sequence with name zName, length nName.
85100**
85101** The return value is either the collation sequence to be used in database
85102** db for collation type name zName, length nName, or NULL, if no collation
85103** sequence can be found.
85104**
85105** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
85106*/
85107SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
85108  sqlite3* db,          /* The database connection */
85109  u8 enc,               /* The desired encoding for the collating sequence */
85110  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
85111  const char *zName     /* Collating sequence name */
85112){
85113  CollSeq *p;
85114
85115  p = pColl;
85116  if( !p ){
85117    p = sqlite3FindCollSeq(db, enc, zName, 0);
85118  }
85119  if( !p || !p->xCmp ){
85120    /* No collation sequence of this type for this encoding is registered.
85121    ** Call the collation factory to see if it can supply us with one.
85122    */
85123    callCollNeeded(db, enc, zName);
85124    p = sqlite3FindCollSeq(db, enc, zName, 0);
85125  }
85126  if( p && !p->xCmp && synthCollSeq(db, p) ){
85127    p = 0;
85128  }
85129  assert( !p || p->xCmp );
85130  return p;
85131}
85132
85133/*
85134** This routine is called on a collation sequence before it is used to
85135** check that it is defined. An undefined collation sequence exists when
85136** a database is loaded that contains references to collation sequences
85137** that have not been defined by sqlite3_create_collation() etc.
85138**
85139** If required, this routine calls the 'collation needed' callback to
85140** request a definition of the collating sequence. If this doesn't work,
85141** an equivalent collating sequence that uses a text encoding different
85142** from the main database is substituted, if one is available.
85143*/
85144SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
85145  if( pColl ){
85146    const char *zName = pColl->zName;
85147    sqlite3 *db = pParse->db;
85148    CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
85149    if( !p ){
85150      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
85151      pParse->nErr++;
85152      return SQLITE_ERROR;
85153    }
85154    assert( p==pColl );
85155  }
85156  return SQLITE_OK;
85157}
85158
85159
85160
85161/*
85162** Locate and return an entry from the db.aCollSeq hash table. If the entry
85163** specified by zName and nName is not found and parameter 'create' is
85164** true, then create a new entry. Otherwise return NULL.
85165**
85166** Each pointer stored in the sqlite3.aCollSeq hash table contains an
85167** array of three CollSeq structures. The first is the collation sequence
85168** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
85169**
85170** Stored immediately after the three collation sequences is a copy of
85171** the collation sequence name. A pointer to this string is stored in
85172** each collation sequence structure.
85173*/
85174static CollSeq *findCollSeqEntry(
85175  sqlite3 *db,          /* Database connection */
85176  const char *zName,    /* Name of the collating sequence */
85177  int create            /* Create a new entry if true */
85178){
85179  CollSeq *pColl;
85180  int nName = sqlite3Strlen30(zName);
85181  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
85182
85183  if( 0==pColl && create ){
85184    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
85185    if( pColl ){
85186      CollSeq *pDel = 0;
85187      pColl[0].zName = (char*)&pColl[3];
85188      pColl[0].enc = SQLITE_UTF8;
85189      pColl[1].zName = (char*)&pColl[3];
85190      pColl[1].enc = SQLITE_UTF16LE;
85191      pColl[2].zName = (char*)&pColl[3];
85192      pColl[2].enc = SQLITE_UTF16BE;
85193      memcpy(pColl[0].zName, zName, nName);
85194      pColl[0].zName[nName] = 0;
85195      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
85196
85197      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
85198      ** return the pColl pointer to be deleted (because it wasn't added
85199      ** to the hash table).
85200      */
85201      assert( pDel==0 || pDel==pColl );
85202      if( pDel!=0 ){
85203        db->mallocFailed = 1;
85204        sqlite3DbFree(db, pDel);
85205        pColl = 0;
85206      }
85207    }
85208  }
85209  return pColl;
85210}
85211
85212/*
85213** Parameter zName points to a UTF-8 encoded string nName bytes long.
85214** Return the CollSeq* pointer for the collation sequence named zName
85215** for the encoding 'enc' from the database 'db'.
85216**
85217** If the entry specified is not found and 'create' is true, then create a
85218** new entry.  Otherwise return NULL.
85219**
85220** A separate function sqlite3LocateCollSeq() is a wrapper around
85221** this routine.  sqlite3LocateCollSeq() invokes the collation factory
85222** if necessary and generates an error message if the collating sequence
85223** cannot be found.
85224**
85225** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
85226*/
85227SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
85228  sqlite3 *db,
85229  u8 enc,
85230  const char *zName,
85231  int create
85232){
85233  CollSeq *pColl;
85234  if( zName ){
85235    pColl = findCollSeqEntry(db, zName, create);
85236  }else{
85237    pColl = db->pDfltColl;
85238  }
85239  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
85240  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
85241  if( pColl ) pColl += enc-1;
85242  return pColl;
85243}
85244
85245/* During the search for the best function definition, this procedure
85246** is called to test how well the function passed as the first argument
85247** matches the request for a function with nArg arguments in a system
85248** that uses encoding enc. The value returned indicates how well the
85249** request is matched. A higher value indicates a better match.
85250**
85251** The returned value is always between 0 and 6, as follows:
85252**
85253** 0: Not a match, or if nArg<0 and the function is has no implementation.
85254** 1: A variable arguments function that prefers UTF-8 when a UTF-16
85255**    encoding is requested, or vice versa.
85256** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
85257**    requested, or vice versa.
85258** 3: A variable arguments function using the same text encoding.
85259** 4: A function with the exact number of arguments requested that
85260**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
85261** 5: A function with the exact number of arguments requested that
85262**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
85263** 6: An exact match.
85264**
85265*/
85266static int matchQuality(FuncDef *p, int nArg, u8 enc){
85267  int match = 0;
85268  if( p->nArg==-1 || p->nArg==nArg
85269   || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
85270  ){
85271    match = 1;
85272    if( p->nArg==nArg || nArg==-1 ){
85273      match = 4;
85274    }
85275    if( enc==p->iPrefEnc ){
85276      match += 2;
85277    }
85278    else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
85279             (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
85280      match += 1;
85281    }
85282  }
85283  return match;
85284}
85285
85286/*
85287** Search a FuncDefHash for a function with the given name.  Return
85288** a pointer to the matching FuncDef if found, or 0 if there is no match.
85289*/
85290static FuncDef *functionSearch(
85291  FuncDefHash *pHash,  /* Hash table to search */
85292  int h,               /* Hash of the name */
85293  const char *zFunc,   /* Name of function */
85294  int nFunc            /* Number of bytes in zFunc */
85295){
85296  FuncDef *p;
85297  for(p=pHash->a[h]; p; p=p->pHash){
85298    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
85299      return p;
85300    }
85301  }
85302  return 0;
85303}
85304
85305/*
85306** Insert a new FuncDef into a FuncDefHash hash table.
85307*/
85308SQLITE_PRIVATE void sqlite3FuncDefInsert(
85309  FuncDefHash *pHash,  /* The hash table into which to insert */
85310  FuncDef *pDef        /* The function definition to insert */
85311){
85312  FuncDef *pOther;
85313  int nName = sqlite3Strlen30(pDef->zName);
85314  u8 c1 = (u8)pDef->zName[0];
85315  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
85316  pOther = functionSearch(pHash, h, pDef->zName, nName);
85317  if( pOther ){
85318    assert( pOther!=pDef && pOther->pNext!=pDef );
85319    pDef->pNext = pOther->pNext;
85320    pOther->pNext = pDef;
85321  }else{
85322    pDef->pNext = 0;
85323    pDef->pHash = pHash->a[h];
85324    pHash->a[h] = pDef;
85325  }
85326}
85327
85328
85329
85330/*
85331** Locate a user function given a name, a number of arguments and a flag
85332** indicating whether the function prefers UTF-16 over UTF-8.  Return a
85333** pointer to the FuncDef structure that defines that function, or return
85334** NULL if the function does not exist.
85335**
85336** If the createFlag argument is true, then a new (blank) FuncDef
85337** structure is created and liked into the "db" structure if a
85338** no matching function previously existed.  When createFlag is true
85339** and the nArg parameter is -1, then only a function that accepts
85340** any number of arguments will be returned.
85341**
85342** If createFlag is false and nArg is -1, then the first valid
85343** function found is returned.  A function is valid if either xFunc
85344** or xStep is non-zero.
85345**
85346** If createFlag is false, then a function with the required name and
85347** number of arguments may be returned even if the eTextRep flag does not
85348** match that requested.
85349*/
85350SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
85351  sqlite3 *db,       /* An open database */
85352  const char *zName, /* Name of the function.  Not null-terminated */
85353  int nName,         /* Number of characters in the name */
85354  int nArg,          /* Number of arguments.  -1 means any number */
85355  u8 enc,            /* Preferred text encoding */
85356  int createFlag     /* Create new entry if true and does not otherwise exist */
85357){
85358  FuncDef *p;         /* Iterator variable */
85359  FuncDef *pBest = 0; /* Best match found so far */
85360  int bestScore = 0;  /* Score of best match */
85361  int h;              /* Hash value */
85362
85363
85364  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
85365  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
85366
85367  /* First search for a match amongst the application-defined functions.
85368  */
85369  p = functionSearch(&db->aFunc, h, zName, nName);
85370  while( p ){
85371    int score = matchQuality(p, nArg, enc);
85372    if( score>bestScore ){
85373      pBest = p;
85374      bestScore = score;
85375    }
85376    p = p->pNext;
85377  }
85378
85379  /* If no match is found, search the built-in functions.
85380  **
85381  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
85382  ** functions even if a prior app-defined function was found.  And give
85383  ** priority to built-in functions.
85384  **
85385  ** Except, if createFlag is true, that means that we are trying to
85386  ** install a new function.  Whatever FuncDef structure is returned it will
85387  ** have fields overwritten with new information appropriate for the
85388  ** new function.  But the FuncDefs for built-in functions are read-only.
85389  ** So we must not search for built-ins when creating a new function.
85390  */
85391  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
85392    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
85393    bestScore = 0;
85394    p = functionSearch(pHash, h, zName, nName);
85395    while( p ){
85396      int score = matchQuality(p, nArg, enc);
85397      if( score>bestScore ){
85398        pBest = p;
85399        bestScore = score;
85400      }
85401      p = p->pNext;
85402    }
85403  }
85404
85405  /* If the createFlag parameter is true and the search did not reveal an
85406  ** exact match for the name, number of arguments and encoding, then add a
85407  ** new entry to the hash table and return it.
85408  */
85409  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
85410      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
85411    pBest->zName = (char *)&pBest[1];
85412    pBest->nArg = (u16)nArg;
85413    pBest->iPrefEnc = enc;
85414    memcpy(pBest->zName, zName, nName);
85415    pBest->zName[nName] = 0;
85416    sqlite3FuncDefInsert(&db->aFunc, pBest);
85417  }
85418
85419  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
85420    return pBest;
85421  }
85422  return 0;
85423}
85424
85425/*
85426** Free all resources held by the schema structure. The void* argument points
85427** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
85428** pointer itself, it just cleans up subsidiary resources (i.e. the contents
85429** of the schema hash tables).
85430**
85431** The Schema.cache_size variable is not cleared.
85432*/
85433SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
85434  Hash temp1;
85435  Hash temp2;
85436  HashElem *pElem;
85437  Schema *pSchema = (Schema *)p;
85438
85439  temp1 = pSchema->tblHash;
85440  temp2 = pSchema->trigHash;
85441  sqlite3HashInit(&pSchema->trigHash);
85442  sqlite3HashClear(&pSchema->idxHash);
85443  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
85444    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
85445  }
85446  sqlite3HashClear(&temp2);
85447  sqlite3HashInit(&pSchema->tblHash);
85448  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
85449    Table *pTab = sqliteHashData(pElem);
85450    sqlite3DeleteTable(0, pTab);
85451  }
85452  sqlite3HashClear(&temp1);
85453  sqlite3HashClear(&pSchema->fkeyHash);
85454  pSchema->pSeqTab = 0;
85455  if( pSchema->flags & DB_SchemaLoaded ){
85456    pSchema->iGeneration++;
85457    pSchema->flags &= ~DB_SchemaLoaded;
85458  }
85459}
85460
85461/*
85462** Find and return the schema associated with a BTree.  Create
85463** a new one if necessary.
85464*/
85465SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
85466  Schema * p;
85467  if( pBt ){
85468    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
85469  }else{
85470    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
85471  }
85472  if( !p ){
85473    db->mallocFailed = 1;
85474  }else if ( 0==p->file_format ){
85475    sqlite3HashInit(&p->tblHash);
85476    sqlite3HashInit(&p->idxHash);
85477    sqlite3HashInit(&p->trigHash);
85478    sqlite3HashInit(&p->fkeyHash);
85479    p->enc = SQLITE_UTF8;
85480  }
85481  return p;
85482}
85483
85484/************** End of callback.c ********************************************/
85485/************** Begin file delete.c ******************************************/
85486/*
85487** 2001 September 15
85488**
85489** The author disclaims copyright to this source code.  In place of
85490** a legal notice, here is a blessing:
85491**
85492**    May you do good and not evil.
85493**    May you find forgiveness for yourself and forgive others.
85494**    May you share freely, never taking more than you give.
85495**
85496*************************************************************************
85497** This file contains C code routines that are called by the parser
85498** in order to generate code for DELETE FROM statements.
85499*/
85500
85501/*
85502** While a SrcList can in general represent multiple tables and subqueries
85503** (as in the FROM clause of a SELECT statement) in this case it contains
85504** the name of a single table, as one might find in an INSERT, DELETE,
85505** or UPDATE statement.  Look up that table in the symbol table and
85506** return a pointer.  Set an error message and return NULL if the table
85507** name is not found or if any other error occurs.
85508**
85509** The following fields are initialized appropriate in pSrc:
85510**
85511**    pSrc->a[0].pTab       Pointer to the Table object
85512**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
85513**
85514*/
85515SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
85516  struct SrcList_item *pItem = pSrc->a;
85517  Table *pTab;
85518  assert( pItem && pSrc->nSrc==1 );
85519  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
85520  sqlite3DeleteTable(pParse->db, pItem->pTab);
85521  pItem->pTab = pTab;
85522  if( pTab ){
85523    pTab->nRef++;
85524  }
85525  if( sqlite3IndexedByLookup(pParse, pItem) ){
85526    pTab = 0;
85527  }
85528  return pTab;
85529}
85530
85531/*
85532** Check to make sure the given table is writable.  If it is not
85533** writable, generate an error message and return 1.  If it is
85534** writable return 0;
85535*/
85536SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
85537  /* A table is not writable under the following circumstances:
85538  **
85539  **   1) It is a virtual table and no implementation of the xUpdate method
85540  **      has been provided, or
85541  **   2) It is a system table (i.e. sqlite_master), this call is not
85542  **      part of a nested parse and writable_schema pragma has not
85543  **      been specified.
85544  **
85545  ** In either case leave an error message in pParse and return non-zero.
85546  */
85547  if( ( IsVirtual(pTab)
85548     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
85549   || ( (pTab->tabFlags & TF_Readonly)!=0
85550     && (pParse->db->flags & SQLITE_WriteSchema)==0
85551     && pParse->nested==0 )
85552  ){
85553    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
85554    return 1;
85555  }
85556
85557#ifndef SQLITE_OMIT_VIEW
85558  if( !viewOk && pTab->pSelect ){
85559    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
85560    return 1;
85561  }
85562#endif
85563  return 0;
85564}
85565
85566
85567#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85568/*
85569** Evaluate a view and store its result in an ephemeral table.  The
85570** pWhere argument is an optional WHERE clause that restricts the
85571** set of rows in the view that are to be added to the ephemeral table.
85572*/
85573SQLITE_PRIVATE void sqlite3MaterializeView(
85574  Parse *pParse,       /* Parsing context */
85575  Table *pView,        /* View definition */
85576  Expr *pWhere,        /* Optional WHERE clause to be added */
85577  int iCur             /* Cursor number for ephemerial table */
85578){
85579  SelectDest dest;
85580  Select *pDup;
85581  sqlite3 *db = pParse->db;
85582
85583  pDup = sqlite3SelectDup(db, pView->pSelect, 0);
85584  if( pWhere ){
85585    SrcList *pFrom;
85586
85587    pWhere = sqlite3ExprDup(db, pWhere, 0);
85588    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
85589    if( pFrom ){
85590      assert( pFrom->nSrc==1 );
85591      pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
85592      pFrom->a[0].pSelect = pDup;
85593      assert( pFrom->a[0].pOn==0 );
85594      assert( pFrom->a[0].pUsing==0 );
85595    }else{
85596      sqlite3SelectDelete(db, pDup);
85597    }
85598    pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
85599  }
85600  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
85601  sqlite3Select(pParse, pDup, &dest);
85602  sqlite3SelectDelete(db, pDup);
85603}
85604#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
85605
85606#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
85607/*
85608** Generate an expression tree to implement the WHERE, ORDER BY,
85609** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
85610**
85611**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
85612**                            \__________________________/
85613**                               pLimitWhere (pInClause)
85614*/
85615SQLITE_PRIVATE Expr *sqlite3LimitWhere(
85616  Parse *pParse,               /* The parser context */
85617  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
85618  Expr *pWhere,                /* The WHERE clause.  May be null */
85619  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
85620  Expr *pLimit,                /* The LIMIT clause.  May be null */
85621  Expr *pOffset,               /* The OFFSET clause.  May be null */
85622  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
85623){
85624  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
85625  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
85626  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
85627  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
85628  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
85629  Select *pSelect = NULL;      /* Complete SELECT tree */
85630
85631  /* Check that there isn't an ORDER BY without a LIMIT clause.
85632  */
85633  if( pOrderBy && (pLimit == 0) ) {
85634    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
85635    goto limit_where_cleanup_2;
85636  }
85637
85638  /* We only need to generate a select expression if there
85639  ** is a limit/offset term to enforce.
85640  */
85641  if( pLimit == 0 ) {
85642    /* if pLimit is null, pOffset will always be null as well. */
85643    assert( pOffset == 0 );
85644    return pWhere;
85645  }
85646
85647  /* Generate a select expression tree to enforce the limit/offset
85648  ** term for the DELETE or UPDATE statement.  For example:
85649  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85650  ** becomes:
85651  **   DELETE FROM table_a WHERE rowid IN (
85652  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85653  **   );
85654  */
85655
85656  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
85657  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
85658  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
85659  if( pEList == 0 ) goto limit_where_cleanup_2;
85660
85661  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
85662  ** and the SELECT subtree. */
85663  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
85664  if( pSelectSrc == 0 ) {
85665    sqlite3ExprListDelete(pParse->db, pEList);
85666    goto limit_where_cleanup_2;
85667  }
85668
85669  /* generate the SELECT expression tree. */
85670  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
85671                             pOrderBy,0,pLimit,pOffset);
85672  if( pSelect == 0 ) return 0;
85673
85674  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
85675  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
85676  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
85677  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
85678  if( pInClause == 0 ) goto limit_where_cleanup_1;
85679
85680  pInClause->x.pSelect = pSelect;
85681  pInClause->flags |= EP_xIsSelect;
85682  sqlite3ExprSetHeight(pParse, pInClause);
85683  return pInClause;
85684
85685  /* something went wrong. clean up anything allocated. */
85686limit_where_cleanup_1:
85687  sqlite3SelectDelete(pParse->db, pSelect);
85688  return 0;
85689
85690limit_where_cleanup_2:
85691  sqlite3ExprDelete(pParse->db, pWhere);
85692  sqlite3ExprListDelete(pParse->db, pOrderBy);
85693  sqlite3ExprDelete(pParse->db, pLimit);
85694  sqlite3ExprDelete(pParse->db, pOffset);
85695  return 0;
85696}
85697#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
85698
85699/*
85700** Generate code for a DELETE FROM statement.
85701**
85702**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
85703**                 \________/       \________________/
85704**                  pTabList              pWhere
85705*/
85706SQLITE_PRIVATE void sqlite3DeleteFrom(
85707  Parse *pParse,         /* The parser context */
85708  SrcList *pTabList,     /* The table from which we should delete things */
85709  Expr *pWhere           /* The WHERE clause.  May be null */
85710){
85711  Vdbe *v;               /* The virtual database engine */
85712  Table *pTab;           /* The table from which records will be deleted */
85713  const char *zDb;       /* Name of database holding pTab */
85714  int end, addr = 0;     /* A couple addresses of generated code */
85715  int i;                 /* Loop counter */
85716  WhereInfo *pWInfo;     /* Information about the WHERE clause */
85717  Index *pIdx;           /* For looping over indices of the table */
85718  int iCur;              /* VDBE Cursor number for pTab */
85719  sqlite3 *db;           /* Main database structure */
85720  AuthContext sContext;  /* Authorization context */
85721  NameContext sNC;       /* Name context to resolve expressions in */
85722  int iDb;               /* Database number */
85723  int memCnt = -1;       /* Memory cell used for change counting */
85724  int rcauth;            /* Value returned by authorization callback */
85725
85726#ifndef SQLITE_OMIT_TRIGGER
85727  int isView;                  /* True if attempting to delete from a view */
85728  Trigger *pTrigger;           /* List of table triggers, if required */
85729#endif
85730
85731  memset(&sContext, 0, sizeof(sContext));
85732  db = pParse->db;
85733  if( pParse->nErr || db->mallocFailed ){
85734    goto delete_from_cleanup;
85735  }
85736  assert( pTabList->nSrc==1 );
85737
85738  /* Locate the table which we want to delete.  This table has to be
85739  ** put in an SrcList structure because some of the subroutines we
85740  ** will be calling are designed to work with multiple tables and expect
85741  ** an SrcList* parameter instead of just a Table* parameter.
85742  */
85743  pTab = sqlite3SrcListLookup(pParse, pTabList);
85744  if( pTab==0 )  goto delete_from_cleanup;
85745
85746  /* Figure out if we have any triggers and if the table being
85747  ** deleted from is a view
85748  */
85749#ifndef SQLITE_OMIT_TRIGGER
85750  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85751  isView = pTab->pSelect!=0;
85752#else
85753# define pTrigger 0
85754# define isView 0
85755#endif
85756#ifdef SQLITE_OMIT_VIEW
85757# undef isView
85758# define isView 0
85759#endif
85760
85761  /* If pTab is really a view, make sure it has been initialized.
85762  */
85763  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85764    goto delete_from_cleanup;
85765  }
85766
85767  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
85768    goto delete_from_cleanup;
85769  }
85770  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85771  assert( iDb<db->nDb );
85772  zDb = db->aDb[iDb].zName;
85773  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
85774  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
85775  if( rcauth==SQLITE_DENY ){
85776    goto delete_from_cleanup;
85777  }
85778  assert(!isView || pTrigger);
85779
85780  /* Assign  cursor number to the table and all its indices.
85781  */
85782  assert( pTabList->nSrc==1 );
85783  iCur = pTabList->a[0].iCursor = pParse->nTab++;
85784  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85785    pParse->nTab++;
85786  }
85787
85788  /* Start the view context
85789  */
85790  if( isView ){
85791    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
85792  }
85793
85794  /* Begin generating code.
85795  */
85796  v = sqlite3GetVdbe(pParse);
85797  if( v==0 ){
85798    goto delete_from_cleanup;
85799  }
85800  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
85801  sqlite3BeginWriteOperation(pParse, 1, iDb);
85802
85803  /* If we are trying to delete from a view, realize that view into
85804  ** a ephemeral table.
85805  */
85806#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85807  if( isView ){
85808    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
85809  }
85810#endif
85811
85812  /* Resolve the column names in the WHERE clause.
85813  */
85814  memset(&sNC, 0, sizeof(sNC));
85815  sNC.pParse = pParse;
85816  sNC.pSrcList = pTabList;
85817  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
85818    goto delete_from_cleanup;
85819  }
85820
85821  /* Initialize the counter of the number of rows deleted, if
85822  ** we are counting rows.
85823  */
85824  if( db->flags & SQLITE_CountRows ){
85825    memCnt = ++pParse->nMem;
85826    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
85827  }
85828
85829#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
85830  /* Special case: A DELETE without a WHERE clause deletes everything.
85831  ** It is easier just to erase the whole table. Prior to version 3.6.5,
85832  ** this optimization caused the row change count (the value returned by
85833  ** API function sqlite3_count_changes) to be set incorrectly.  */
85834  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
85835   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
85836  ){
85837    assert( !isView );
85838    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
85839                      pTab->zName, P4_STATIC);
85840    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85841      assert( pIdx->pSchema==pTab->pSchema );
85842      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
85843    }
85844  }else
85845#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
85846  /* The usual case: There is a WHERE clause so we have to scan through
85847  ** the table and pick which records to delete.
85848  */
85849  {
85850    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
85851    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
85852    int regRowid;                   /* Actual register containing rowids */
85853
85854    /* Collect rowids of every row to be deleted.
85855    */
85856    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
85857    pWInfo = sqlite3WhereBegin(
85858        pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK
85859    );
85860    if( pWInfo==0 ) goto delete_from_cleanup;
85861    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
85862    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
85863    if( db->flags & SQLITE_CountRows ){
85864      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
85865    }
85866    sqlite3WhereEnd(pWInfo);
85867
85868    /* Delete every item whose key was written to the list during the
85869    ** database scan.  We have to delete items after the scan is complete
85870    ** because deleting an item can change the scan order.  */
85871    end = sqlite3VdbeMakeLabel(v);
85872
85873    /* Unless this is a view, open cursors for the table we are
85874    ** deleting from and all its indices. If this is a view, then the
85875    ** only effect this statement has is to fire the INSTEAD OF
85876    ** triggers.  */
85877    if( !isView ){
85878      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
85879    }
85880
85881    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
85882
85883    /* Delete the row */
85884#ifndef SQLITE_OMIT_VIRTUALTABLE
85885    if( IsVirtual(pTab) ){
85886      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
85887      sqlite3VtabMakeWritable(pParse, pTab);
85888      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
85889      sqlite3VdbeChangeP5(v, OE_Abort);
85890      sqlite3MayAbort(pParse);
85891    }else
85892#endif
85893    {
85894      int count = (pParse->nested==0);    /* True to count changes */
85895      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
85896    }
85897
85898    /* End of the delete loop */
85899    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
85900    sqlite3VdbeResolveLabel(v, end);
85901
85902    /* Close the cursors open on the table and its indexes. */
85903    if( !isView && !IsVirtual(pTab) ){
85904      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85905        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
85906      }
85907      sqlite3VdbeAddOp1(v, OP_Close, iCur);
85908    }
85909  }
85910
85911  /* Update the sqlite_sequence table by storing the content of the
85912  ** maximum rowid counter values recorded while inserting into
85913  ** autoincrement tables.
85914  */
85915  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85916    sqlite3AutoincrementEnd(pParse);
85917  }
85918
85919  /* Return the number of rows that were deleted. If this routine is
85920  ** generating code because of a call to sqlite3NestedParse(), do not
85921  ** invoke the callback function.
85922  */
85923  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85924    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
85925    sqlite3VdbeSetNumCols(v, 1);
85926    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
85927  }
85928
85929delete_from_cleanup:
85930  sqlite3AuthContextPop(&sContext);
85931  sqlite3SrcListDelete(db, pTabList);
85932  sqlite3ExprDelete(db, pWhere);
85933  return;
85934}
85935/* Make sure "isView" and other macros defined above are undefined. Otherwise
85936** thely may interfere with compilation of other functions in this file
85937** (or in another file, if this file becomes part of the amalgamation).  */
85938#ifdef isView
85939 #undef isView
85940#endif
85941#ifdef pTrigger
85942 #undef pTrigger
85943#endif
85944
85945/*
85946** This routine generates VDBE code that causes a single row of a
85947** single table to be deleted.
85948**
85949** The VDBE must be in a particular state when this routine is called.
85950** These are the requirements:
85951**
85952**   1.  A read/write cursor pointing to pTab, the table containing the row
85953**       to be deleted, must be opened as cursor number $iCur.
85954**
85955**   2.  Read/write cursors for all indices of pTab must be open as
85956**       cursor number base+i for the i-th index.
85957**
85958**   3.  The record number of the row to be deleted must be stored in
85959**       memory cell iRowid.
85960**
85961** This routine generates code to remove both the table record and all
85962** index entries that point to that record.
85963*/
85964SQLITE_PRIVATE void sqlite3GenerateRowDelete(
85965  Parse *pParse,     /* Parsing context */
85966  Table *pTab,       /* Table containing the row to be deleted */
85967  int iCur,          /* Cursor number for the table */
85968  int iRowid,        /* Memory cell that contains the rowid to delete */
85969  int count,         /* If non-zero, increment the row change counter */
85970  Trigger *pTrigger, /* List of triggers to (potentially) fire */
85971  int onconf         /* Default ON CONFLICT policy for triggers */
85972){
85973  Vdbe *v = pParse->pVdbe;        /* Vdbe */
85974  int iOld = 0;                   /* First register in OLD.* array */
85975  int iLabel;                     /* Label resolved to end of generated code */
85976
85977  /* Vdbe is guaranteed to have been allocated by this stage. */
85978  assert( v );
85979
85980  /* Seek cursor iCur to the row to delete. If this row no longer exists
85981  ** (this can happen if a trigger program has already deleted it), do
85982  ** not attempt to delete it or fire any DELETE triggers.  */
85983  iLabel = sqlite3VdbeMakeLabel(v);
85984  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85985
85986  /* If there are any triggers to fire, allocate a range of registers to
85987  ** use for the old.* references in the triggers.  */
85988  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
85989    u32 mask;                     /* Mask of OLD.* columns in use */
85990    int iCol;                     /* Iterator used while populating OLD.* */
85991
85992    /* TODO: Could use temporary registers here. Also could attempt to
85993    ** avoid copying the contents of the rowid register.  */
85994    mask = sqlite3TriggerColmask(
85995        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
85996    );
85997    mask |= sqlite3FkOldmask(pParse, pTab);
85998    iOld = pParse->nMem+1;
85999    pParse->nMem += (1 + pTab->nCol);
86000
86001    /* Populate the OLD.* pseudo-table register array. These values will be
86002    ** used by any BEFORE and AFTER triggers that exist.  */
86003    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
86004    for(iCol=0; iCol<pTab->nCol; iCol++){
86005      if( mask==0xffffffff || mask&(1<<iCol) ){
86006        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
86007      }
86008    }
86009
86010    /* Invoke BEFORE DELETE trigger programs. */
86011    sqlite3CodeRowTrigger(pParse, pTrigger,
86012        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
86013    );
86014
86015    /* Seek the cursor to the row to be deleted again. It may be that
86016    ** the BEFORE triggers coded above have already removed the row
86017    ** being deleted. Do not attempt to delete the row a second time, and
86018    ** do not fire AFTER triggers.  */
86019    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
86020
86021    /* Do FK processing. This call checks that any FK constraints that
86022    ** refer to this table (i.e. constraints attached to other tables)
86023    ** are not violated by deleting this row.  */
86024    sqlite3FkCheck(pParse, pTab, iOld, 0);
86025  }
86026
86027  /* Delete the index and table entries. Skip this step if pTab is really
86028  ** a view (in which case the only effect of the DELETE statement is to
86029  ** fire the INSTEAD OF triggers).  */
86030  if( pTab->pSelect==0 ){
86031    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
86032    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
86033    if( count ){
86034      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
86035    }
86036  }
86037
86038  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
86039  ** handle rows (possibly in other tables) that refer via a foreign key
86040  ** to the row just deleted. */
86041  sqlite3FkActions(pParse, pTab, 0, iOld);
86042
86043  /* Invoke AFTER DELETE trigger programs. */
86044  sqlite3CodeRowTrigger(pParse, pTrigger,
86045      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
86046  );
86047
86048  /* Jump here if the row had already been deleted before any BEFORE
86049  ** trigger programs were invoked. Or if a trigger program throws a
86050  ** RAISE(IGNORE) exception.  */
86051  sqlite3VdbeResolveLabel(v, iLabel);
86052}
86053
86054/*
86055** This routine generates VDBE code that causes the deletion of all
86056** index entries associated with a single row of a single table.
86057**
86058** The VDBE must be in a particular state when this routine is called.
86059** These are the requirements:
86060**
86061**   1.  A read/write cursor pointing to pTab, the table containing the row
86062**       to be deleted, must be opened as cursor number "iCur".
86063**
86064**   2.  Read/write cursors for all indices of pTab must be open as
86065**       cursor number iCur+i for the i-th index.
86066**
86067**   3.  The "iCur" cursor must be pointing to the row that is to be
86068**       deleted.
86069*/
86070SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
86071  Parse *pParse,     /* Parsing and code generating context */
86072  Table *pTab,       /* Table containing the row to be deleted */
86073  int iCur,          /* Cursor number for the table */
86074  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
86075){
86076  int i;
86077  Index *pIdx;
86078  int r1;
86079
86080  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
86081    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
86082    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
86083    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
86084  }
86085}
86086
86087/*
86088** Generate code that will assemble an index key and put it in register
86089** regOut.  The key with be for index pIdx which is an index on pTab.
86090** iCur is the index of a cursor open on the pTab table and pointing to
86091** the entry that needs indexing.
86092**
86093** Return a register number which is the first in a block of
86094** registers that holds the elements of the index key.  The
86095** block of registers has already been deallocated by the time
86096** this routine returns.
86097*/
86098SQLITE_PRIVATE int sqlite3GenerateIndexKey(
86099  Parse *pParse,     /* Parsing context */
86100  Index *pIdx,       /* The index for which to generate a key */
86101  int iCur,          /* Cursor number for the pIdx->pTable table */
86102  int regOut,        /* Write the new index key to this register */
86103  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
86104){
86105  Vdbe *v = pParse->pVdbe;
86106  int j;
86107  Table *pTab = pIdx->pTable;
86108  int regBase;
86109  int nCol;
86110
86111  nCol = pIdx->nColumn;
86112  regBase = sqlite3GetTempRange(pParse, nCol+1);
86113  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
86114  for(j=0; j<nCol; j++){
86115    int idx = pIdx->aiColumn[j];
86116    if( idx==pTab->iPKey ){
86117      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
86118    }else{
86119      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
86120      sqlite3ColumnDefault(v, pTab, idx, -1);
86121    }
86122  }
86123  if( doMakeRec ){
86124    const char *zAff;
86125    if( pTab->pSelect || (pParse->db->flags & SQLITE_IdxRealAsInt)!=0 ){
86126      zAff = 0;
86127    }else{
86128      zAff = sqlite3IndexAffinityStr(v, pIdx);
86129    }
86130    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
86131    sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
86132  }
86133  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
86134  return regBase;
86135}
86136
86137/************** End of delete.c **********************************************/
86138/************** Begin file func.c ********************************************/
86139/*
86140** 2002 February 23
86141**
86142** The author disclaims copyright to this source code.  In place of
86143** a legal notice, here is a blessing:
86144**
86145**    May you do good and not evil.
86146**    May you find forgiveness for yourself and forgive others.
86147**    May you share freely, never taking more than you give.
86148**
86149*************************************************************************
86150** This file contains the C functions that implement various SQL
86151** functions of SQLite.
86152**
86153** There is only one exported symbol in this file - the function
86154** sqliteRegisterBuildinFunctions() found at the bottom of the file.
86155** All other code has file scope.
86156*/
86157/* #include <stdlib.h> */
86158/* #include <assert.h> */
86159
86160/*
86161** Return the collating function associated with a function.
86162*/
86163static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
86164  return context->pColl;
86165}
86166
86167/*
86168** Indicate that the accumulator load should be skipped on this
86169** iteration of the aggregate loop.
86170*/
86171static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
86172  context->skipFlag = 1;
86173}
86174
86175/*
86176** Implementation of the non-aggregate min() and max() functions
86177*/
86178static void minmaxFunc(
86179  sqlite3_context *context,
86180  int argc,
86181  sqlite3_value **argv
86182){
86183  int i;
86184  int mask;    /* 0 for min() or 0xffffffff for max() */
86185  int iBest;
86186  CollSeq *pColl;
86187
86188  assert( argc>1 );
86189  mask = sqlite3_user_data(context)==0 ? 0 : -1;
86190  pColl = sqlite3GetFuncCollSeq(context);
86191  assert( pColl );
86192  assert( mask==-1 || mask==0 );
86193  iBest = 0;
86194  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
86195  for(i=1; i<argc; i++){
86196    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
86197    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
86198      testcase( mask==0 );
86199      iBest = i;
86200    }
86201  }
86202  sqlite3_result_value(context, argv[iBest]);
86203}
86204
86205/*
86206** Return the type of the argument.
86207*/
86208static void typeofFunc(
86209  sqlite3_context *context,
86210  int NotUsed,
86211  sqlite3_value **argv
86212){
86213  const char *z = 0;
86214  UNUSED_PARAMETER(NotUsed);
86215  switch( sqlite3_value_type(argv[0]) ){
86216    case SQLITE_INTEGER: z = "integer"; break;
86217    case SQLITE_TEXT:    z = "text";    break;
86218    case SQLITE_FLOAT:   z = "real";    break;
86219    case SQLITE_BLOB:    z = "blob";    break;
86220    default:             z = "null";    break;
86221  }
86222  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
86223}
86224
86225
86226/*
86227** Implementation of the length() function
86228*/
86229static void lengthFunc(
86230  sqlite3_context *context,
86231  int argc,
86232  sqlite3_value **argv
86233){
86234  int len;
86235
86236  assert( argc==1 );
86237  UNUSED_PARAMETER(argc);
86238  switch( sqlite3_value_type(argv[0]) ){
86239    case SQLITE_BLOB:
86240    case SQLITE_INTEGER:
86241    case SQLITE_FLOAT: {
86242      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
86243      break;
86244    }
86245    case SQLITE_TEXT: {
86246      const unsigned char *z = sqlite3_value_text(argv[0]);
86247      if( z==0 ) return;
86248      len = 0;
86249      while( *z ){
86250        len++;
86251        SQLITE_SKIP_UTF8(z);
86252      }
86253      sqlite3_result_int(context, len);
86254      break;
86255    }
86256    default: {
86257      sqlite3_result_null(context);
86258      break;
86259    }
86260  }
86261}
86262
86263/*
86264** Implementation of the abs() function.
86265**
86266** IMP: R-23979-26855 The abs(X) function returns the absolute value of
86267** the numeric argument X.
86268*/
86269static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86270  assert( argc==1 );
86271  UNUSED_PARAMETER(argc);
86272  switch( sqlite3_value_type(argv[0]) ){
86273    case SQLITE_INTEGER: {
86274      i64 iVal = sqlite3_value_int64(argv[0]);
86275      if( iVal<0 ){
86276        if( (iVal<<1)==0 ){
86277          /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
86278          ** abs(X) throws an integer overflow error since there is no
86279          ** equivalent positive 64-bit two complement value. */
86280          sqlite3_result_error(context, "integer overflow", -1);
86281          return;
86282        }
86283        iVal = -iVal;
86284      }
86285      sqlite3_result_int64(context, iVal);
86286      break;
86287    }
86288    case SQLITE_NULL: {
86289      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
86290      sqlite3_result_null(context);
86291      break;
86292    }
86293    default: {
86294      /* Because sqlite3_value_double() returns 0.0 if the argument is not
86295      ** something that can be converted into a number, we have:
86296      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
86297      ** cannot be converted to a numeric value.
86298      */
86299      double rVal = sqlite3_value_double(argv[0]);
86300      if( rVal<0 ) rVal = -rVal;
86301      sqlite3_result_double(context, rVal);
86302      break;
86303    }
86304  }
86305}
86306
86307/*
86308** Implementation of the substr() function.
86309**
86310** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
86311** p1 is 1-indexed.  So substr(x,1,1) returns the first character
86312** of x.  If x is text, then we actually count UTF-8 characters.
86313** If x is a blob, then we count bytes.
86314**
86315** If p1 is negative, then we begin abs(p1) from the end of x[].
86316**
86317** If p2 is negative, return the p2 characters preceeding p1.
86318*/
86319static void substrFunc(
86320  sqlite3_context *context,
86321  int argc,
86322  sqlite3_value **argv
86323){
86324  const unsigned char *z;
86325  const unsigned char *z2;
86326  int len;
86327  int p0type;
86328  i64 p1, p2;
86329  int negP2 = 0;
86330
86331  assert( argc==3 || argc==2 );
86332  if( sqlite3_value_type(argv[1])==SQLITE_NULL
86333   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
86334  ){
86335    return;
86336  }
86337  p0type = sqlite3_value_type(argv[0]);
86338  p1 = sqlite3_value_int(argv[1]);
86339  if( p0type==SQLITE_BLOB ){
86340    len = sqlite3_value_bytes(argv[0]);
86341    z = sqlite3_value_blob(argv[0]);
86342    if( z==0 ) return;
86343    assert( len==sqlite3_value_bytes(argv[0]) );
86344  }else{
86345    z = sqlite3_value_text(argv[0]);
86346    if( z==0 ) return;
86347    len = 0;
86348    if( p1<0 ){
86349      for(z2=z; *z2; len++){
86350        SQLITE_SKIP_UTF8(z2);
86351      }
86352    }
86353  }
86354  if( argc==3 ){
86355    p2 = sqlite3_value_int(argv[2]);
86356    if( p2<0 ){
86357      p2 = -p2;
86358      negP2 = 1;
86359    }
86360  }else{
86361    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
86362  }
86363  if( p1<0 ){
86364    p1 += len;
86365    if( p1<0 ){
86366      p2 += p1;
86367      if( p2<0 ) p2 = 0;
86368      p1 = 0;
86369    }
86370  }else if( p1>0 ){
86371    p1--;
86372  }else if( p2>0 ){
86373    p2--;
86374  }
86375  if( negP2 ){
86376    p1 -= p2;
86377    if( p1<0 ){
86378      p2 += p1;
86379      p1 = 0;
86380    }
86381  }
86382  assert( p1>=0 && p2>=0 );
86383  if( p0type!=SQLITE_BLOB ){
86384    while( *z && p1 ){
86385      SQLITE_SKIP_UTF8(z);
86386      p1--;
86387    }
86388    for(z2=z; *z2 && p2; p2--){
86389      SQLITE_SKIP_UTF8(z2);
86390    }
86391    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
86392  }else{
86393    if( p1+p2>len ){
86394      p2 = len-p1;
86395      if( p2<0 ) p2 = 0;
86396    }
86397    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
86398  }
86399}
86400
86401/*
86402** Implementation of the round() function
86403*/
86404#ifndef SQLITE_OMIT_FLOATING_POINT
86405static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86406  int n = 0;
86407  double r;
86408  char *zBuf;
86409  assert( argc==1 || argc==2 );
86410  if( argc==2 ){
86411    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
86412    n = sqlite3_value_int(argv[1]);
86413    if( n>30 ) n = 30;
86414    if( n<0 ) n = 0;
86415  }
86416  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
86417  r = sqlite3_value_double(argv[0]);
86418  /* If Y==0 and X will fit in a 64-bit int,
86419  ** handle the rounding directly,
86420  ** otherwise use printf.
86421  */
86422  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
86423    r = (double)((sqlite_int64)(r+0.5));
86424  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
86425    r = -(double)((sqlite_int64)((-r)+0.5));
86426  }else{
86427    zBuf = sqlite3_mprintf("%.*f",n,r);
86428    if( zBuf==0 ){
86429      sqlite3_result_error_nomem(context);
86430      return;
86431    }
86432    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
86433    sqlite3_free(zBuf);
86434  }
86435  sqlite3_result_double(context, r);
86436}
86437#endif
86438
86439/*
86440** Allocate nByte bytes of space using sqlite3_malloc(). If the
86441** allocation fails, call sqlite3_result_error_nomem() to notify
86442** the database handle that malloc() has failed and return NULL.
86443** If nByte is larger than the maximum string or blob length, then
86444** raise an SQLITE_TOOBIG exception and return NULL.
86445*/
86446static void *contextMalloc(sqlite3_context *context, i64 nByte){
86447  char *z;
86448  sqlite3 *db = sqlite3_context_db_handle(context);
86449  assert( nByte>0 );
86450  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
86451  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
86452  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
86453    sqlite3_result_error_toobig(context);
86454    z = 0;
86455  }else{
86456    z = sqlite3Malloc((int)nByte);
86457    if( !z ){
86458      sqlite3_result_error_nomem(context);
86459    }
86460  }
86461  return z;
86462}
86463
86464/*
86465** Implementation of the upper() and lower() SQL functions.
86466*/
86467static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86468  char *z1;
86469  const char *z2;
86470  int i, n;
86471  UNUSED_PARAMETER(argc);
86472  z2 = (char*)sqlite3_value_text(argv[0]);
86473  n = sqlite3_value_bytes(argv[0]);
86474  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86475  assert( z2==(char*)sqlite3_value_text(argv[0]) );
86476  if( z2 ){
86477    z1 = contextMalloc(context, ((i64)n)+1);
86478    if( z1 ){
86479      for(i=0; i<n; i++){
86480        z1[i] = (char)sqlite3Toupper(z2[i]);
86481      }
86482      sqlite3_result_text(context, z1, n, sqlite3_free);
86483    }
86484  }
86485}
86486static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86487  char *z1;
86488  const char *z2;
86489  int i, n;
86490  UNUSED_PARAMETER(argc);
86491  z2 = (char*)sqlite3_value_text(argv[0]);
86492  n = sqlite3_value_bytes(argv[0]);
86493  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86494  assert( z2==(char*)sqlite3_value_text(argv[0]) );
86495  if( z2 ){
86496    z1 = contextMalloc(context, ((i64)n)+1);
86497    if( z1 ){
86498      for(i=0; i<n; i++){
86499        z1[i] = sqlite3Tolower(z2[i]);
86500      }
86501      sqlite3_result_text(context, z1, n, sqlite3_free);
86502    }
86503  }
86504}
86505
86506
86507#if 0  /* This function is never used. */
86508/*
86509** The COALESCE() and IFNULL() functions used to be implemented as shown
86510** here.  But now they are implemented as VDBE code so that unused arguments
86511** do not have to be computed.  This legacy implementation is retained as
86512** comment.
86513*/
86514/*
86515** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
86516** All three do the same thing.  They return the first non-NULL
86517** argument.
86518*/
86519static void ifnullFunc(
86520  sqlite3_context *context,
86521  int argc,
86522  sqlite3_value **argv
86523){
86524  int i;
86525  for(i=0; i<argc; i++){
86526    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
86527      sqlite3_result_value(context, argv[i]);
86528      break;
86529    }
86530  }
86531}
86532#endif /* NOT USED */
86533#define ifnullFunc versionFunc   /* Substitute function - never called */
86534
86535/*
86536** Implementation of random().  Return a random integer.
86537*/
86538static void randomFunc(
86539  sqlite3_context *context,
86540  int NotUsed,
86541  sqlite3_value **NotUsed2
86542){
86543  sqlite_int64 r;
86544  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86545  sqlite3_randomness(sizeof(r), &r);
86546  if( r<0 ){
86547    /* We need to prevent a random number of 0x8000000000000000
86548    ** (or -9223372036854775808) since when you do abs() of that
86549    ** number of you get the same value back again.  To do this
86550    ** in a way that is testable, mask the sign bit off of negative
86551    ** values, resulting in a positive value.  Then take the
86552    ** 2s complement of that positive value.  The end result can
86553    ** therefore be no less than -9223372036854775807.
86554    */
86555    r = -(r & LARGEST_INT64);
86556  }
86557  sqlite3_result_int64(context, r);
86558}
86559
86560/*
86561** Implementation of randomblob(N).  Return a random blob
86562** that is N bytes long.
86563*/
86564static void randomBlob(
86565  sqlite3_context *context,
86566  int argc,
86567  sqlite3_value **argv
86568){
86569  int n;
86570  unsigned char *p;
86571  assert( argc==1 );
86572  UNUSED_PARAMETER(argc);
86573  n = sqlite3_value_int(argv[0]);
86574  if( n<1 ){
86575    n = 1;
86576  }
86577  p = contextMalloc(context, n);
86578  if( p ){
86579    sqlite3_randomness(n, p);
86580    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
86581  }
86582}
86583
86584/*
86585** Implementation of the last_insert_rowid() SQL function.  The return
86586** value is the same as the sqlite3_last_insert_rowid() API function.
86587*/
86588static void last_insert_rowid(
86589  sqlite3_context *context,
86590  int NotUsed,
86591  sqlite3_value **NotUsed2
86592){
86593  sqlite3 *db = sqlite3_context_db_handle(context);
86594  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86595  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
86596  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
86597  ** function. */
86598  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
86599}
86600
86601/*
86602** Implementation of the changes() SQL function.
86603**
86604** IMP: R-62073-11209 The changes() SQL function is a wrapper
86605** around the sqlite3_changes() C/C++ function and hence follows the same
86606** rules for counting changes.
86607*/
86608static void changes(
86609  sqlite3_context *context,
86610  int NotUsed,
86611  sqlite3_value **NotUsed2
86612){
86613  sqlite3 *db = sqlite3_context_db_handle(context);
86614  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86615  sqlite3_result_int(context, sqlite3_changes(db));
86616}
86617
86618/*
86619** Implementation of the total_changes() SQL function.  The return value is
86620** the same as the sqlite3_total_changes() API function.
86621*/
86622static void total_changes(
86623  sqlite3_context *context,
86624  int NotUsed,
86625  sqlite3_value **NotUsed2
86626){
86627  sqlite3 *db = sqlite3_context_db_handle(context);
86628  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86629  /* IMP: R-52756-41993 This function is a wrapper around the
86630  ** sqlite3_total_changes() C/C++ interface. */
86631  sqlite3_result_int(context, sqlite3_total_changes(db));
86632}
86633
86634/*
86635** A structure defining how to do GLOB-style comparisons.
86636*/
86637struct compareInfo {
86638  u8 matchAll;
86639  u8 matchOne;
86640  u8 matchSet;
86641  u8 noCase;
86642};
86643
86644/*
86645** For LIKE and GLOB matching on EBCDIC machines, assume that every
86646** character is exactly one byte in size.  Also, all characters are
86647** able to participate in upper-case-to-lower-case mappings in EBCDIC
86648** whereas only characters less than 0x80 do in ASCII.
86649*/
86650#if defined(SQLITE_EBCDIC)
86651# define sqlite3Utf8Read(A,C)  (*(A++))
86652# define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
86653#else
86654# define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
86655#endif
86656
86657static const struct compareInfo globInfo = { '*', '?', '[', 0 };
86658/* The correct SQL-92 behavior is for the LIKE operator to ignore
86659** case.  Thus  'a' LIKE 'A' would be true. */
86660static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
86661/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
86662** is case sensitive causing 'a' LIKE 'A' to be false */
86663static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
86664
86665/*
86666** Compare two UTF-8 strings for equality where the first string can
86667** potentially be a "glob" expression.  Return true (1) if they
86668** are the same and false (0) if they are different.
86669**
86670** Globbing rules:
86671**
86672**      '*'       Matches any sequence of zero or more characters.
86673**
86674**      '?'       Matches exactly one character.
86675**
86676**     [...]      Matches one character from the enclosed list of
86677**                characters.
86678**
86679**     [^...]     Matches one character not in the enclosed list.
86680**
86681** With the [...] and [^...] matching, a ']' character can be included
86682** in the list by making it the first character after '[' or '^'.  A
86683** range of characters can be specified using '-'.  Example:
86684** "[a-z]" matches any single lower-case letter.  To match a '-', make
86685** it the last character in the list.
86686**
86687** This routine is usually quick, but can be N**2 in the worst case.
86688**
86689** Hints: to match '*' or '?', put them in "[]".  Like this:
86690**
86691**         abc[*]xyz        Matches "abc*xyz" only
86692*/
86693static int patternCompare(
86694  const u8 *zPattern,              /* The glob pattern */
86695  const u8 *zString,               /* The string to compare against the glob */
86696  const struct compareInfo *pInfo, /* Information about how to do the compare */
86697  u32 esc                          /* The escape character */
86698){
86699  u32 c, c2;
86700  int invert;
86701  int seen;
86702  u8 matchOne = pInfo->matchOne;
86703  u8 matchAll = pInfo->matchAll;
86704  u8 matchSet = pInfo->matchSet;
86705  u8 noCase = pInfo->noCase;
86706  int prevEscape = 0;     /* True if the previous character was 'escape' */
86707
86708  while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
86709    if( !prevEscape && c==matchAll ){
86710      while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
86711               || c == matchOne ){
86712        if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
86713          return 0;
86714        }
86715      }
86716      if( c==0 ){
86717        return 1;
86718      }else if( c==esc ){
86719        c = sqlite3Utf8Read(zPattern, &zPattern);
86720        if( c==0 ){
86721          return 0;
86722        }
86723      }else if( c==matchSet ){
86724        assert( esc==0 );         /* This is GLOB, not LIKE */
86725        assert( matchSet<0x80 );  /* '[' is a single-byte character */
86726        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
86727          SQLITE_SKIP_UTF8(zString);
86728        }
86729        return *zString!=0;
86730      }
86731      while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
86732        if( noCase ){
86733          GlogUpperToLower(c2);
86734          GlogUpperToLower(c);
86735          while( c2 != 0 && c2 != c ){
86736            c2 = sqlite3Utf8Read(zString, &zString);
86737            GlogUpperToLower(c2);
86738          }
86739        }else{
86740          while( c2 != 0 && c2 != c ){
86741            c2 = sqlite3Utf8Read(zString, &zString);
86742          }
86743        }
86744        if( c2==0 ) return 0;
86745        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
86746      }
86747      return 0;
86748    }else if( !prevEscape && c==matchOne ){
86749      if( sqlite3Utf8Read(zString, &zString)==0 ){
86750        return 0;
86751      }
86752    }else if( c==matchSet ){
86753      u32 prior_c = 0;
86754      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
86755      seen = 0;
86756      invert = 0;
86757      c = sqlite3Utf8Read(zString, &zString);
86758      if( c==0 ) return 0;
86759      c2 = sqlite3Utf8Read(zPattern, &zPattern);
86760      if( c2=='^' ){
86761        invert = 1;
86762        c2 = sqlite3Utf8Read(zPattern, &zPattern);
86763      }
86764      if( c2==']' ){
86765        if( c==']' ) seen = 1;
86766        c2 = sqlite3Utf8Read(zPattern, &zPattern);
86767      }
86768      while( c2 && c2!=']' ){
86769        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
86770          c2 = sqlite3Utf8Read(zPattern, &zPattern);
86771          if( c>=prior_c && c<=c2 ) seen = 1;
86772          prior_c = 0;
86773        }else{
86774          if( c==c2 ){
86775            seen = 1;
86776          }
86777          prior_c = c2;
86778        }
86779        c2 = sqlite3Utf8Read(zPattern, &zPattern);
86780      }
86781      if( c2==0 || (seen ^ invert)==0 ){
86782        return 0;
86783      }
86784    }else if( esc==c && !prevEscape ){
86785      prevEscape = 1;
86786    }else{
86787      c2 = sqlite3Utf8Read(zString, &zString);
86788      if( noCase ){
86789        GlogUpperToLower(c);
86790        GlogUpperToLower(c2);
86791      }
86792      if( c!=c2 ){
86793        return 0;
86794      }
86795      prevEscape = 0;
86796    }
86797  }
86798  return *zString==0;
86799}
86800
86801/*
86802** Count the number of times that the LIKE operator (or GLOB which is
86803** just a variation of LIKE) gets called.  This is used for testing
86804** only.
86805*/
86806#ifdef SQLITE_TEST
86807SQLITE_API int sqlite3_like_count = 0;
86808#endif
86809
86810
86811/*
86812** Implementation of the like() SQL function.  This function implements
86813** the build-in LIKE operator.  The first argument to the function is the
86814** pattern and the second argument is the string.  So, the SQL statements:
86815**
86816**       A LIKE B
86817**
86818** is implemented as like(B,A).
86819**
86820** This same function (with a different compareInfo structure) computes
86821** the GLOB operator.
86822*/
86823static void likeFunc(
86824  sqlite3_context *context,
86825  int argc,
86826  sqlite3_value **argv
86827){
86828  const unsigned char *zA, *zB;
86829  u32 escape = 0;
86830  int nPat;
86831  sqlite3 *db = sqlite3_context_db_handle(context);
86832
86833  zB = sqlite3_value_text(argv[0]);
86834  zA = sqlite3_value_text(argv[1]);
86835
86836  /* Limit the length of the LIKE or GLOB pattern to avoid problems
86837  ** of deep recursion and N*N behavior in patternCompare().
86838  */
86839  nPat = sqlite3_value_bytes(argv[0]);
86840  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
86841  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
86842  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
86843    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
86844    return;
86845  }
86846  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
86847
86848  if( argc==3 ){
86849    /* The escape character string must consist of a single UTF-8 character.
86850    ** Otherwise, return an error.
86851    */
86852    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
86853    if( zEsc==0 ) return;
86854    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
86855      sqlite3_result_error(context,
86856          "ESCAPE expression must be a single character", -1);
86857      return;
86858    }
86859    escape = sqlite3Utf8Read(zEsc, &zEsc);
86860  }
86861  if( zA && zB ){
86862    struct compareInfo *pInfo = sqlite3_user_data(context);
86863#ifdef SQLITE_TEST
86864    sqlite3_like_count++;
86865#endif
86866
86867    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
86868  }
86869}
86870
86871/*
86872** Implementation of the NULLIF(x,y) function.  The result is the first
86873** argument if the arguments are different.  The result is NULL if the
86874** arguments are equal to each other.
86875*/
86876static void nullifFunc(
86877  sqlite3_context *context,
86878  int NotUsed,
86879  sqlite3_value **argv
86880){
86881  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
86882  UNUSED_PARAMETER(NotUsed);
86883  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
86884    sqlite3_result_value(context, argv[0]);
86885  }
86886}
86887
86888/*
86889** Implementation of the sqlite_version() function.  The result is the version
86890** of the SQLite library that is running.
86891*/
86892static void versionFunc(
86893  sqlite3_context *context,
86894  int NotUsed,
86895  sqlite3_value **NotUsed2
86896){
86897  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86898  /* IMP: R-48699-48617 This function is an SQL wrapper around the
86899  ** sqlite3_libversion() C-interface. */
86900  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
86901}
86902
86903/*
86904** Implementation of the sqlite_source_id() function. The result is a string
86905** that identifies the particular version of the source code used to build
86906** SQLite.
86907*/
86908static void sourceidFunc(
86909  sqlite3_context *context,
86910  int NotUsed,
86911  sqlite3_value **NotUsed2
86912){
86913  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86914  /* IMP: R-24470-31136 This function is an SQL wrapper around the
86915  ** sqlite3_sourceid() C interface. */
86916  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
86917}
86918
86919/*
86920** Implementation of the sqlite_log() function.  This is a wrapper around
86921** sqlite3_log().  The return value is NULL.  The function exists purely for
86922** its side-effects.
86923*/
86924static void errlogFunc(
86925  sqlite3_context *context,
86926  int argc,
86927  sqlite3_value **argv
86928){
86929  UNUSED_PARAMETER(argc);
86930  UNUSED_PARAMETER(context);
86931  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
86932}
86933
86934/*
86935** Implementation of the sqlite_compileoption_used() function.
86936** The result is an integer that identifies if the compiler option
86937** was used to build SQLite.
86938*/
86939#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86940static void compileoptionusedFunc(
86941  sqlite3_context *context,
86942  int argc,
86943  sqlite3_value **argv
86944){
86945  const char *zOptName;
86946  assert( argc==1 );
86947  UNUSED_PARAMETER(argc);
86948  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
86949  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
86950  ** function.
86951  */
86952  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
86953    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
86954  }
86955}
86956#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86957
86958/*
86959** Implementation of the sqlite_compileoption_get() function.
86960** The result is a string that identifies the compiler options
86961** used to build SQLite.
86962*/
86963#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86964static void compileoptiongetFunc(
86965  sqlite3_context *context,
86966  int argc,
86967  sqlite3_value **argv
86968){
86969  int n;
86970  assert( argc==1 );
86971  UNUSED_PARAMETER(argc);
86972  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
86973  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
86974  */
86975  n = sqlite3_value_int(argv[0]);
86976  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
86977}
86978#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86979
86980/* Array for converting from half-bytes (nybbles) into ASCII hex
86981** digits. */
86982static const char hexdigits[] = {
86983  '0', '1', '2', '3', '4', '5', '6', '7',
86984  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
86985};
86986
86987/*
86988** EXPERIMENTAL - This is not an official function.  The interface may
86989** change.  This function may disappear.  Do not write code that depends
86990** on this function.
86991**
86992** Implementation of the QUOTE() function.  This function takes a single
86993** argument.  If the argument is numeric, the return value is the same as
86994** the argument.  If the argument is NULL, the return value is the string
86995** "NULL".  Otherwise, the argument is enclosed in single quotes with
86996** single-quote escapes.
86997*/
86998static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86999  assert( argc==1 );
87000  UNUSED_PARAMETER(argc);
87001  switch( sqlite3_value_type(argv[0]) ){
87002    case SQLITE_INTEGER:
87003    case SQLITE_FLOAT: {
87004      sqlite3_result_value(context, argv[0]);
87005      break;
87006    }
87007    case SQLITE_BLOB: {
87008      char *zText = 0;
87009      char const *zBlob = sqlite3_value_blob(argv[0]);
87010      int nBlob = sqlite3_value_bytes(argv[0]);
87011      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
87012      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
87013      if( zText ){
87014        int i;
87015        for(i=0; i<nBlob; i++){
87016          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
87017          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
87018        }
87019        zText[(nBlob*2)+2] = '\'';
87020        zText[(nBlob*2)+3] = '\0';
87021        zText[0] = 'X';
87022        zText[1] = '\'';
87023        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
87024        sqlite3_free(zText);
87025      }
87026      break;
87027    }
87028    case SQLITE_TEXT: {
87029      int i,j;
87030      u64 n;
87031      const unsigned char *zArg = sqlite3_value_text(argv[0]);
87032      char *z;
87033
87034      if( zArg==0 ) return;
87035      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
87036      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
87037      if( z ){
87038        z[0] = '\'';
87039        for(i=0, j=1; zArg[i]; i++){
87040          z[j++] = zArg[i];
87041          if( zArg[i]=='\'' ){
87042            z[j++] = '\'';
87043          }
87044        }
87045        z[j++] = '\'';
87046        z[j] = 0;
87047        sqlite3_result_text(context, z, j, sqlite3_free);
87048      }
87049      break;
87050    }
87051    default: {
87052      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
87053      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
87054      break;
87055    }
87056  }
87057}
87058
87059/*
87060** The hex() function.  Interpret the argument as a blob.  Return
87061** a hexadecimal rendering as text.
87062*/
87063static void hexFunc(
87064  sqlite3_context *context,
87065  int argc,
87066  sqlite3_value **argv
87067){
87068  int i, n;
87069  const unsigned char *pBlob;
87070  char *zHex, *z;
87071  assert( argc==1 );
87072  UNUSED_PARAMETER(argc);
87073  pBlob = sqlite3_value_blob(argv[0]);
87074  n = sqlite3_value_bytes(argv[0]);
87075  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
87076  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
87077  if( zHex ){
87078    for(i=0; i<n; i++, pBlob++){
87079      unsigned char c = *pBlob;
87080      *(z++) = hexdigits[(c>>4)&0xf];
87081      *(z++) = hexdigits[c&0xf];
87082    }
87083    *z = 0;
87084    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
87085  }
87086}
87087
87088/*
87089** The zeroblob(N) function returns a zero-filled blob of size N bytes.
87090*/
87091static void zeroblobFunc(
87092  sqlite3_context *context,
87093  int argc,
87094  sqlite3_value **argv
87095){
87096  i64 n;
87097  sqlite3 *db = sqlite3_context_db_handle(context);
87098  assert( argc==1 );
87099  UNUSED_PARAMETER(argc);
87100  n = sqlite3_value_int64(argv[0]);
87101  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
87102  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
87103  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
87104    sqlite3_result_error_toobig(context);
87105  }else{
87106    sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
87107  }
87108}
87109
87110/*
87111** The replace() function.  Three arguments are all strings: call
87112** them A, B, and C. The result is also a string which is derived
87113** from A by replacing every occurance of B with C.  The match
87114** must be exact.  Collating sequences are not used.
87115*/
87116static void replaceFunc(
87117  sqlite3_context *context,
87118  int argc,
87119  sqlite3_value **argv
87120){
87121  const unsigned char *zStr;        /* The input string A */
87122  const unsigned char *zPattern;    /* The pattern string B */
87123  const unsigned char *zRep;        /* The replacement string C */
87124  unsigned char *zOut;              /* The output */
87125  int nStr;                /* Size of zStr */
87126  int nPattern;            /* Size of zPattern */
87127  int nRep;                /* Size of zRep */
87128  i64 nOut;                /* Maximum size of zOut */
87129  int loopLimit;           /* Last zStr[] that might match zPattern[] */
87130  int i, j;                /* Loop counters */
87131
87132  assert( argc==3 );
87133  UNUSED_PARAMETER(argc);
87134  zStr = sqlite3_value_text(argv[0]);
87135  if( zStr==0 ) return;
87136  nStr = sqlite3_value_bytes(argv[0]);
87137  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
87138  zPattern = sqlite3_value_text(argv[1]);
87139  if( zPattern==0 ){
87140    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
87141            || sqlite3_context_db_handle(context)->mallocFailed );
87142    return;
87143  }
87144  if( zPattern[0]==0 ){
87145    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
87146    sqlite3_result_value(context, argv[0]);
87147    return;
87148  }
87149  nPattern = sqlite3_value_bytes(argv[1]);
87150  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
87151  zRep = sqlite3_value_text(argv[2]);
87152  if( zRep==0 ) return;
87153  nRep = sqlite3_value_bytes(argv[2]);
87154  assert( zRep==sqlite3_value_text(argv[2]) );
87155  nOut = nStr + 1;
87156  assert( nOut<SQLITE_MAX_LENGTH );
87157  zOut = contextMalloc(context, (i64)nOut);
87158  if( zOut==0 ){
87159    return;
87160  }
87161  loopLimit = nStr - nPattern;
87162  for(i=j=0; i<=loopLimit; i++){
87163    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
87164      zOut[j++] = zStr[i];
87165    }else{
87166      u8 *zOld;
87167      sqlite3 *db = sqlite3_context_db_handle(context);
87168      nOut += nRep - nPattern;
87169      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
87170      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
87171      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
87172        sqlite3_result_error_toobig(context);
87173        sqlite3_free(zOut);
87174        return;
87175      }
87176      zOld = zOut;
87177      zOut = sqlite3_realloc(zOut, (int)nOut);
87178      if( zOut==0 ){
87179        sqlite3_result_error_nomem(context);
87180        sqlite3_free(zOld);
87181        return;
87182      }
87183      memcpy(&zOut[j], zRep, nRep);
87184      j += nRep;
87185      i += nPattern-1;
87186    }
87187  }
87188  assert( j+nStr-i+1==nOut );
87189  memcpy(&zOut[j], &zStr[i], nStr-i);
87190  j += nStr - i;
87191  assert( j<=nOut );
87192  zOut[j] = 0;
87193  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
87194}
87195
87196/*
87197** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
87198** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
87199*/
87200static void trimFunc(
87201  sqlite3_context *context,
87202  int argc,
87203  sqlite3_value **argv
87204){
87205  const unsigned char *zIn;         /* Input string */
87206  const unsigned char *zCharSet;    /* Set of characters to trim */
87207  int nIn;                          /* Number of bytes in input */
87208  int flags;                        /* 1: trimleft  2: trimright  3: trim */
87209  int i;                            /* Loop counter */
87210  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
87211  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
87212  int nChar;                        /* Number of characters in zCharSet */
87213
87214  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
87215    return;
87216  }
87217  zIn = sqlite3_value_text(argv[0]);
87218  if( zIn==0 ) return;
87219  nIn = sqlite3_value_bytes(argv[0]);
87220  assert( zIn==sqlite3_value_text(argv[0]) );
87221  if( argc==1 ){
87222    static const unsigned char lenOne[] = { 1 };
87223    static unsigned char * const azOne[] = { (u8*)" " };
87224    nChar = 1;
87225    aLen = (u8*)lenOne;
87226    azChar = (unsigned char **)azOne;
87227    zCharSet = 0;
87228  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
87229    return;
87230  }else{
87231    const unsigned char *z;
87232    for(z=zCharSet, nChar=0; *z; nChar++){
87233      SQLITE_SKIP_UTF8(z);
87234    }
87235    if( nChar>0 ){
87236      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
87237      if( azChar==0 ){
87238        return;
87239      }
87240      aLen = (unsigned char*)&azChar[nChar];
87241      for(z=zCharSet, nChar=0; *z; nChar++){
87242        azChar[nChar] = (unsigned char *)z;
87243        SQLITE_SKIP_UTF8(z);
87244        aLen[nChar] = (u8)(z - azChar[nChar]);
87245      }
87246    }
87247  }
87248  if( nChar>0 ){
87249    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
87250    if( flags & 1 ){
87251      while( nIn>0 ){
87252        int len = 0;
87253        for(i=0; i<nChar; i++){
87254          len = aLen[i];
87255          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
87256        }
87257        if( i>=nChar ) break;
87258        zIn += len;
87259        nIn -= len;
87260      }
87261    }
87262    if( flags & 2 ){
87263      while( nIn>0 ){
87264        int len = 0;
87265        for(i=0; i<nChar; i++){
87266          len = aLen[i];
87267          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
87268        }
87269        if( i>=nChar ) break;
87270        nIn -= len;
87271      }
87272    }
87273    if( zCharSet ){
87274      sqlite3_free(azChar);
87275    }
87276  }
87277  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
87278}
87279
87280
87281/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
87282** is only available if the SQLITE_SOUNDEX compile-time option is used
87283** when SQLite is built.
87284*/
87285#ifdef SQLITE_SOUNDEX
87286/*
87287** Compute the soundex encoding of a word.
87288**
87289** IMP: R-59782-00072 The soundex(X) function returns a string that is the
87290** soundex encoding of the string X.
87291*/
87292static void soundexFunc(
87293  sqlite3_context *context,
87294  int argc,
87295  sqlite3_value **argv
87296){
87297  char zResult[8];
87298  const u8 *zIn;
87299  int i, j;
87300  static const unsigned char iCode[] = {
87301    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87302    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87303    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87304    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87305    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
87306    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
87307    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
87308    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
87309  };
87310  assert( argc==1 );
87311  zIn = (u8*)sqlite3_value_text(argv[0]);
87312  if( zIn==0 ) zIn = (u8*)"";
87313  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
87314  if( zIn[i] ){
87315    u8 prevcode = iCode[zIn[i]&0x7f];
87316    zResult[0] = sqlite3Toupper(zIn[i]);
87317    for(j=1; j<4 && zIn[i]; i++){
87318      int code = iCode[zIn[i]&0x7f];
87319      if( code>0 ){
87320        if( code!=prevcode ){
87321          prevcode = code;
87322          zResult[j++] = code + '0';
87323        }
87324      }else{
87325        prevcode = 0;
87326      }
87327    }
87328    while( j<4 ){
87329      zResult[j++] = '0';
87330    }
87331    zResult[j] = 0;
87332    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
87333  }else{
87334    /* IMP: R-64894-50321 The string "?000" is returned if the argument
87335    ** is NULL or contains no ASCII alphabetic characters. */
87336    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
87337  }
87338}
87339#endif /* SQLITE_SOUNDEX */
87340
87341#ifndef SQLITE_OMIT_LOAD_EXTENSION
87342/*
87343** A function that loads a shared-library extension then returns NULL.
87344*/
87345static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
87346  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
87347  const char *zProc;
87348  sqlite3 *db = sqlite3_context_db_handle(context);
87349  char *zErrMsg = 0;
87350
87351  if( argc==2 ){
87352    zProc = (const char *)sqlite3_value_text(argv[1]);
87353  }else{
87354    zProc = 0;
87355  }
87356  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
87357    sqlite3_result_error(context, zErrMsg, -1);
87358    sqlite3_free(zErrMsg);
87359  }
87360}
87361#endif
87362
87363
87364/*
87365** An instance of the following structure holds the context of a
87366** sum() or avg() aggregate computation.
87367*/
87368typedef struct SumCtx SumCtx;
87369struct SumCtx {
87370  double rSum;      /* Floating point sum */
87371  i64 iSum;         /* Integer sum */
87372  i64 cnt;          /* Number of elements summed */
87373  u8 overflow;      /* True if integer overflow seen */
87374  u8 approx;        /* True if non-integer value was input to the sum */
87375};
87376
87377/*
87378** Routines used to compute the sum, average, and total.
87379**
87380** The SUM() function follows the (broken) SQL standard which means
87381** that it returns NULL if it sums over no inputs.  TOTAL returns
87382** 0.0 in that case.  In addition, TOTAL always returns a float where
87383** SUM might return an integer if it never encounters a floating point
87384** value.  TOTAL never fails, but SUM might through an exception if
87385** it overflows an integer.
87386*/
87387static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
87388  SumCtx *p;
87389  int type;
87390  assert( argc==1 );
87391  UNUSED_PARAMETER(argc);
87392  p = sqlite3_aggregate_context(context, sizeof(*p));
87393  type = sqlite3_value_numeric_type(argv[0]);
87394  if( p && type!=SQLITE_NULL ){
87395    p->cnt++;
87396    if( type==SQLITE_INTEGER ){
87397      i64 v = sqlite3_value_int64(argv[0]);
87398      p->rSum += v;
87399      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
87400        p->overflow = 1;
87401      }
87402    }else{
87403      p->rSum += sqlite3_value_double(argv[0]);
87404      p->approx = 1;
87405    }
87406  }
87407}
87408static void sumFinalize(sqlite3_context *context){
87409  SumCtx *p;
87410  p = sqlite3_aggregate_context(context, 0);
87411  if( p && p->cnt>0 ){
87412    if( p->overflow ){
87413      sqlite3_result_error(context,"integer overflow",-1);
87414    }else if( p->approx ){
87415      sqlite3_result_double(context, p->rSum);
87416    }else{
87417      sqlite3_result_int64(context, p->iSum);
87418    }
87419  }
87420}
87421static void avgFinalize(sqlite3_context *context){
87422  SumCtx *p;
87423  p = sqlite3_aggregate_context(context, 0);
87424  if( p && p->cnt>0 ){
87425    sqlite3_result_double(context, p->rSum/(double)p->cnt);
87426  }
87427}
87428static void totalFinalize(sqlite3_context *context){
87429  SumCtx *p;
87430  p = sqlite3_aggregate_context(context, 0);
87431  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
87432  sqlite3_result_double(context, p ? p->rSum : (double)0);
87433}
87434
87435/*
87436** The following structure keeps track of state information for the
87437** count() aggregate function.
87438*/
87439typedef struct CountCtx CountCtx;
87440struct CountCtx {
87441  i64 n;
87442};
87443
87444/*
87445** Routines to implement the count() aggregate function.
87446*/
87447static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
87448  CountCtx *p;
87449  p = sqlite3_aggregate_context(context, sizeof(*p));
87450  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
87451    p->n++;
87452  }
87453
87454#ifndef SQLITE_OMIT_DEPRECATED
87455  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
87456  ** sure it still operates correctly, verify that its count agrees with our
87457  ** internal count when using count(*) and when the total count can be
87458  ** expressed as a 32-bit integer. */
87459  assert( argc==1 || p==0 || p->n>0x7fffffff
87460          || p->n==sqlite3_aggregate_count(context) );
87461#endif
87462}
87463static void countFinalize(sqlite3_context *context){
87464  CountCtx *p;
87465  p = sqlite3_aggregate_context(context, 0);
87466  sqlite3_result_int64(context, p ? p->n : 0);
87467}
87468
87469/*
87470** Routines to implement min() and max() aggregate functions.
87471*/
87472static void minmaxStep(
87473  sqlite3_context *context,
87474  int NotUsed,
87475  sqlite3_value **argv
87476){
87477  Mem *pArg  = (Mem *)argv[0];
87478  Mem *pBest;
87479  UNUSED_PARAMETER(NotUsed);
87480
87481  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
87482  if( !pBest ) return;
87483
87484  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
87485    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
87486  }else if( pBest->flags ){
87487    int max;
87488    int cmp;
87489    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
87490    /* This step function is used for both the min() and max() aggregates,
87491    ** the only difference between the two being that the sense of the
87492    ** comparison is inverted. For the max() aggregate, the
87493    ** sqlite3_user_data() function returns (void *)-1. For min() it
87494    ** returns (void *)db, where db is the sqlite3* database pointer.
87495    ** Therefore the next statement sets variable 'max' to 1 for the max()
87496    ** aggregate, or 0 for min().
87497    */
87498    max = sqlite3_user_data(context)!=0;
87499    cmp = sqlite3MemCompare(pBest, pArg, pColl);
87500    if( (max && cmp<0) || (!max && cmp>0) ){
87501      sqlite3VdbeMemCopy(pBest, pArg);
87502    }else{
87503      sqlite3SkipAccumulatorLoad(context);
87504    }
87505  }else{
87506    sqlite3VdbeMemCopy(pBest, pArg);
87507  }
87508}
87509static void minMaxFinalize(sqlite3_context *context){
87510  sqlite3_value *pRes;
87511  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
87512  if( pRes ){
87513    if( pRes->flags ){
87514      sqlite3_result_value(context, pRes);
87515    }
87516    sqlite3VdbeMemRelease(pRes);
87517  }
87518}
87519
87520/*
87521** group_concat(EXPR, ?SEPARATOR?)
87522*/
87523static void groupConcatStep(
87524  sqlite3_context *context,
87525  int argc,
87526  sqlite3_value **argv
87527){
87528  const char *zVal;
87529  StrAccum *pAccum;
87530  const char *zSep;
87531  int nVal, nSep;
87532  assert( argc==1 || argc==2 );
87533  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87534  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
87535
87536  if( pAccum ){
87537    sqlite3 *db = sqlite3_context_db_handle(context);
87538    int firstTerm = pAccum->useMalloc==0;
87539    pAccum->useMalloc = 2;
87540    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
87541    if( !firstTerm ){
87542      if( argc==2 ){
87543        zSep = (char*)sqlite3_value_text(argv[1]);
87544        nSep = sqlite3_value_bytes(argv[1]);
87545      }else{
87546        zSep = ",";
87547        nSep = 1;
87548      }
87549      sqlite3StrAccumAppend(pAccum, zSep, nSep);
87550    }
87551    zVal = (char*)sqlite3_value_text(argv[0]);
87552    nVal = sqlite3_value_bytes(argv[0]);
87553    sqlite3StrAccumAppend(pAccum, zVal, nVal);
87554  }
87555}
87556static void groupConcatFinalize(sqlite3_context *context){
87557  StrAccum *pAccum;
87558  pAccum = sqlite3_aggregate_context(context, 0);
87559  if( pAccum ){
87560    if( pAccum->tooBig ){
87561      sqlite3_result_error_toobig(context);
87562    }else if( pAccum->mallocFailed ){
87563      sqlite3_result_error_nomem(context);
87564    }else{
87565      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
87566                          sqlite3_free);
87567    }
87568  }
87569}
87570
87571/*
87572** This routine does per-connection function registration.  Most
87573** of the built-in functions above are part of the global function set.
87574** This routine only deals with those that are not global.
87575*/
87576SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
87577  int rc = sqlite3_overload_function(db, "MATCH", 2);
87578  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
87579  if( rc==SQLITE_NOMEM ){
87580    db->mallocFailed = 1;
87581  }
87582}
87583
87584/*
87585** Set the LIKEOPT flag on the 2-argument function with the given name.
87586*/
87587static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
87588  FuncDef *pDef;
87589  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
87590                             2, SQLITE_UTF8, 0);
87591  if( ALWAYS(pDef) ){
87592    pDef->flags = flagVal;
87593  }
87594}
87595
87596/*
87597** Register the built-in LIKE and GLOB functions.  The caseSensitive
87598** parameter determines whether or not the LIKE operator is case
87599** sensitive.  GLOB is always case sensitive.
87600*/
87601SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
87602  struct compareInfo *pInfo;
87603  if( caseSensitive ){
87604    pInfo = (struct compareInfo*)&likeInfoAlt;
87605  }else{
87606    pInfo = (struct compareInfo*)&likeInfoNorm;
87607  }
87608  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
87609  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
87610  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
87611      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
87612  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
87613  setLikeOptFlag(db, "like",
87614      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
87615}
87616
87617/*
87618** pExpr points to an expression which implements a function.  If
87619** it is appropriate to apply the LIKE optimization to that function
87620** then set aWc[0] through aWc[2] to the wildcard characters and
87621** return TRUE.  If the function is not a LIKE-style function then
87622** return FALSE.
87623*/
87624SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
87625  FuncDef *pDef;
87626  if( pExpr->op!=TK_FUNCTION
87627   || !pExpr->x.pList
87628   || pExpr->x.pList->nExpr!=2
87629  ){
87630    return 0;
87631  }
87632  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87633  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
87634                             sqlite3Strlen30(pExpr->u.zToken),
87635                             2, SQLITE_UTF8, 0);
87636  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
87637    return 0;
87638  }
87639
87640  /* The memcpy() statement assumes that the wildcard characters are
87641  ** the first three statements in the compareInfo structure.  The
87642  ** asserts() that follow verify that assumption
87643  */
87644  memcpy(aWc, pDef->pUserData, 3);
87645  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
87646  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
87647  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
87648  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
87649  return 1;
87650}
87651
87652/*
87653** All all of the FuncDef structures in the aBuiltinFunc[] array above
87654** to the global function hash table.  This occurs at start-time (as
87655** a consequence of calling sqlite3_initialize()).
87656**
87657** After this routine runs
87658*/
87659SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
87660  /*
87661  ** The following array holds FuncDef structures for all of the functions
87662  ** defined in this file.
87663  **
87664  ** The array cannot be constant since changes are made to the
87665  ** FuncDef.pHash elements at start-time.  The elements of this array
87666  ** are read-only after initialization is complete.
87667  */
87668  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
87669    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
87670    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
87671    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
87672    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
87673    FUNCTION(trim,               1, 3, 0, trimFunc         ),
87674    FUNCTION(trim,               2, 3, 0, trimFunc         ),
87675    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
87676    FUNCTION(min,                0, 0, 1, 0                ),
87677    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
87678    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
87679    FUNCTION(max,                0, 1, 1, 0                ),
87680    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
87681    FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
87682    FUNCTION(length,             1, 0, 0, lengthFunc       ),
87683    FUNCTION(substr,             2, 0, 0, substrFunc       ),
87684    FUNCTION(substr,             3, 0, 0, substrFunc       ),
87685    FUNCTION(abs,                1, 0, 0, absFunc          ),
87686#ifndef SQLITE_OMIT_FLOATING_POINT
87687    FUNCTION(round,              1, 0, 0, roundFunc        ),
87688    FUNCTION(round,              2, 0, 0, roundFunc        ),
87689#endif
87690    FUNCTION(upper,              1, 0, 0, upperFunc        ),
87691    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
87692    FUNCTION(coalesce,           1, 0, 0, 0                ),
87693    FUNCTION(coalesce,           0, 0, 0, 0                ),
87694/*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
87695    {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
87696    FUNCTION(hex,                1, 0, 0, hexFunc          ),
87697/*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
87698    {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
87699    FUNCTION(random,             0, 0, 0, randomFunc       ),
87700    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
87701    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
87702    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
87703    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
87704    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
87705#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87706    FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
87707    FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
87708#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
87709    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
87710    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
87711    FUNCTION(changes,            0, 0, 0, changes          ),
87712    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
87713    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
87714    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
87715  #ifdef SQLITE_SOUNDEX
87716    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
87717  #endif
87718  #ifndef SQLITE_OMIT_LOAD_EXTENSION
87719    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
87720    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
87721  #endif
87722    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
87723    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
87724    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
87725 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
87726    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
87727    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
87728    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
87729    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
87730
87731    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87732  #ifdef SQLITE_CASE_SENSITIVE_LIKE
87733    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87734    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87735  #else
87736    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
87737    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
87738  #endif
87739  };
87740
87741  int i;
87742  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
87743  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
87744
87745  for(i=0; i<ArraySize(aBuiltinFunc); i++){
87746    sqlite3FuncDefInsert(pHash, &aFunc[i]);
87747  }
87748  sqlite3RegisterDateTimeFunctions();
87749#ifndef SQLITE_OMIT_ALTERTABLE
87750  sqlite3AlterFunctions();
87751#endif
87752}
87753
87754/************** End of func.c ************************************************/
87755/************** Begin file fkey.c ********************************************/
87756/*
87757**
87758** The author disclaims copyright to this source code.  In place of
87759** a legal notice, here is a blessing:
87760**
87761**    May you do good and not evil.
87762**    May you find forgiveness for yourself and forgive others.
87763**    May you share freely, never taking more than you give.
87764**
87765*************************************************************************
87766** This file contains code used by the compiler to add foreign key
87767** support to compiled SQL statements.
87768*/
87769
87770#ifndef SQLITE_OMIT_FOREIGN_KEY
87771#ifndef SQLITE_OMIT_TRIGGER
87772
87773/*
87774** Deferred and Immediate FKs
87775** --------------------------
87776**
87777** Foreign keys in SQLite come in two flavours: deferred and immediate.
87778** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
87779** is returned and the current statement transaction rolled back. If a
87780** deferred foreign key constraint is violated, no action is taken
87781** immediately. However if the application attempts to commit the
87782** transaction before fixing the constraint violation, the attempt fails.
87783**
87784** Deferred constraints are implemented using a simple counter associated
87785** with the database handle. The counter is set to zero each time a
87786** database transaction is opened. Each time a statement is executed
87787** that causes a foreign key violation, the counter is incremented. Each
87788** time a statement is executed that removes an existing violation from
87789** the database, the counter is decremented. When the transaction is
87790** committed, the commit fails if the current value of the counter is
87791** greater than zero. This scheme has two big drawbacks:
87792**
87793**   * When a commit fails due to a deferred foreign key constraint,
87794**     there is no way to tell which foreign constraint is not satisfied,
87795**     or which row it is not satisfied for.
87796**
87797**   * If the database contains foreign key violations when the
87798**     transaction is opened, this may cause the mechanism to malfunction.
87799**
87800** Despite these problems, this approach is adopted as it seems simpler
87801** than the alternatives.
87802**
87803** INSERT operations:
87804**
87805**   I.1) For each FK for which the table is the child table, search
87806**        the parent table for a match. If none is found increment the
87807**        constraint counter.
87808**
87809**   I.2) For each FK for which the table is the parent table,
87810**        search the child table for rows that correspond to the new
87811**        row in the parent table. Decrement the counter for each row
87812**        found (as the constraint is now satisfied).
87813**
87814** DELETE operations:
87815**
87816**   D.1) For each FK for which the table is the child table,
87817**        search the parent table for a row that corresponds to the
87818**        deleted row in the child table. If such a row is not found,
87819**        decrement the counter.
87820**
87821**   D.2) For each FK for which the table is the parent table, search
87822**        the child table for rows that correspond to the deleted row
87823**        in the parent table. For each found increment the counter.
87824**
87825** UPDATE operations:
87826**
87827**   An UPDATE command requires that all 4 steps above are taken, but only
87828**   for FK constraints for which the affected columns are actually
87829**   modified (values must be compared at runtime).
87830**
87831** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
87832** This simplifies the implementation a bit.
87833**
87834** For the purposes of immediate FK constraints, the OR REPLACE conflict
87835** resolution is considered to delete rows before the new row is inserted.
87836** If a delete caused by OR REPLACE violates an FK constraint, an exception
87837** is thrown, even if the FK constraint would be satisfied after the new
87838** row is inserted.
87839**
87840** Immediate constraints are usually handled similarly. The only difference
87841** is that the counter used is stored as part of each individual statement
87842** object (struct Vdbe). If, after the statement has run, its immediate
87843** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
87844** and the statement transaction is rolled back. An exception is an INSERT
87845** statement that inserts a single row only (no triggers). In this case,
87846** instead of using a counter, an exception is thrown immediately if the
87847** INSERT violates a foreign key constraint. This is necessary as such
87848** an INSERT does not open a statement transaction.
87849**
87850** TODO: How should dropping a table be handled? How should renaming a
87851** table be handled?
87852**
87853**
87854** Query API Notes
87855** ---------------
87856**
87857** Before coding an UPDATE or DELETE row operation, the code-generator
87858** for those two operations needs to know whether or not the operation
87859** requires any FK processing and, if so, which columns of the original
87860** row are required by the FK processing VDBE code (i.e. if FKs were
87861** implemented using triggers, which of the old.* columns would be
87862** accessed). No information is required by the code-generator before
87863** coding an INSERT operation. The functions used by the UPDATE/DELETE
87864** generation code to query for this information are:
87865**
87866**   sqlite3FkRequired() - Test to see if FK processing is required.
87867**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
87868**
87869**
87870** Externally accessible module functions
87871** --------------------------------------
87872**
87873**   sqlite3FkCheck()    - Check for foreign key violations.
87874**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
87875**   sqlite3FkDelete()   - Delete an FKey structure.
87876*/
87877
87878/*
87879** VDBE Calling Convention
87880** -----------------------
87881**
87882** Example:
87883**
87884**   For the following INSERT statement:
87885**
87886**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
87887**     INSERT INTO t1 VALUES(1, 2, 3.1);
87888**
87889**   Register (x):        2    (type integer)
87890**   Register (x+1):      1    (type integer)
87891**   Register (x+2):      NULL (type NULL)
87892**   Register (x+3):      3.1  (type real)
87893*/
87894
87895/*
87896** A foreign key constraint requires that the key columns in the parent
87897** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
87898** Given that pParent is the parent table for foreign key constraint pFKey,
87899** search the schema a unique index on the parent key columns.
87900**
87901** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
87902** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
87903** is set to point to the unique index.
87904**
87905** If the parent key consists of a single column (the foreign key constraint
87906** is not a composite foreign key), output variable *paiCol is set to NULL.
87907** Otherwise, it is set to point to an allocated array of size N, where
87908** N is the number of columns in the parent key. The first element of the
87909** array is the index of the child table column that is mapped by the FK
87910** constraint to the parent table column stored in the left-most column
87911** of index *ppIdx. The second element of the array is the index of the
87912** child table column that corresponds to the second left-most column of
87913** *ppIdx, and so on.
87914**
87915** If the required index cannot be found, either because:
87916**
87917**   1) The named parent key columns do not exist, or
87918**
87919**   2) The named parent key columns do exist, but are not subject to a
87920**      UNIQUE or PRIMARY KEY constraint, or
87921**
87922**   3) No parent key columns were provided explicitly as part of the
87923**      foreign key definition, and the parent table does not have a
87924**      PRIMARY KEY, or
87925**
87926**   4) No parent key columns were provided explicitly as part of the
87927**      foreign key definition, and the PRIMARY KEY of the parent table
87928**      consists of a a different number of columns to the child key in
87929**      the child table.
87930**
87931** then non-zero is returned, and a "foreign key mismatch" error loaded
87932** into pParse. If an OOM error occurs, non-zero is returned and the
87933** pParse->db->mallocFailed flag is set.
87934*/
87935static int locateFkeyIndex(
87936  Parse *pParse,                  /* Parse context to store any error in */
87937  Table *pParent,                 /* Parent table of FK constraint pFKey */
87938  FKey *pFKey,                    /* Foreign key to find index for */
87939  Index **ppIdx,                  /* OUT: Unique index on parent table */
87940  int **paiCol                    /* OUT: Map of index columns in pFKey */
87941){
87942  Index *pIdx = 0;                    /* Value to return via *ppIdx */
87943  int *aiCol = 0;                     /* Value to return via *paiCol */
87944  int nCol = pFKey->nCol;             /* Number of columns in parent key */
87945  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
87946
87947  /* The caller is responsible for zeroing output parameters. */
87948  assert( ppIdx && *ppIdx==0 );
87949  assert( !paiCol || *paiCol==0 );
87950  assert( pParse );
87951
87952  /* If this is a non-composite (single column) foreign key, check if it
87953  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
87954  ** and *paiCol set to zero and return early.
87955  **
87956  ** Otherwise, for a composite foreign key (more than one column), allocate
87957  ** space for the aiCol array (returned via output parameter *paiCol).
87958  ** Non-composite foreign keys do not require the aiCol array.
87959  */
87960  if( nCol==1 ){
87961    /* The FK maps to the IPK if any of the following are true:
87962    **
87963    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
87964    **      mapped to the primary key of table pParent, or
87965    **   2) The FK is explicitly mapped to a column declared as INTEGER
87966    **      PRIMARY KEY.
87967    */
87968    if( pParent->iPKey>=0 ){
87969      if( !zKey ) return 0;
87970      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
87971    }
87972  }else if( paiCol ){
87973    assert( nCol>1 );
87974    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
87975    if( !aiCol ) return 1;
87976    *paiCol = aiCol;
87977  }
87978
87979  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
87980    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
87981      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
87982      ** of columns. If each indexed column corresponds to a foreign key
87983      ** column of pFKey, then this index is a winner.  */
87984
87985      if( zKey==0 ){
87986        /* If zKey is NULL, then this foreign key is implicitly mapped to
87987        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
87988        ** identified by the test (Index.autoIndex==2).  */
87989        if( pIdx->autoIndex==2 ){
87990          if( aiCol ){
87991            int i;
87992            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
87993          }
87994          break;
87995        }
87996      }else{
87997        /* If zKey is non-NULL, then this foreign key was declared to
87998        ** map to an explicit list of columns in table pParent. Check if this
87999        ** index matches those columns. Also, check that the index uses
88000        ** the default collation sequences for each column. */
88001        int i, j;
88002        for(i=0; i<nCol; i++){
88003          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
88004          char *zDfltColl;                  /* Def. collation for column */
88005          char *zIdxCol;                    /* Name of indexed column */
88006
88007          /* If the index uses a collation sequence that is different from
88008          ** the default collation sequence for the column, this index is
88009          ** unusable. Bail out early in this case.  */
88010          zDfltColl = pParent->aCol[iCol].zColl;
88011          if( !zDfltColl ){
88012            zDfltColl = "BINARY";
88013          }
88014          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
88015
88016          zIdxCol = pParent->aCol[iCol].zName;
88017          for(j=0; j<nCol; j++){
88018            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
88019              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
88020              break;
88021            }
88022          }
88023          if( j==nCol ) break;
88024        }
88025        if( i==nCol ) break;      /* pIdx is usable */
88026      }
88027    }
88028  }
88029
88030  if( !pIdx ){
88031    if( !pParse->disableTriggers ){
88032      sqlite3ErrorMsg(pParse, "foreign key mismatch");
88033    }
88034    sqlite3DbFree(pParse->db, aiCol);
88035    return 1;
88036  }
88037
88038  *ppIdx = pIdx;
88039  return 0;
88040}
88041
88042/*
88043** This function is called when a row is inserted into or deleted from the
88044** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
88045** on the child table of pFKey, this function is invoked twice for each row
88046** affected - once to "delete" the old row, and then again to "insert" the
88047** new row.
88048**
88049** Each time it is called, this function generates VDBE code to locate the
88050** row in the parent table that corresponds to the row being inserted into
88051** or deleted from the child table. If the parent row can be found, no
88052** special action is taken. Otherwise, if the parent row can *not* be
88053** found in the parent table:
88054**
88055**   Operation | FK type   | Action taken
88056**   --------------------------------------------------------------------------
88057**   INSERT      immediate   Increment the "immediate constraint counter".
88058**
88059**   DELETE      immediate   Decrement the "immediate constraint counter".
88060**
88061**   INSERT      deferred    Increment the "deferred constraint counter".
88062**
88063**   DELETE      deferred    Decrement the "deferred constraint counter".
88064**
88065** These operations are identified in the comment at the top of this file
88066** (fkey.c) as "I.1" and "D.1".
88067*/
88068static void fkLookupParent(
88069  Parse *pParse,        /* Parse context */
88070  int iDb,              /* Index of database housing pTab */
88071  Table *pTab,          /* Parent table of FK pFKey */
88072  Index *pIdx,          /* Unique index on parent key columns in pTab */
88073  FKey *pFKey,          /* Foreign key constraint */
88074  int *aiCol,           /* Map from parent key columns to child table columns */
88075  int regData,          /* Address of array containing child table row */
88076  int nIncr,            /* Increment constraint counter by this */
88077  int isIgnore          /* If true, pretend pTab contains all NULL values */
88078){
88079  int i;                                    /* Iterator variable */
88080  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
88081  int iCur = pParse->nTab - 1;              /* Cursor number to use */
88082  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
88083
88084  /* If nIncr is less than zero, then check at runtime if there are any
88085  ** outstanding constraints to resolve. If there are not, there is no need
88086  ** to check if deleting this row resolves any outstanding violations.
88087  **
88088  ** Check if any of the key columns in the child table row are NULL. If
88089  ** any are, then the constraint is considered satisfied. No need to
88090  ** search for a matching row in the parent table.  */
88091  if( nIncr<0 ){
88092    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
88093  }
88094  for(i=0; i<pFKey->nCol; i++){
88095    int iReg = aiCol[i] + regData + 1;
88096    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
88097  }
88098
88099  if( isIgnore==0 ){
88100    if( pIdx==0 ){
88101      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
88102      ** column of the parent table (table pTab).  */
88103      int iMustBeInt;               /* Address of MustBeInt instruction */
88104      int regTemp = sqlite3GetTempReg(pParse);
88105
88106      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
88107      ** apply the affinity of the parent key). If this fails, then there
88108      ** is no matching parent key. Before using MustBeInt, make a copy of
88109      ** the value. Otherwise, the value inserted into the child key column
88110      ** will have INTEGER affinity applied to it, which may not be correct.  */
88111      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
88112      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
88113
88114      /* If the parent table is the same as the child table, and we are about
88115      ** to increment the constraint-counter (i.e. this is an INSERT operation),
88116      ** then check if the row being inserted matches itself. If so, do not
88117      ** increment the constraint-counter.  */
88118      if( pTab==pFKey->pFrom && nIncr==1 ){
88119        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
88120      }
88121
88122      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
88123      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
88124      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
88125      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
88126      sqlite3VdbeJumpHere(v, iMustBeInt);
88127      sqlite3ReleaseTempReg(pParse, regTemp);
88128    }else{
88129      int nCol = pFKey->nCol;
88130      int regTemp = sqlite3GetTempRange(pParse, nCol);
88131      int regRec = sqlite3GetTempReg(pParse);
88132      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
88133
88134      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
88135      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
88136      for(i=0; i<nCol; i++){
88137        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
88138      }
88139
88140      /* If the parent table is the same as the child table, and we are about
88141      ** to increment the constraint-counter (i.e. this is an INSERT operation),
88142      ** then check if the row being inserted matches itself. If so, do not
88143      ** increment the constraint-counter.
88144      **
88145      ** If any of the parent-key values are NULL, then the row cannot match
88146      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
88147      ** of the parent-key values are NULL (at this point it is known that
88148      ** none of the child key values are).
88149      */
88150      if( pTab==pFKey->pFrom && nIncr==1 ){
88151        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
88152        for(i=0; i<nCol; i++){
88153          int iChild = aiCol[i]+1+regData;
88154          int iParent = pIdx->aiColumn[i]+1+regData;
88155          assert( aiCol[i]!=pTab->iPKey );
88156          if( pIdx->aiColumn[i]==pTab->iPKey ){
88157            /* The parent key is a composite key that includes the IPK column */
88158            iParent = regData;
88159          }
88160          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
88161          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
88162        }
88163        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
88164      }
88165
88166      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
88167      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
88168      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
88169
88170      sqlite3ReleaseTempReg(pParse, regRec);
88171      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
88172    }
88173  }
88174
88175  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
88176    /* Special case: If this is an INSERT statement that will insert exactly
88177    ** one row into the table, raise a constraint immediately instead of
88178    ** incrementing a counter. This is necessary as the VM code is being
88179    ** generated for will not open a statement transaction.  */
88180    assert( nIncr==1 );
88181    sqlite3HaltConstraint(
88182        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
88183    );
88184  }else{
88185    if( nIncr>0 && pFKey->isDeferred==0 ){
88186      sqlite3ParseToplevel(pParse)->mayAbort = 1;
88187    }
88188    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
88189  }
88190
88191  sqlite3VdbeResolveLabel(v, iOk);
88192  sqlite3VdbeAddOp1(v, OP_Close, iCur);
88193}
88194
88195/*
88196** This function is called to generate code executed when a row is deleted
88197** from the parent table of foreign key constraint pFKey and, if pFKey is
88198** deferred, when a row is inserted into the same table. When generating
88199** code for an SQL UPDATE operation, this function may be called twice -
88200** once to "delete" the old row and once to "insert" the new row.
88201**
88202** The code generated by this function scans through the rows in the child
88203** table that correspond to the parent table row being deleted or inserted.
88204** For each child row found, one of the following actions is taken:
88205**
88206**   Operation | FK type   | Action taken
88207**   --------------------------------------------------------------------------
88208**   DELETE      immediate   Increment the "immediate constraint counter".
88209**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
88210**                           throw a "foreign key constraint failed" exception.
88211**
88212**   INSERT      immediate   Decrement the "immediate constraint counter".
88213**
88214**   DELETE      deferred    Increment the "deferred constraint counter".
88215**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
88216**                           throw a "foreign key constraint failed" exception.
88217**
88218**   INSERT      deferred    Decrement the "deferred constraint counter".
88219**
88220** These operations are identified in the comment at the top of this file
88221** (fkey.c) as "I.2" and "D.2".
88222*/
88223static void fkScanChildren(
88224  Parse *pParse,                  /* Parse context */
88225  SrcList *pSrc,                  /* SrcList containing the table to scan */
88226  Table *pTab,
88227  Index *pIdx,                    /* Foreign key index */
88228  FKey *pFKey,                    /* Foreign key relationship */
88229  int *aiCol,                     /* Map from pIdx cols to child table cols */
88230  int regData,                    /* Referenced table data starts here */
88231  int nIncr                       /* Amount to increment deferred counter by */
88232){
88233  sqlite3 *db = pParse->db;       /* Database handle */
88234  int i;                          /* Iterator variable */
88235  Expr *pWhere = 0;               /* WHERE clause to scan with */
88236  NameContext sNameContext;       /* Context used to resolve WHERE clause */
88237  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
88238  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
88239  Vdbe *v = sqlite3GetVdbe(pParse);
88240
88241  assert( !pIdx || pIdx->pTable==pTab );
88242
88243  if( nIncr<0 ){
88244    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
88245  }
88246
88247  /* Create an Expr object representing an SQL expression like:
88248  **
88249  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
88250  **
88251  ** The collation sequence used for the comparison should be that of
88252  ** the parent key columns. The affinity of the parent key column should
88253  ** be applied to each child key value before the comparison takes place.
88254  */
88255  for(i=0; i<pFKey->nCol; i++){
88256    Expr *pLeft;                  /* Value from parent table row */
88257    Expr *pRight;                 /* Column ref to child table */
88258    Expr *pEq;                    /* Expression (pLeft = pRight) */
88259    int iCol;                     /* Index of column in child table */
88260    const char *zCol;             /* Name of column in child table */
88261
88262    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
88263    if( pLeft ){
88264      /* Set the collation sequence and affinity of the LHS of each TK_EQ
88265      ** expression to the parent key column defaults.  */
88266      if( pIdx ){
88267        Column *pCol;
88268        iCol = pIdx->aiColumn[i];
88269        pCol = &pTab->aCol[iCol];
88270        if( pTab->iPKey==iCol ) iCol = -1;
88271        pLeft->iTable = regData+iCol+1;
88272        pLeft->affinity = pCol->affinity;
88273        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
88274      }else{
88275        pLeft->iTable = regData;
88276        pLeft->affinity = SQLITE_AFF_INTEGER;
88277      }
88278    }
88279    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
88280    assert( iCol>=0 );
88281    zCol = pFKey->pFrom->aCol[iCol].zName;
88282    pRight = sqlite3Expr(db, TK_ID, zCol);
88283    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
88284    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88285  }
88286
88287  /* If the child table is the same as the parent table, and this scan
88288  ** is taking place as part of a DELETE operation (operation D.2), omit the
88289  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
88290  ** clause, where $rowid is the rowid of the row being deleted.  */
88291  if( pTab==pFKey->pFrom && nIncr>0 ){
88292    Expr *pEq;                    /* Expression (pLeft = pRight) */
88293    Expr *pLeft;                  /* Value from parent table row */
88294    Expr *pRight;                 /* Column ref to child table */
88295    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
88296    pRight = sqlite3Expr(db, TK_COLUMN, 0);
88297    if( pLeft && pRight ){
88298      pLeft->iTable = regData;
88299      pLeft->affinity = SQLITE_AFF_INTEGER;
88300      pRight->iTable = pSrc->a[0].iCursor;
88301      pRight->iColumn = -1;
88302    }
88303    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
88304    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88305  }
88306
88307  /* Resolve the references in the WHERE clause. */
88308  memset(&sNameContext, 0, sizeof(NameContext));
88309  sNameContext.pSrcList = pSrc;
88310  sNameContext.pParse = pParse;
88311  sqlite3ResolveExprNames(&sNameContext, pWhere);
88312
88313  /* Create VDBE to loop through the entries in pSrc that match the WHERE
88314  ** clause. If the constraint is not deferred, throw an exception for
88315  ** each row found. Otherwise, for deferred constraints, increment the
88316  ** deferred constraint counter by nIncr for each row selected.  */
88317  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0);
88318  if( nIncr>0 && pFKey->isDeferred==0 ){
88319    sqlite3ParseToplevel(pParse)->mayAbort = 1;
88320  }
88321  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
88322  if( pWInfo ){
88323    sqlite3WhereEnd(pWInfo);
88324  }
88325
88326  /* Clean up the WHERE clause constructed above. */
88327  sqlite3ExprDelete(db, pWhere);
88328  if( iFkIfZero ){
88329    sqlite3VdbeJumpHere(v, iFkIfZero);
88330  }
88331}
88332
88333/*
88334** This function returns a pointer to the head of a linked list of FK
88335** constraints for which table pTab is the parent table. For example,
88336** given the following schema:
88337**
88338**   CREATE TABLE t1(a PRIMARY KEY);
88339**   CREATE TABLE t2(b REFERENCES t1(a);
88340**
88341** Calling this function with table "t1" as an argument returns a pointer
88342** to the FKey structure representing the foreign key constraint on table
88343** "t2". Calling this function with "t2" as the argument would return a
88344** NULL pointer (as there are no FK constraints for which t2 is the parent
88345** table).
88346*/
88347SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
88348  int nName = sqlite3Strlen30(pTab->zName);
88349  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
88350}
88351
88352/*
88353** The second argument is a Trigger structure allocated by the
88354** fkActionTrigger() routine. This function deletes the Trigger structure
88355** and all of its sub-components.
88356**
88357** The Trigger structure or any of its sub-components may be allocated from
88358** the lookaside buffer belonging to database handle dbMem.
88359*/
88360static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
88361  if( p ){
88362    TriggerStep *pStep = p->step_list;
88363    sqlite3ExprDelete(dbMem, pStep->pWhere);
88364    sqlite3ExprListDelete(dbMem, pStep->pExprList);
88365    sqlite3SelectDelete(dbMem, pStep->pSelect);
88366    sqlite3ExprDelete(dbMem, p->pWhen);
88367    sqlite3DbFree(dbMem, p);
88368  }
88369}
88370
88371/*
88372** This function is called to generate code that runs when table pTab is
88373** being dropped from the database. The SrcList passed as the second argument
88374** to this function contains a single entry guaranteed to resolve to
88375** table pTab.
88376**
88377** Normally, no code is required. However, if either
88378**
88379**   (a) The table is the parent table of a FK constraint, or
88380**   (b) The table is the child table of a deferred FK constraint and it is
88381**       determined at runtime that there are outstanding deferred FK
88382**       constraint violations in the database,
88383**
88384** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
88385** the table from the database. Triggers are disabled while running this
88386** DELETE, but foreign key actions are not.
88387*/
88388SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
88389  sqlite3 *db = pParse->db;
88390  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
88391    int iSkip = 0;
88392    Vdbe *v = sqlite3GetVdbe(pParse);
88393
88394    assert( v );                  /* VDBE has already been allocated */
88395    if( sqlite3FkReferences(pTab)==0 ){
88396      /* Search for a deferred foreign key constraint for which this table
88397      ** is the child table. If one cannot be found, return without
88398      ** generating any VDBE code. If one can be found, then jump over
88399      ** the entire DELETE if there are no outstanding deferred constraints
88400      ** when this statement is run.  */
88401      FKey *p;
88402      for(p=pTab->pFKey; p; p=p->pNextFrom){
88403        if( p->isDeferred ) break;
88404      }
88405      if( !p ) return;
88406      iSkip = sqlite3VdbeMakeLabel(v);
88407      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
88408    }
88409
88410    pParse->disableTriggers = 1;
88411    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
88412    pParse->disableTriggers = 0;
88413
88414    /* If the DELETE has generated immediate foreign key constraint
88415    ** violations, halt the VDBE and return an error at this point, before
88416    ** any modifications to the schema are made. This is because statement
88417    ** transactions are not able to rollback schema changes.  */
88418    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
88419    sqlite3HaltConstraint(
88420        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
88421    );
88422
88423    if( iSkip ){
88424      sqlite3VdbeResolveLabel(v, iSkip);
88425    }
88426  }
88427}
88428
88429/*
88430** This function is called when inserting, deleting or updating a row of
88431** table pTab to generate VDBE code to perform foreign key constraint
88432** processing for the operation.
88433**
88434** For a DELETE operation, parameter regOld is passed the index of the
88435** first register in an array of (pTab->nCol+1) registers containing the
88436** rowid of the row being deleted, followed by each of the column values
88437** of the row being deleted, from left to right. Parameter regNew is passed
88438** zero in this case.
88439**
88440** For an INSERT operation, regOld is passed zero and regNew is passed the
88441** first register of an array of (pTab->nCol+1) registers containing the new
88442** row data.
88443**
88444** For an UPDATE operation, this function is called twice. Once before
88445** the original record is deleted from the table using the calling convention
88446** described for DELETE. Then again after the original record is deleted
88447** but before the new record is inserted using the INSERT convention.
88448*/
88449SQLITE_PRIVATE void sqlite3FkCheck(
88450  Parse *pParse,                  /* Parse context */
88451  Table *pTab,                    /* Row is being deleted from this table */
88452  int regOld,                     /* Previous row data is stored here */
88453  int regNew                      /* New row data is stored here */
88454){
88455  sqlite3 *db = pParse->db;       /* Database handle */
88456  FKey *pFKey;                    /* Used to iterate through FKs */
88457  int iDb;                        /* Index of database containing pTab */
88458  const char *zDb;                /* Name of database containing pTab */
88459  int isIgnoreErrors = pParse->disableTriggers;
88460
88461  /* Exactly one of regOld and regNew should be non-zero. */
88462  assert( (regOld==0)!=(regNew==0) );
88463
88464  /* If foreign-keys are disabled, this function is a no-op. */
88465  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
88466
88467  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
88468  zDb = db->aDb[iDb].zName;
88469
88470  /* Loop through all the foreign key constraints for which pTab is the
88471  ** child table (the table that the foreign key definition is part of).  */
88472  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
88473    Table *pTo;                   /* Parent table of foreign key pFKey */
88474    Index *pIdx = 0;              /* Index on key columns in pTo */
88475    int *aiFree = 0;
88476    int *aiCol;
88477    int iCol;
88478    int i;
88479    int isIgnore = 0;
88480
88481    /* Find the parent table of this foreign key. Also find a unique index
88482    ** on the parent key columns in the parent table. If either of these
88483    ** schema items cannot be located, set an error in pParse and return
88484    ** early.  */
88485    if( pParse->disableTriggers ){
88486      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
88487    }else{
88488      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
88489    }
88490    if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
88491      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
88492      if( !isIgnoreErrors || db->mallocFailed ) return;
88493      if( pTo==0 ){
88494        /* If isIgnoreErrors is true, then a table is being dropped. In this
88495        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
88496        ** before actually dropping it in order to check FK constraints.
88497        ** If the parent table of an FK constraint on the current table is
88498        ** missing, behave as if it is empty. i.e. decrement the relevant
88499        ** FK counter for each row of the current table with non-NULL keys.
88500        */
88501        Vdbe *v = sqlite3GetVdbe(pParse);
88502        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
88503        for(i=0; i<pFKey->nCol; i++){
88504          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
88505          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
88506        }
88507        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
88508      }
88509      continue;
88510    }
88511    assert( pFKey->nCol==1 || (aiFree && pIdx) );
88512
88513    if( aiFree ){
88514      aiCol = aiFree;
88515    }else{
88516      iCol = pFKey->aCol[0].iFrom;
88517      aiCol = &iCol;
88518    }
88519    for(i=0; i<pFKey->nCol; i++){
88520      if( aiCol[i]==pTab->iPKey ){
88521        aiCol[i] = -1;
88522      }
88523#ifndef SQLITE_OMIT_AUTHORIZATION
88524      /* Request permission to read the parent key columns. If the
88525      ** authorization callback returns SQLITE_IGNORE, behave as if any
88526      ** values read from the parent table are NULL. */
88527      if( db->xAuth ){
88528        int rcauth;
88529        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
88530        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
88531        isIgnore = (rcauth==SQLITE_IGNORE);
88532      }
88533#endif
88534    }
88535
88536    /* Take a shared-cache advisory read-lock on the parent table. Allocate
88537    ** a cursor to use to search the unique index on the parent key columns
88538    ** in the parent table.  */
88539    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
88540    pParse->nTab++;
88541
88542    if( regOld!=0 ){
88543      /* A row is being removed from the child table. Search for the parent.
88544      ** If the parent does not exist, removing the child row resolves an
88545      ** outstanding foreign key constraint violation. */
88546      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
88547    }
88548    if( regNew!=0 ){
88549      /* A row is being added to the child table. If a parent row cannot
88550      ** be found, adding the child row has violated the FK constraint. */
88551      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
88552    }
88553
88554    sqlite3DbFree(db, aiFree);
88555  }
88556
88557  /* Loop through all the foreign key constraints that refer to this table */
88558  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88559    Index *pIdx = 0;              /* Foreign key index for pFKey */
88560    SrcList *pSrc;
88561    int *aiCol = 0;
88562
88563    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
88564      assert( regOld==0 && regNew!=0 );
88565      /* Inserting a single row into a parent table cannot cause an immediate
88566      ** foreign key violation. So do nothing in this case.  */
88567      continue;
88568    }
88569
88570    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
88571      if( !isIgnoreErrors || db->mallocFailed ) return;
88572      continue;
88573    }
88574    assert( aiCol || pFKey->nCol==1 );
88575
88576    /* Create a SrcList structure containing a single table (the table
88577    ** the foreign key that refers to this table is attached to). This
88578    ** is required for the sqlite3WhereXXX() interface.  */
88579    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
88580    if( pSrc ){
88581      struct SrcList_item *pItem = pSrc->a;
88582      pItem->pTab = pFKey->pFrom;
88583      pItem->zName = pFKey->pFrom->zName;
88584      pItem->pTab->nRef++;
88585      pItem->iCursor = pParse->nTab++;
88586
88587      if( regNew!=0 ){
88588        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
88589      }
88590      if( regOld!=0 ){
88591        /* If there is a RESTRICT action configured for the current operation
88592        ** on the parent table of this FK, then throw an exception
88593        ** immediately if the FK constraint is violated, even if this is a
88594        ** deferred trigger. That's what RESTRICT means. To defer checking
88595        ** the constraint, the FK should specify NO ACTION (represented
88596        ** using OE_None). NO ACTION is the default.  */
88597        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
88598      }
88599      pItem->zName = 0;
88600      sqlite3SrcListDelete(db, pSrc);
88601    }
88602    sqlite3DbFree(db, aiCol);
88603  }
88604}
88605
88606#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
88607
88608/*
88609** This function is called before generating code to update or delete a
88610** row contained in table pTab.
88611*/
88612SQLITE_PRIVATE u32 sqlite3FkOldmask(
88613  Parse *pParse,                  /* Parse context */
88614  Table *pTab                     /* Table being modified */
88615){
88616  u32 mask = 0;
88617  if( pParse->db->flags&SQLITE_ForeignKeys ){
88618    FKey *p;
88619    int i;
88620    for(p=pTab->pFKey; p; p=p->pNextFrom){
88621      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
88622    }
88623    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
88624      Index *pIdx = 0;
88625      locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
88626      if( pIdx ){
88627        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
88628      }
88629    }
88630  }
88631  return mask;
88632}
88633
88634/*
88635** This function is called before generating code to update or delete a
88636** row contained in table pTab. If the operation is a DELETE, then
88637** parameter aChange is passed a NULL value. For an UPDATE, aChange points
88638** to an array of size N, where N is the number of columns in table pTab.
88639** If the i'th column is not modified by the UPDATE, then the corresponding
88640** entry in the aChange[] array is set to -1. If the column is modified,
88641** the value is 0 or greater. Parameter chngRowid is set to true if the
88642** UPDATE statement modifies the rowid fields of the table.
88643**
88644** If any foreign key processing will be required, this function returns
88645** true. If there is no foreign key related processing, this function
88646** returns false.
88647*/
88648SQLITE_PRIVATE int sqlite3FkRequired(
88649  Parse *pParse,                  /* Parse context */
88650  Table *pTab,                    /* Table being modified */
88651  int *aChange,                   /* Non-NULL for UPDATE operations */
88652  int chngRowid                   /* True for UPDATE that affects rowid */
88653){
88654  if( pParse->db->flags&SQLITE_ForeignKeys ){
88655    if( !aChange ){
88656      /* A DELETE operation. Foreign key processing is required if the
88657      ** table in question is either the child or parent table for any
88658      ** foreign key constraint.  */
88659      return (sqlite3FkReferences(pTab) || pTab->pFKey);
88660    }else{
88661      /* This is an UPDATE. Foreign key processing is only required if the
88662      ** operation modifies one or more child or parent key columns. */
88663      int i;
88664      FKey *p;
88665
88666      /* Check if any child key columns are being modified. */
88667      for(p=pTab->pFKey; p; p=p->pNextFrom){
88668        for(i=0; i<p->nCol; i++){
88669          int iChildKey = p->aCol[i].iFrom;
88670          if( aChange[iChildKey]>=0 ) return 1;
88671          if( iChildKey==pTab->iPKey && chngRowid ) return 1;
88672        }
88673      }
88674
88675      /* Check if any parent key columns are being modified. */
88676      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
88677        for(i=0; i<p->nCol; i++){
88678          char *zKey = p->aCol[i].zCol;
88679          int iKey;
88680          for(iKey=0; iKey<pTab->nCol; iKey++){
88681            Column *pCol = &pTab->aCol[iKey];
88682            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
88683              if( aChange[iKey]>=0 ) return 1;
88684              if( iKey==pTab->iPKey && chngRowid ) return 1;
88685            }
88686          }
88687        }
88688      }
88689    }
88690  }
88691  return 0;
88692}
88693
88694/*
88695** This function is called when an UPDATE or DELETE operation is being
88696** compiled on table pTab, which is the parent table of foreign-key pFKey.
88697** If the current operation is an UPDATE, then the pChanges parameter is
88698** passed a pointer to the list of columns being modified. If it is a
88699** DELETE, pChanges is passed a NULL pointer.
88700**
88701** It returns a pointer to a Trigger structure containing a trigger
88702** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
88703** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
88704** returned (these actions require no special handling by the triggers
88705** sub-system, code for them is created by fkScanChildren()).
88706**
88707** For example, if pFKey is the foreign key and pTab is table "p" in
88708** the following schema:
88709**
88710**   CREATE TABLE p(pk PRIMARY KEY);
88711**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
88712**
88713** then the returned trigger structure is equivalent to:
88714**
88715**   CREATE TRIGGER ... DELETE ON p BEGIN
88716**     DELETE FROM c WHERE ck = old.pk;
88717**   END;
88718**
88719** The returned pointer is cached as part of the foreign key object. It
88720** is eventually freed along with the rest of the foreign key object by
88721** sqlite3FkDelete().
88722*/
88723static Trigger *fkActionTrigger(
88724  Parse *pParse,                  /* Parse context */
88725  Table *pTab,                    /* Table being updated or deleted from */
88726  FKey *pFKey,                    /* Foreign key to get action for */
88727  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
88728){
88729  sqlite3 *db = pParse->db;       /* Database handle */
88730  int action;                     /* One of OE_None, OE_Cascade etc. */
88731  Trigger *pTrigger;              /* Trigger definition to return */
88732  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
88733
88734  action = pFKey->aAction[iAction];
88735  pTrigger = pFKey->apTrigger[iAction];
88736
88737  if( action!=OE_None && !pTrigger ){
88738    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
88739    char const *zFrom;            /* Name of child table */
88740    int nFrom;                    /* Length in bytes of zFrom */
88741    Index *pIdx = 0;              /* Parent key index for this FK */
88742    int *aiCol = 0;               /* child table cols -> parent key cols */
88743    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
88744    Expr *pWhere = 0;             /* WHERE clause of trigger step */
88745    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
88746    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
88747    int i;                        /* Iterator variable */
88748    Expr *pWhen = 0;              /* WHEN clause for the trigger */
88749
88750    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
88751    assert( aiCol || pFKey->nCol==1 );
88752
88753    for(i=0; i<pFKey->nCol; i++){
88754      Token tOld = { "old", 3 };  /* Literal "old" token */
88755      Token tNew = { "new", 3 };  /* Literal "new" token */
88756      Token tFromCol;             /* Name of column in child table */
88757      Token tToCol;               /* Name of column in parent table */
88758      int iFromCol;               /* Idx of column in child table */
88759      Expr *pEq;                  /* tFromCol = OLD.tToCol */
88760
88761      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
88762      assert( iFromCol>=0 );
88763      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
88764      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
88765
88766      tToCol.n = sqlite3Strlen30(tToCol.z);
88767      tFromCol.n = sqlite3Strlen30(tFromCol.z);
88768
88769      /* Create the expression "OLD.zToCol = zFromCol". It is important
88770      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
88771      ** that the affinity and collation sequence associated with the
88772      ** parent table are used for the comparison. */
88773      pEq = sqlite3PExpr(pParse, TK_EQ,
88774          sqlite3PExpr(pParse, TK_DOT,
88775            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
88776            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88777          , 0),
88778          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
88779      , 0);
88780      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88781
88782      /* For ON UPDATE, construct the next term of the WHEN clause.
88783      ** The final WHEN clause will be like this:
88784      **
88785      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
88786      */
88787      if( pChanges ){
88788        pEq = sqlite3PExpr(pParse, TK_IS,
88789            sqlite3PExpr(pParse, TK_DOT,
88790              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
88791              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88792              0),
88793            sqlite3PExpr(pParse, TK_DOT,
88794              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
88795              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88796              0),
88797            0);
88798        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
88799      }
88800
88801      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
88802        Expr *pNew;
88803        if( action==OE_Cascade ){
88804          pNew = sqlite3PExpr(pParse, TK_DOT,
88805            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
88806            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88807          , 0);
88808        }else if( action==OE_SetDflt ){
88809          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
88810          if( pDflt ){
88811            pNew = sqlite3ExprDup(db, pDflt, 0);
88812          }else{
88813            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
88814          }
88815        }else{
88816          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
88817        }
88818        pList = sqlite3ExprListAppend(pParse, pList, pNew);
88819        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
88820      }
88821    }
88822    sqlite3DbFree(db, aiCol);
88823
88824    zFrom = pFKey->pFrom->zName;
88825    nFrom = sqlite3Strlen30(zFrom);
88826
88827    if( action==OE_Restrict ){
88828      Token tFrom;
88829      Expr *pRaise;
88830
88831      tFrom.z = zFrom;
88832      tFrom.n = nFrom;
88833      pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
88834      if( pRaise ){
88835        pRaise->affinity = OE_Abort;
88836      }
88837      pSelect = sqlite3SelectNew(pParse,
88838          sqlite3ExprListAppend(pParse, 0, pRaise),
88839          sqlite3SrcListAppend(db, 0, &tFrom, 0),
88840          pWhere,
88841          0, 0, 0, 0, 0, 0
88842      );
88843      pWhere = 0;
88844    }
88845
88846    /* Disable lookaside memory allocation */
88847    enableLookaside = db->lookaside.bEnabled;
88848    db->lookaside.bEnabled = 0;
88849
88850    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
88851        sizeof(Trigger) +         /* struct Trigger */
88852        sizeof(TriggerStep) +     /* Single step in trigger program */
88853        nFrom + 1                 /* Space for pStep->target.z */
88854    );
88855    if( pTrigger ){
88856      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
88857      pStep->target.z = (char *)&pStep[1];
88858      pStep->target.n = nFrom;
88859      memcpy((char *)pStep->target.z, zFrom, nFrom);
88860
88861      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
88862      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
88863      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
88864      if( pWhen ){
88865        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
88866        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
88867      }
88868    }
88869
88870    /* Re-enable the lookaside buffer, if it was disabled earlier. */
88871    db->lookaside.bEnabled = enableLookaside;
88872
88873    sqlite3ExprDelete(db, pWhere);
88874    sqlite3ExprDelete(db, pWhen);
88875    sqlite3ExprListDelete(db, pList);
88876    sqlite3SelectDelete(db, pSelect);
88877    if( db->mallocFailed==1 ){
88878      fkTriggerDelete(db, pTrigger);
88879      return 0;
88880    }
88881    assert( pStep!=0 );
88882
88883    switch( action ){
88884      case OE_Restrict:
88885        pStep->op = TK_SELECT;
88886        break;
88887      case OE_Cascade:
88888        if( !pChanges ){
88889          pStep->op = TK_DELETE;
88890          break;
88891        }
88892      default:
88893        pStep->op = TK_UPDATE;
88894    }
88895    pStep->pTrig = pTrigger;
88896    pTrigger->pSchema = pTab->pSchema;
88897    pTrigger->pTabSchema = pTab->pSchema;
88898    pFKey->apTrigger[iAction] = pTrigger;
88899    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
88900  }
88901
88902  return pTrigger;
88903}
88904
88905/*
88906** This function is called when deleting or updating a row to implement
88907** any required CASCADE, SET NULL or SET DEFAULT actions.
88908*/
88909SQLITE_PRIVATE void sqlite3FkActions(
88910  Parse *pParse,                  /* Parse context */
88911  Table *pTab,                    /* Table being updated or deleted from */
88912  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
88913  int regOld                      /* Address of array containing old row */
88914){
88915  /* If foreign-key support is enabled, iterate through all FKs that
88916  ** refer to table pTab. If there is an action associated with the FK
88917  ** for this operation (either update or delete), invoke the associated
88918  ** trigger sub-program.  */
88919  if( pParse->db->flags&SQLITE_ForeignKeys ){
88920    FKey *pFKey;                  /* Iterator variable */
88921    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88922      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
88923      if( pAction ){
88924        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
88925      }
88926    }
88927  }
88928}
88929
88930#endif /* ifndef SQLITE_OMIT_TRIGGER */
88931
88932/*
88933** Free all memory associated with foreign key definitions attached to
88934** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
88935** hash table.
88936*/
88937SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
88938  FKey *pFKey;                    /* Iterator variable */
88939  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
88940
88941  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
88942  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
88943
88944    /* Remove the FK from the fkeyHash hash table. */
88945    if( !db || db->pnBytesFreed==0 ){
88946      if( pFKey->pPrevTo ){
88947        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
88948      }else{
88949        void *p = (void *)pFKey->pNextTo;
88950        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
88951        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
88952      }
88953      if( pFKey->pNextTo ){
88954        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
88955      }
88956    }
88957
88958    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
88959    ** classified as either immediate or deferred.
88960    */
88961    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
88962
88963    /* Delete any triggers created to implement actions for this FK. */
88964#ifndef SQLITE_OMIT_TRIGGER
88965    fkTriggerDelete(db, pFKey->apTrigger[0]);
88966    fkTriggerDelete(db, pFKey->apTrigger[1]);
88967#endif
88968
88969    pNext = pFKey->pNextFrom;
88970    sqlite3DbFree(db, pFKey);
88971  }
88972}
88973#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
88974
88975/************** End of fkey.c ************************************************/
88976/************** Begin file insert.c ******************************************/
88977/*
88978** 2001 September 15
88979**
88980** The author disclaims copyright to this source code.  In place of
88981** a legal notice, here is a blessing:
88982**
88983**    May you do good and not evil.
88984**    May you find forgiveness for yourself and forgive others.
88985**    May you share freely, never taking more than you give.
88986**
88987*************************************************************************
88988** This file contains C code routines that are called by the parser
88989** to handle INSERT statements in SQLite.
88990*/
88991
88992/*
88993** Generate code that will open a table for reading.
88994*/
88995SQLITE_PRIVATE void sqlite3OpenTable(
88996  Parse *p,       /* Generate code into this VDBE */
88997  int iCur,       /* The cursor number of the table */
88998  int iDb,        /* The database index in sqlite3.aDb[] */
88999  Table *pTab,    /* The table to be opened */
89000  int opcode      /* OP_OpenRead or OP_OpenWrite */
89001){
89002  Vdbe *v;
89003  if( IsVirtual(pTab) ) return;
89004  v = sqlite3GetVdbe(p);
89005  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
89006  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
89007  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
89008  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
89009  VdbeComment((v, "%s", pTab->zName));
89010}
89011
89012/*
89013** Return a pointer to the column affinity string associated with index
89014** pIdx. A column affinity string has one character for each column in
89015** the table, according to the affinity of the column:
89016**
89017**  Character      Column affinity
89018**  ------------------------------
89019**  'a'            TEXT
89020**  'b'            NONE
89021**  'c'            NUMERIC
89022**  'd'            INTEGER
89023**  'e'            REAL
89024**
89025** An extra 'd' is appended to the end of the string to cover the
89026** rowid that appears as the last column in every index.
89027**
89028** Memory for the buffer containing the column index affinity string
89029** is managed along with the rest of the Index structure. It will be
89030** released when sqlite3DeleteIndex() is called.
89031*/
89032SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
89033  if( !pIdx->zColAff ){
89034    /* The first time a column affinity string for a particular index is
89035    ** required, it is allocated and populated here. It is then stored as
89036    ** a member of the Index structure for subsequent use.
89037    **
89038    ** The column affinity string will eventually be deleted by
89039    ** sqliteDeleteIndex() when the Index structure itself is cleaned
89040    ** up.
89041    */
89042    int n;
89043    Table *pTab = pIdx->pTable;
89044    sqlite3 *db = sqlite3VdbeDb(v);
89045    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
89046    if( !pIdx->zColAff ){
89047      db->mallocFailed = 1;
89048      return 0;
89049    }
89050    for(n=0; n<pIdx->nColumn; n++){
89051      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
89052    }
89053    pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
89054    pIdx->zColAff[n] = 0;
89055  }
89056
89057  return pIdx->zColAff;
89058}
89059
89060/*
89061** Set P4 of the most recently inserted opcode to a column affinity
89062** string for table pTab. A column affinity string has one character
89063** for each column indexed by the index, according to the affinity of the
89064** column:
89065**
89066**  Character      Column affinity
89067**  ------------------------------
89068**  'a'            TEXT
89069**  'b'            NONE
89070**  'c'            NUMERIC
89071**  'd'            INTEGER
89072**  'e'            REAL
89073*/
89074SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
89075  /* The first time a column affinity string for a particular table
89076  ** is required, it is allocated and populated here. It is then
89077  ** stored as a member of the Table structure for subsequent use.
89078  **
89079  ** The column affinity string will eventually be deleted by
89080  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
89081  */
89082  if( !pTab->zColAff ){
89083    char *zColAff;
89084    int i;
89085    sqlite3 *db = sqlite3VdbeDb(v);
89086
89087    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
89088    if( !zColAff ){
89089      db->mallocFailed = 1;
89090      return;
89091    }
89092
89093    for(i=0; i<pTab->nCol; i++){
89094      zColAff[i] = pTab->aCol[i].affinity;
89095    }
89096    zColAff[pTab->nCol] = '\0';
89097
89098    pTab->zColAff = zColAff;
89099  }
89100
89101  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
89102}
89103
89104/*
89105** Return non-zero if the table pTab in database iDb or any of its indices
89106** have been opened at any point in the VDBE program beginning at location
89107** iStartAddr throught the end of the program.  This is used to see if
89108** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
89109** run without using temporary table for the results of the SELECT.
89110*/
89111static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
89112  Vdbe *v = sqlite3GetVdbe(p);
89113  int i;
89114  int iEnd = sqlite3VdbeCurrentAddr(v);
89115#ifndef SQLITE_OMIT_VIRTUALTABLE
89116  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
89117#endif
89118
89119  for(i=iStartAddr; i<iEnd; i++){
89120    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
89121    assert( pOp!=0 );
89122    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
89123      Index *pIndex;
89124      int tnum = pOp->p2;
89125      if( tnum==pTab->tnum ){
89126        return 1;
89127      }
89128      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
89129        if( tnum==pIndex->tnum ){
89130          return 1;
89131        }
89132      }
89133    }
89134#ifndef SQLITE_OMIT_VIRTUALTABLE
89135    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
89136      assert( pOp->p4.pVtab!=0 );
89137      assert( pOp->p4type==P4_VTAB );
89138      return 1;
89139    }
89140#endif
89141  }
89142  return 0;
89143}
89144
89145#ifndef SQLITE_OMIT_AUTOINCREMENT
89146/*
89147** Locate or create an AutoincInfo structure associated with table pTab
89148** which is in database iDb.  Return the register number for the register
89149** that holds the maximum rowid.
89150**
89151** There is at most one AutoincInfo structure per table even if the
89152** same table is autoincremented multiple times due to inserts within
89153** triggers.  A new AutoincInfo structure is created if this is the
89154** first use of table pTab.  On 2nd and subsequent uses, the original
89155** AutoincInfo structure is used.
89156**
89157** Three memory locations are allocated:
89158**
89159**   (1)  Register to hold the name of the pTab table.
89160**   (2)  Register to hold the maximum ROWID of pTab.
89161**   (3)  Register to hold the rowid in sqlite_sequence of pTab
89162**
89163** The 2nd register is the one that is returned.  That is all the
89164** insert routine needs to know about.
89165*/
89166static int autoIncBegin(
89167  Parse *pParse,      /* Parsing context */
89168  int iDb,            /* Index of the database holding pTab */
89169  Table *pTab         /* The table we are writing to */
89170){
89171  int memId = 0;      /* Register holding maximum rowid */
89172  if( pTab->tabFlags & TF_Autoincrement ){
89173    Parse *pToplevel = sqlite3ParseToplevel(pParse);
89174    AutoincInfo *pInfo;
89175
89176    pInfo = pToplevel->pAinc;
89177    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
89178    if( pInfo==0 ){
89179      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
89180      if( pInfo==0 ) return 0;
89181      pInfo->pNext = pToplevel->pAinc;
89182      pToplevel->pAinc = pInfo;
89183      pInfo->pTab = pTab;
89184      pInfo->iDb = iDb;
89185      pToplevel->nMem++;                  /* Register to hold name of table */
89186      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
89187      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
89188    }
89189    memId = pInfo->regCtr;
89190  }
89191  return memId;
89192}
89193
89194/*
89195** This routine generates code that will initialize all of the
89196** register used by the autoincrement tracker.
89197*/
89198SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
89199  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
89200  sqlite3 *db = pParse->db;  /* The database connection */
89201  Db *pDb;                   /* Database only autoinc table */
89202  int memId;                 /* Register holding max rowid */
89203  int addr;                  /* A VDBE address */
89204  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
89205
89206  /* This routine is never called during trigger-generation.  It is
89207  ** only called from the top-level */
89208  assert( pParse->pTriggerTab==0 );
89209  assert( pParse==sqlite3ParseToplevel(pParse) );
89210
89211  assert( v );   /* We failed long ago if this is not so */
89212  for(p = pParse->pAinc; p; p = p->pNext){
89213    pDb = &db->aDb[p->iDb];
89214    memId = p->regCtr;
89215    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
89216    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
89217    sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
89218    addr = sqlite3VdbeCurrentAddr(v);
89219    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
89220    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
89221    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
89222    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
89223    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
89224    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
89225    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
89226    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
89227    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
89228    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
89229    sqlite3VdbeAddOp0(v, OP_Close);
89230  }
89231}
89232
89233/*
89234** Update the maximum rowid for an autoincrement calculation.
89235**
89236** This routine should be called when the top of the stack holds a
89237** new rowid that is about to be inserted.  If that new rowid is
89238** larger than the maximum rowid in the memId memory cell, then the
89239** memory cell is updated.  The stack is unchanged.
89240*/
89241static void autoIncStep(Parse *pParse, int memId, int regRowid){
89242  if( memId>0 ){
89243    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
89244  }
89245}
89246
89247/*
89248** This routine generates the code needed to write autoincrement
89249** maximum rowid values back into the sqlite_sequence register.
89250** Every statement that might do an INSERT into an autoincrement
89251** table (either directly or through triggers) needs to call this
89252** routine just before the "exit" code.
89253*/
89254SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
89255  AutoincInfo *p;
89256  Vdbe *v = pParse->pVdbe;
89257  sqlite3 *db = pParse->db;
89258
89259  assert( v );
89260  for(p = pParse->pAinc; p; p = p->pNext){
89261    Db *pDb = &db->aDb[p->iDb];
89262    int j1, j2, j3, j4, j5;
89263    int iRec;
89264    int memId = p->regCtr;
89265
89266    iRec = sqlite3GetTempReg(pParse);
89267    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
89268    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
89269    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
89270    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
89271    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
89272    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
89273    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
89274    sqlite3VdbeJumpHere(v, j2);
89275    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
89276    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
89277    sqlite3VdbeJumpHere(v, j4);
89278    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
89279    sqlite3VdbeJumpHere(v, j1);
89280    sqlite3VdbeJumpHere(v, j5);
89281    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
89282    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
89283    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89284    sqlite3VdbeAddOp0(v, OP_Close);
89285    sqlite3ReleaseTempReg(pParse, iRec);
89286  }
89287}
89288#else
89289/*
89290** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
89291** above are all no-ops
89292*/
89293# define autoIncBegin(A,B,C) (0)
89294# define autoIncStep(A,B,C)
89295#endif /* SQLITE_OMIT_AUTOINCREMENT */
89296
89297
89298/* Forward declaration */
89299static int xferOptimization(
89300  Parse *pParse,        /* Parser context */
89301  Table *pDest,         /* The table we are inserting into */
89302  Select *pSelect,      /* A SELECT statement to use as the data source */
89303  int onError,          /* How to handle constraint errors */
89304  int iDbDest           /* The database of pDest */
89305);
89306
89307/*
89308** This routine is call to handle SQL of the following forms:
89309**
89310**    insert into TABLE (IDLIST) values(EXPRLIST)
89311**    insert into TABLE (IDLIST) select
89312**
89313** The IDLIST following the table name is always optional.  If omitted,
89314** then a list of all columns for the table is substituted.  The IDLIST
89315** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
89316**
89317** The pList parameter holds EXPRLIST in the first form of the INSERT
89318** statement above, and pSelect is NULL.  For the second form, pList is
89319** NULL and pSelect is a pointer to the select statement used to generate
89320** data for the insert.
89321**
89322** The code generated follows one of four templates.  For a simple
89323** select with data coming from a VALUES clause, the code executes
89324** once straight down through.  Pseudo-code follows (we call this
89325** the "1st template"):
89326**
89327**         open write cursor to <table> and its indices
89328**         puts VALUES clause expressions onto the stack
89329**         write the resulting record into <table>
89330**         cleanup
89331**
89332** The three remaining templates assume the statement is of the form
89333**
89334**   INSERT INTO <table> SELECT ...
89335**
89336** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
89337** in other words if the SELECT pulls all columns from a single table
89338** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
89339** if <table2> and <table1> are distinct tables but have identical
89340** schemas, including all the same indices, then a special optimization
89341** is invoked that copies raw records from <table2> over to <table1>.
89342** See the xferOptimization() function for the implementation of this
89343** template.  This is the 2nd template.
89344**
89345**         open a write cursor to <table>
89346**         open read cursor on <table2>
89347**         transfer all records in <table2> over to <table>
89348**         close cursors
89349**         foreach index on <table>
89350**           open a write cursor on the <table> index
89351**           open a read cursor on the corresponding <table2> index
89352**           transfer all records from the read to the write cursors
89353**           close cursors
89354**         end foreach
89355**
89356** The 3rd template is for when the second template does not apply
89357** and the SELECT clause does not read from <table> at any time.
89358** The generated code follows this template:
89359**
89360**         EOF <- 0
89361**         X <- A
89362**         goto B
89363**      A: setup for the SELECT
89364**         loop over the rows in the SELECT
89365**           load values into registers R..R+n
89366**           yield X
89367**         end loop
89368**         cleanup after the SELECT
89369**         EOF <- 1
89370**         yield X
89371**         goto A
89372**      B: open write cursor to <table> and its indices
89373**      C: yield X
89374**         if EOF goto D
89375**         insert the select result into <table> from R..R+n
89376**         goto C
89377**      D: cleanup
89378**
89379** The 4th template is used if the insert statement takes its
89380** values from a SELECT but the data is being inserted into a table
89381** that is also read as part of the SELECT.  In the third form,
89382** we have to use a intermediate table to store the results of
89383** the select.  The template is like this:
89384**
89385**         EOF <- 0
89386**         X <- A
89387**         goto B
89388**      A: setup for the SELECT
89389**         loop over the tables in the SELECT
89390**           load value into register R..R+n
89391**           yield X
89392**         end loop
89393**         cleanup after the SELECT
89394**         EOF <- 1
89395**         yield X
89396**         halt-error
89397**      B: open temp table
89398**      L: yield X
89399**         if EOF goto M
89400**         insert row from R..R+n into temp table
89401**         goto L
89402**      M: open write cursor to <table> and its indices
89403**         rewind temp table
89404**      C: loop over rows of intermediate table
89405**           transfer values form intermediate table into <table>
89406**         end loop
89407**      D: cleanup
89408*/
89409SQLITE_PRIVATE void sqlite3Insert(
89410  Parse *pParse,        /* Parser context */
89411  SrcList *pTabList,    /* Name of table into which we are inserting */
89412  ExprList *pList,      /* List of values to be inserted */
89413  Select *pSelect,      /* A SELECT statement to use as the data source */
89414  IdList *pColumn,      /* Column names corresponding to IDLIST. */
89415  int onError           /* How to handle constraint errors */
89416){
89417  sqlite3 *db;          /* The main database structure */
89418  Table *pTab;          /* The table to insert into.  aka TABLE */
89419  char *zTab;           /* Name of the table into which we are inserting */
89420  const char *zDb;      /* Name of the database holding this table */
89421  int i, j, idx;        /* Loop counters */
89422  Vdbe *v;              /* Generate code into this virtual machine */
89423  Index *pIdx;          /* For looping over indices of the table */
89424  int nColumn;          /* Number of columns in the data */
89425  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
89426  int baseCur = 0;      /* VDBE Cursor number for pTab */
89427  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
89428  int endOfLoop;        /* Label for the end of the insertion loop */
89429  int useTempTable = 0; /* Store SELECT results in intermediate table */
89430  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
89431  int addrInsTop = 0;   /* Jump to label "D" */
89432  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
89433  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
89434  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
89435  int iDb;              /* Index of database holding TABLE */
89436  Db *pDb;              /* The database containing table being inserted into */
89437  int appendFlag = 0;   /* True if the insert is likely to be an append */
89438
89439  /* Register allocations */
89440  int regFromSelect = 0;/* Base register for data coming from SELECT */
89441  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
89442  int regRowCount = 0;  /* Memory cell used for the row counter */
89443  int regIns;           /* Block of regs holding rowid+data being inserted */
89444  int regRowid;         /* registers holding insert rowid */
89445  int regData;          /* register holding first column to insert */
89446  int regEof = 0;       /* Register recording end of SELECT data */
89447  int *aRegIdx = 0;     /* One register allocated to each index */
89448
89449#ifndef SQLITE_OMIT_TRIGGER
89450  int isView;                 /* True if attempting to insert into a view */
89451  Trigger *pTrigger;          /* List of triggers on pTab, if required */
89452  int tmask;                  /* Mask of trigger times */
89453#endif
89454
89455  db = pParse->db;
89456  memset(&dest, 0, sizeof(dest));
89457  if( pParse->nErr || db->mallocFailed ){
89458    goto insert_cleanup;
89459  }
89460
89461  /* Locate the table into which we will be inserting new information.
89462  */
89463  assert( pTabList->nSrc==1 );
89464  zTab = pTabList->a[0].zName;
89465  if( NEVER(zTab==0) ) goto insert_cleanup;
89466  pTab = sqlite3SrcListLookup(pParse, pTabList);
89467  if( pTab==0 ){
89468    goto insert_cleanup;
89469  }
89470  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89471  assert( iDb<db->nDb );
89472  pDb = &db->aDb[iDb];
89473  zDb = pDb->zName;
89474  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
89475    goto insert_cleanup;
89476  }
89477
89478  /* Figure out if we have any triggers and if the table being
89479  ** inserted into is a view
89480  */
89481#ifndef SQLITE_OMIT_TRIGGER
89482  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
89483  isView = pTab->pSelect!=0;
89484#else
89485# define pTrigger 0
89486# define tmask 0
89487# define isView 0
89488#endif
89489#ifdef SQLITE_OMIT_VIEW
89490# undef isView
89491# define isView 0
89492#endif
89493  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
89494
89495  /* If pTab is really a view, make sure it has been initialized.
89496  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
89497  ** module table).
89498  */
89499  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
89500    goto insert_cleanup;
89501  }
89502
89503  /* Ensure that:
89504  *  (a) the table is not read-only,
89505  *  (b) that if it is a view then ON INSERT triggers exist
89506  */
89507  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
89508    goto insert_cleanup;
89509  }
89510
89511  /* Allocate a VDBE
89512  */
89513  v = sqlite3GetVdbe(pParse);
89514  if( v==0 ) goto insert_cleanup;
89515  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
89516  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
89517
89518#ifndef SQLITE_OMIT_XFER_OPT
89519  /* If the statement is of the form
89520  **
89521  **       INSERT INTO <table1> SELECT * FROM <table2>;
89522  **
89523  ** Then special optimizations can be applied that make the transfer
89524  ** very fast and which reduce fragmentation of indices.
89525  **
89526  ** This is the 2nd template.
89527  */
89528  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
89529    assert( !pTrigger );
89530    assert( pList==0 );
89531    goto insert_end;
89532  }
89533#endif /* SQLITE_OMIT_XFER_OPT */
89534
89535  /* If this is an AUTOINCREMENT table, look up the sequence number in the
89536  ** sqlite_sequence table and store it in memory cell regAutoinc.
89537  */
89538  regAutoinc = autoIncBegin(pParse, iDb, pTab);
89539
89540  /* Figure out how many columns of data are supplied.  If the data
89541  ** is coming from a SELECT statement, then generate a co-routine that
89542  ** produces a single row of the SELECT on each invocation.  The
89543  ** co-routine is the common header to the 3rd and 4th templates.
89544  */
89545  if( pSelect ){
89546    /* Data is coming from a SELECT.  Generate code to implement that SELECT
89547    ** as a co-routine.  The code is common to both the 3rd and 4th
89548    ** templates:
89549    **
89550    **         EOF <- 0
89551    **         X <- A
89552    **         goto B
89553    **      A: setup for the SELECT
89554    **         loop over the tables in the SELECT
89555    **           load value into register R..R+n
89556    **           yield X
89557    **         end loop
89558    **         cleanup after the SELECT
89559    **         EOF <- 1
89560    **         yield X
89561    **         halt-error
89562    **
89563    ** On each invocation of the co-routine, it puts a single row of the
89564    ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
89565    ** (These output registers are allocated by sqlite3Select().)  When
89566    ** the SELECT completes, it sets the EOF flag stored in regEof.
89567    */
89568    int rc, j1;
89569
89570    regEof = ++pParse->nMem;
89571    sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
89572    VdbeComment((v, "SELECT eof flag"));
89573    sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
89574    addrSelect = sqlite3VdbeCurrentAddr(v)+2;
89575    sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
89576    j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
89577    VdbeComment((v, "Jump over SELECT coroutine"));
89578
89579    /* Resolve the expressions in the SELECT statement and execute it. */
89580    rc = sqlite3Select(pParse, pSelect, &dest);
89581    assert( pParse->nErr==0 || rc );
89582    if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
89583      goto insert_cleanup;
89584    }
89585    sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
89586    sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
89587    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
89588    VdbeComment((v, "End of SELECT coroutine"));
89589    sqlite3VdbeJumpHere(v, j1);                          /* label B: */
89590
89591    regFromSelect = dest.iMem;
89592    assert( pSelect->pEList );
89593    nColumn = pSelect->pEList->nExpr;
89594    assert( dest.nMem==nColumn );
89595
89596    /* Set useTempTable to TRUE if the result of the SELECT statement
89597    ** should be written into a temporary table (template 4).  Set to
89598    ** FALSE if each* row of the SELECT can be written directly into
89599    ** the destination table (template 3).
89600    **
89601    ** A temp table must be used if the table being updated is also one
89602    ** of the tables being read by the SELECT statement.  Also use a
89603    ** temp table in the case of row triggers.
89604    */
89605    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
89606      useTempTable = 1;
89607    }
89608
89609    if( useTempTable ){
89610      /* Invoke the coroutine to extract information from the SELECT
89611      ** and add it to a transient table srcTab.  The code generated
89612      ** here is from the 4th template:
89613      **
89614      **      B: open temp table
89615      **      L: yield X
89616      **         if EOF goto M
89617      **         insert row from R..R+n into temp table
89618      **         goto L
89619      **      M: ...
89620      */
89621      int regRec;          /* Register to hold packed record */
89622      int regTempRowid;    /* Register to hold temp table ROWID */
89623      int addrTop;         /* Label "L" */
89624      int addrIf;          /* Address of jump to M */
89625
89626      srcTab = pParse->nTab++;
89627      regRec = sqlite3GetTempReg(pParse);
89628      regTempRowid = sqlite3GetTempReg(pParse);
89629      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
89630      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
89631      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
89632      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
89633      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
89634      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
89635      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
89636      sqlite3VdbeJumpHere(v, addrIf);
89637      sqlite3ReleaseTempReg(pParse, regRec);
89638      sqlite3ReleaseTempReg(pParse, regTempRowid);
89639    }
89640  }else{
89641    /* This is the case if the data for the INSERT is coming from a VALUES
89642    ** clause
89643    */
89644    NameContext sNC;
89645    memset(&sNC, 0, sizeof(sNC));
89646    sNC.pParse = pParse;
89647    srcTab = -1;
89648    assert( useTempTable==0 );
89649    nColumn = pList ? pList->nExpr : 0;
89650    for(i=0; i<nColumn; i++){
89651      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
89652        goto insert_cleanup;
89653      }
89654    }
89655  }
89656
89657  /* Make sure the number of columns in the source data matches the number
89658  ** of columns to be inserted into the table.
89659  */
89660  if( IsVirtual(pTab) ){
89661    for(i=0; i<pTab->nCol; i++){
89662      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
89663    }
89664  }
89665  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
89666    sqlite3ErrorMsg(pParse,
89667       "table %S has %d columns but %d values were supplied",
89668       pTabList, 0, pTab->nCol-nHidden, nColumn);
89669    goto insert_cleanup;
89670  }
89671  if( pColumn!=0 && nColumn!=pColumn->nId ){
89672    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
89673    goto insert_cleanup;
89674  }
89675
89676  /* If the INSERT statement included an IDLIST term, then make sure
89677  ** all elements of the IDLIST really are columns of the table and
89678  ** remember the column indices.
89679  **
89680  ** If the table has an INTEGER PRIMARY KEY column and that column
89681  ** is named in the IDLIST, then record in the keyColumn variable
89682  ** the index into IDLIST of the primary key column.  keyColumn is
89683  ** the index of the primary key as it appears in IDLIST, not as
89684  ** is appears in the original table.  (The index of the primary
89685  ** key in the original table is pTab->iPKey.)
89686  */
89687  if( pColumn ){
89688    for(i=0; i<pColumn->nId; i++){
89689      pColumn->a[i].idx = -1;
89690    }
89691    for(i=0; i<pColumn->nId; i++){
89692      for(j=0; j<pTab->nCol; j++){
89693        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
89694          pColumn->a[i].idx = j;
89695          if( j==pTab->iPKey ){
89696            keyColumn = i;
89697          }
89698          break;
89699        }
89700      }
89701      if( j>=pTab->nCol ){
89702        if( sqlite3IsRowid(pColumn->a[i].zName) ){
89703          keyColumn = i;
89704        }else{
89705          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
89706              pTabList, 0, pColumn->a[i].zName);
89707          pParse->checkSchema = 1;
89708          goto insert_cleanup;
89709        }
89710      }
89711    }
89712  }
89713
89714  /* If there is no IDLIST term but the table has an integer primary
89715  ** key, the set the keyColumn variable to the primary key column index
89716  ** in the original table definition.
89717  */
89718  if( pColumn==0 && nColumn>0 ){
89719    keyColumn = pTab->iPKey;
89720  }
89721
89722  /* Initialize the count of rows to be inserted
89723  */
89724  if( db->flags & SQLITE_CountRows ){
89725    regRowCount = ++pParse->nMem;
89726    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
89727  }
89728
89729  /* If this is not a view, open the table and and all indices */
89730  if( !isView ){
89731    int nIdx;
89732
89733    baseCur = pParse->nTab;
89734    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
89735    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
89736    if( aRegIdx==0 ){
89737      goto insert_cleanup;
89738    }
89739    for(i=0; i<nIdx; i++){
89740      aRegIdx[i] = ++pParse->nMem;
89741    }
89742  }
89743
89744  /* This is the top of the main insertion loop */
89745  if( useTempTable ){
89746    /* This block codes the top of loop only.  The complete loop is the
89747    ** following pseudocode (template 4):
89748    **
89749    **         rewind temp table
89750    **      C: loop over rows of intermediate table
89751    **           transfer values form intermediate table into <table>
89752    **         end loop
89753    **      D: ...
89754    */
89755    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
89756    addrCont = sqlite3VdbeCurrentAddr(v);
89757  }else if( pSelect ){
89758    /* This block codes the top of loop only.  The complete loop is the
89759    ** following pseudocode (template 3):
89760    **
89761    **      C: yield X
89762    **         if EOF goto D
89763    **         insert the select result into <table> from R..R+n
89764    **         goto C
89765    **      D: ...
89766    */
89767    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
89768    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
89769  }
89770
89771  /* Allocate registers for holding the rowid of the new row,
89772  ** the content of the new row, and the assemblied row record.
89773  */
89774  regRowid = regIns = pParse->nMem+1;
89775  pParse->nMem += pTab->nCol + 1;
89776  if( IsVirtual(pTab) ){
89777    regRowid++;
89778    pParse->nMem++;
89779  }
89780  regData = regRowid+1;
89781
89782  /* Run the BEFORE and INSTEAD OF triggers, if there are any
89783  */
89784  endOfLoop = sqlite3VdbeMakeLabel(v);
89785  if( tmask & TRIGGER_BEFORE ){
89786    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
89787
89788    /* build the NEW.* reference row.  Note that if there is an INTEGER
89789    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
89790    ** translated into a unique ID for the row.  But on a BEFORE trigger,
89791    ** we do not know what the unique ID will be (because the insert has
89792    ** not happened yet) so we substitute a rowid of -1
89793    */
89794    if( keyColumn<0 ){
89795      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89796    }else{
89797      int j1;
89798      if( useTempTable ){
89799        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
89800      }else{
89801        assert( pSelect==0 );  /* Otherwise useTempTable is true */
89802        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
89803      }
89804      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
89805      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89806      sqlite3VdbeJumpHere(v, j1);
89807      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
89808    }
89809
89810    /* Cannot have triggers on a virtual table. If it were possible,
89811    ** this block would have to account for hidden column.
89812    */
89813    assert( !IsVirtual(pTab) );
89814
89815    /* Create the new column data
89816    */
89817    for(i=0; i<pTab->nCol; i++){
89818      if( pColumn==0 ){
89819        j = i;
89820      }else{
89821        for(j=0; j<pColumn->nId; j++){
89822          if( pColumn->a[j].idx==i ) break;
89823        }
89824      }
89825      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
89826        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
89827      }else if( useTempTable ){
89828        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
89829      }else{
89830        assert( pSelect==0 ); /* Otherwise useTempTable is true */
89831        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
89832      }
89833    }
89834
89835    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
89836    ** do not attempt any conversions before assembling the record.
89837    ** If this is a real table, attempt conversions as required by the
89838    ** table column affinities.
89839    */
89840    if( !isView ){
89841      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
89842      sqlite3TableAffinityStr(v, pTab);
89843    }
89844
89845    /* Fire BEFORE or INSTEAD OF triggers */
89846    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
89847        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
89848
89849    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
89850  }
89851
89852  /* Push the record number for the new entry onto the stack.  The
89853  ** record number is a randomly generate integer created by NewRowid
89854  ** except when the table has an INTEGER PRIMARY KEY column, in which
89855  ** case the record number is the same as that column.
89856  */
89857  if( !isView ){
89858    if( IsVirtual(pTab) ){
89859      /* The row that the VUpdate opcode will delete: none */
89860      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
89861    }
89862    if( keyColumn>=0 ){
89863      if( useTempTable ){
89864        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
89865      }else if( pSelect ){
89866        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
89867      }else{
89868        VdbeOp *pOp;
89869        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
89870        pOp = sqlite3VdbeGetOp(v, -1);
89871        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
89872          appendFlag = 1;
89873          pOp->opcode = OP_NewRowid;
89874          pOp->p1 = baseCur;
89875          pOp->p2 = regRowid;
89876          pOp->p3 = regAutoinc;
89877        }
89878      }
89879      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
89880      ** to generate a unique primary key value.
89881      */
89882      if( !appendFlag ){
89883        int j1;
89884        if( !IsVirtual(pTab) ){
89885          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
89886          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89887          sqlite3VdbeJumpHere(v, j1);
89888        }else{
89889          j1 = sqlite3VdbeCurrentAddr(v);
89890          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
89891        }
89892        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
89893      }
89894    }else if( IsVirtual(pTab) ){
89895      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
89896    }else{
89897      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89898      appendFlag = 1;
89899    }
89900    autoIncStep(pParse, regAutoinc, regRowid);
89901
89902    /* Push onto the stack, data for all columns of the new entry, beginning
89903    ** with the first column.
89904    */
89905    nHidden = 0;
89906    for(i=0; i<pTab->nCol; i++){
89907      int iRegStore = regRowid+1+i;
89908      if( i==pTab->iPKey ){
89909        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
89910        ** Whenever this column is read, the record number will be substituted
89911        ** in its place.  So will fill this column with a NULL to avoid
89912        ** taking up data space with information that will never be used. */
89913        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
89914        continue;
89915      }
89916      if( pColumn==0 ){
89917        if( IsHiddenColumn(&pTab->aCol[i]) ){
89918          assert( IsVirtual(pTab) );
89919          j = -1;
89920          nHidden++;
89921        }else{
89922          j = i - nHidden;
89923        }
89924      }else{
89925        for(j=0; j<pColumn->nId; j++){
89926          if( pColumn->a[j].idx==i ) break;
89927        }
89928      }
89929      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
89930        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
89931      }else if( useTempTable ){
89932        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
89933      }else if( pSelect ){
89934        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
89935      }else{
89936        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
89937      }
89938    }
89939
89940    /* Generate code to check constraints and generate index keys and
89941    ** do the insertion.
89942    */
89943#ifndef SQLITE_OMIT_VIRTUALTABLE
89944    if( IsVirtual(pTab) ){
89945      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
89946      sqlite3VtabMakeWritable(pParse, pTab);
89947      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
89948      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
89949      sqlite3MayAbort(pParse);
89950    }else
89951#endif
89952    {
89953      int isReplace;    /* Set to true if constraints may cause a replace */
89954      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
89955          keyColumn>=0, 0, onError, endOfLoop, &isReplace
89956      );
89957      sqlite3FkCheck(pParse, pTab, 0, regIns);
89958      sqlite3CompleteInsertion(
89959          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
89960      );
89961    }
89962  }
89963
89964  /* Update the count of rows that are inserted
89965  */
89966  if( (db->flags & SQLITE_CountRows)!=0 ){
89967    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
89968  }
89969
89970  if( pTrigger ){
89971    /* Code AFTER triggers */
89972    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
89973        pTab, regData-2-pTab->nCol, onError, endOfLoop);
89974  }
89975
89976  /* The bottom of the main insertion loop, if the data source
89977  ** is a SELECT statement.
89978  */
89979  sqlite3VdbeResolveLabel(v, endOfLoop);
89980  if( useTempTable ){
89981    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
89982    sqlite3VdbeJumpHere(v, addrInsTop);
89983    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
89984  }else if( pSelect ){
89985    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
89986    sqlite3VdbeJumpHere(v, addrInsTop);
89987  }
89988
89989  if( !IsVirtual(pTab) && !isView ){
89990    /* Close all tables opened */
89991    sqlite3VdbeAddOp1(v, OP_Close, baseCur);
89992    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
89993      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
89994    }
89995  }
89996
89997insert_end:
89998  /* Update the sqlite_sequence table by storing the content of the
89999  ** maximum rowid counter values recorded while inserting into
90000  ** autoincrement tables.
90001  */
90002  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
90003    sqlite3AutoincrementEnd(pParse);
90004  }
90005
90006  /*
90007  ** Return the number of rows inserted. If this routine is
90008  ** generating code because of a call to sqlite3NestedParse(), do not
90009  ** invoke the callback function.
90010  */
90011  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
90012    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
90013    sqlite3VdbeSetNumCols(v, 1);
90014    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
90015  }
90016
90017insert_cleanup:
90018  sqlite3SrcListDelete(db, pTabList);
90019  sqlite3ExprListDelete(db, pList);
90020  sqlite3SelectDelete(db, pSelect);
90021  sqlite3IdListDelete(db, pColumn);
90022  sqlite3DbFree(db, aRegIdx);
90023}
90024
90025/* Make sure "isView" and other macros defined above are undefined. Otherwise
90026** thely may interfere with compilation of other functions in this file
90027** (or in another file, if this file becomes part of the amalgamation).  */
90028#ifdef isView
90029 #undef isView
90030#endif
90031#ifdef pTrigger
90032 #undef pTrigger
90033#endif
90034#ifdef tmask
90035 #undef tmask
90036#endif
90037
90038
90039/*
90040** Generate code to do constraint checks prior to an INSERT or an UPDATE.
90041**
90042** The input is a range of consecutive registers as follows:
90043**
90044**    1.  The rowid of the row after the update.
90045**
90046**    2.  The data in the first column of the entry after the update.
90047**
90048**    i.  Data from middle columns...
90049**
90050**    N.  The data in the last column of the entry after the update.
90051**
90052** The regRowid parameter is the index of the register containing (1).
90053**
90054** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
90055** the address of a register containing the rowid before the update takes
90056** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
90057** is false, indicating an INSERT statement, then a non-zero rowidChng
90058** indicates that the rowid was explicitly specified as part of the
90059** INSERT statement. If rowidChng is false, it means that  the rowid is
90060** computed automatically in an insert or that the rowid value is not
90061** modified by an update.
90062**
90063** The code generated by this routine store new index entries into
90064** registers identified by aRegIdx[].  No index entry is created for
90065** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
90066** the same as the order of indices on the linked list of indices
90067** attached to the table.
90068**
90069** This routine also generates code to check constraints.  NOT NULL,
90070** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
90071** then the appropriate action is performed.  There are five possible
90072** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
90073**
90074**  Constraint type  Action       What Happens
90075**  ---------------  ----------   ----------------------------------------
90076**  any              ROLLBACK     The current transaction is rolled back and
90077**                                sqlite3_exec() returns immediately with a
90078**                                return code of SQLITE_CONSTRAINT.
90079**
90080**  any              ABORT        Back out changes from the current command
90081**                                only (do not do a complete rollback) then
90082**                                cause sqlite3_exec() to return immediately
90083**                                with SQLITE_CONSTRAINT.
90084**
90085**  any              FAIL         Sqlite3_exec() returns immediately with a
90086**                                return code of SQLITE_CONSTRAINT.  The
90087**                                transaction is not rolled back and any
90088**                                prior changes are retained.
90089**
90090**  any              IGNORE       The record number and data is popped from
90091**                                the stack and there is an immediate jump
90092**                                to label ignoreDest.
90093**
90094**  NOT NULL         REPLACE      The NULL value is replace by the default
90095**                                value for that column.  If the default value
90096**                                is NULL, the action is the same as ABORT.
90097**
90098**  UNIQUE           REPLACE      The other row that conflicts with the row
90099**                                being inserted is removed.
90100**
90101**  CHECK            REPLACE      Illegal.  The results in an exception.
90102**
90103** Which action to take is determined by the overrideError parameter.
90104** Or if overrideError==OE_Default, then the pParse->onError parameter
90105** is used.  Or if pParse->onError==OE_Default then the onError value
90106** for the constraint is used.
90107**
90108** The calling routine must open a read/write cursor for pTab with
90109** cursor number "baseCur".  All indices of pTab must also have open
90110** read/write cursors with cursor number baseCur+i for the i-th cursor.
90111** Except, if there is no possibility of a REPLACE action then
90112** cursors do not need to be open for indices where aRegIdx[i]==0.
90113*/
90114SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
90115  Parse *pParse,      /* The parser context */
90116  Table *pTab,        /* the table into which we are inserting */
90117  int baseCur,        /* Index of a read/write cursor pointing at pTab */
90118  int regRowid,       /* Index of the range of input registers */
90119  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
90120  int rowidChng,      /* True if the rowid might collide with existing entry */
90121  int isUpdate,       /* True for UPDATE, False for INSERT */
90122  int overrideError,  /* Override onError to this if not OE_Default */
90123  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
90124  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
90125){
90126  int i;              /* loop counter */
90127  Vdbe *v;            /* VDBE under constrution */
90128  int nCol;           /* Number of columns */
90129  int onError;        /* Conflict resolution strategy */
90130  int j1;             /* Addresss of jump instruction */
90131  int j2 = 0, j3;     /* Addresses of jump instructions */
90132  int regData;        /* Register containing first data column */
90133  int iCur;           /* Table cursor number */
90134  Index *pIdx;         /* Pointer to one of the indices */
90135  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
90136  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
90137
90138  v = sqlite3GetVdbe(pParse);
90139  assert( v!=0 );
90140  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
90141  nCol = pTab->nCol;
90142  regData = regRowid + 1;
90143
90144  /* Test all NOT NULL constraints.
90145  */
90146  for(i=0; i<nCol; i++){
90147    if( i==pTab->iPKey ){
90148      continue;
90149    }
90150    onError = pTab->aCol[i].notNull;
90151    if( onError==OE_None ) continue;
90152    if( overrideError!=OE_Default ){
90153      onError = overrideError;
90154    }else if( onError==OE_Default ){
90155      onError = OE_Abort;
90156    }
90157    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
90158      onError = OE_Abort;
90159    }
90160    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
90161        || onError==OE_Ignore || onError==OE_Replace );
90162    switch( onError ){
90163      case OE_Abort:
90164        sqlite3MayAbort(pParse);
90165      case OE_Rollback:
90166      case OE_Fail: {
90167        char *zMsg;
90168        sqlite3VdbeAddOp3(v, OP_HaltIfNull,
90169                                  SQLITE_CONSTRAINT, onError, regData+i);
90170        zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
90171                              pTab->zName, pTab->aCol[i].zName);
90172        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
90173        break;
90174      }
90175      case OE_Ignore: {
90176        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
90177        break;
90178      }
90179      default: {
90180        assert( onError==OE_Replace );
90181        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
90182        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
90183        sqlite3VdbeJumpHere(v, j1);
90184        break;
90185      }
90186    }
90187  }
90188
90189  /* Test all CHECK constraints
90190  */
90191#ifndef SQLITE_OMIT_CHECK
90192  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
90193    int allOk = sqlite3VdbeMakeLabel(v);
90194    pParse->ckBase = regData;
90195    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
90196    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
90197    if( onError==OE_Ignore ){
90198      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90199    }else{
90200      if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
90201      sqlite3HaltConstraint(pParse, onError, 0, 0);
90202    }
90203    sqlite3VdbeResolveLabel(v, allOk);
90204  }
90205#endif /* !defined(SQLITE_OMIT_CHECK) */
90206
90207  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
90208  ** of the new record does not previously exist.  Except, if this
90209  ** is an UPDATE and the primary key is not changing, that is OK.
90210  */
90211  if( rowidChng ){
90212    onError = pTab->keyConf;
90213    if( overrideError!=OE_Default ){
90214      onError = overrideError;
90215    }else if( onError==OE_Default ){
90216      onError = OE_Abort;
90217    }
90218
90219    if( isUpdate ){
90220      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
90221    }
90222    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
90223    switch( onError ){
90224      default: {
90225        onError = OE_Abort;
90226        /* Fall thru into the next case */
90227      }
90228      case OE_Rollback:
90229      case OE_Abort:
90230      case OE_Fail: {
90231        sqlite3HaltConstraint(
90232          pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
90233        break;
90234      }
90235      case OE_Replace: {
90236        /* If there are DELETE triggers on this table and the
90237        ** recursive-triggers flag is set, call GenerateRowDelete() to
90238        ** remove the conflicting row from the the table. This will fire
90239        ** the triggers and remove both the table and index b-tree entries.
90240        **
90241        ** Otherwise, if there are no triggers or the recursive-triggers
90242        ** flag is not set, but the table has one or more indexes, call
90243        ** GenerateRowIndexDelete(). This removes the index b-tree entries
90244        ** only. The table b-tree entry will be replaced by the new entry
90245        ** when it is inserted.
90246        **
90247        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
90248        ** also invoke MultiWrite() to indicate that this VDBE may require
90249        ** statement rollback (if the statement is aborted after the delete
90250        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
90251        ** but being more selective here allows statements like:
90252        **
90253        **   REPLACE INTO t(rowid) VALUES($newrowid)
90254        **
90255        ** to run without a statement journal if there are no indexes on the
90256        ** table.
90257        */
90258        Trigger *pTrigger = 0;
90259        if( pParse->db->flags&SQLITE_RecTriggers ){
90260          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90261        }
90262        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
90263          sqlite3MultiWrite(pParse);
90264          sqlite3GenerateRowDelete(
90265              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
90266          );
90267        }else if( pTab->pIndex ){
90268          sqlite3MultiWrite(pParse);
90269          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
90270        }
90271        seenReplace = 1;
90272        break;
90273      }
90274      case OE_Ignore: {
90275        assert( seenReplace==0 );
90276        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90277        break;
90278      }
90279    }
90280    sqlite3VdbeJumpHere(v, j3);
90281    if( isUpdate ){
90282      sqlite3VdbeJumpHere(v, j2);
90283    }
90284  }
90285
90286  /* Test all UNIQUE constraints by creating entries for each UNIQUE
90287  ** index and making sure that duplicate entries do not already exist.
90288  ** Add the new records to the indices as we go.
90289  */
90290  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
90291    int regIdx;
90292    int regR;
90293
90294    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
90295
90296    /* Create a key for accessing the index entry */
90297    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
90298    for(i=0; i<pIdx->nColumn; i++){
90299      int idx = pIdx->aiColumn[i];
90300      if( idx==pTab->iPKey ){
90301        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
90302      }else{
90303        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
90304      }
90305    }
90306    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
90307    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
90308    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
90309    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
90310
90311    /* Find out what action to take in case there is an indexing conflict */
90312    onError = pIdx->onError;
90313    if( onError==OE_None ){
90314      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
90315      continue;  /* pIdx is not a UNIQUE index */
90316    }
90317    if( overrideError!=OE_Default ){
90318      onError = overrideError;
90319    }else if( onError==OE_Default ){
90320      onError = OE_Abort;
90321    }
90322    if( seenReplace ){
90323      if( onError==OE_Ignore ) onError = OE_Replace;
90324      else if( onError==OE_Fail ) onError = OE_Abort;
90325    }
90326
90327    /* Check to see if the new index entry will be unique */
90328    regR = sqlite3GetTempReg(pParse);
90329    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
90330    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
90331                           regR, SQLITE_INT_TO_PTR(regIdx),
90332                           P4_INT32);
90333    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
90334
90335    /* Generate code that executes if the new index entry is not unique */
90336    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
90337        || onError==OE_Ignore || onError==OE_Replace );
90338    switch( onError ){
90339      case OE_Rollback:
90340      case OE_Abort:
90341      case OE_Fail: {
90342        int j;
90343        StrAccum errMsg;
90344        const char *zSep;
90345        char *zErr;
90346
90347        sqlite3StrAccumInit(&errMsg, 0, 0, 200);
90348        errMsg.db = pParse->db;
90349        zSep = pIdx->nColumn>1 ? "columns " : "column ";
90350        for(j=0; j<pIdx->nColumn; j++){
90351          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
90352          sqlite3StrAccumAppend(&errMsg, zSep, -1);
90353          zSep = ", ";
90354          sqlite3StrAccumAppend(&errMsg, zCol, -1);
90355        }
90356        sqlite3StrAccumAppend(&errMsg,
90357            pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
90358        zErr = sqlite3StrAccumFinish(&errMsg);
90359        sqlite3HaltConstraint(pParse, onError, zErr, 0);
90360        sqlite3DbFree(errMsg.db, zErr);
90361        break;
90362      }
90363      case OE_Ignore: {
90364        assert( seenReplace==0 );
90365        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90366        break;
90367      }
90368      default: {
90369        Trigger *pTrigger = 0;
90370        assert( onError==OE_Replace );
90371        sqlite3MultiWrite(pParse);
90372        if( pParse->db->flags&SQLITE_RecTriggers ){
90373          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90374        }
90375        sqlite3GenerateRowDelete(
90376            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
90377        );
90378        seenReplace = 1;
90379        break;
90380      }
90381    }
90382    sqlite3VdbeJumpHere(v, j3);
90383    sqlite3ReleaseTempReg(pParse, regR);
90384  }
90385
90386  if( pbMayReplace ){
90387    *pbMayReplace = seenReplace;
90388  }
90389}
90390
90391/*
90392** This routine generates code to finish the INSERT or UPDATE operation
90393** that was started by a prior call to sqlite3GenerateConstraintChecks.
90394** A consecutive range of registers starting at regRowid contains the
90395** rowid and the content to be inserted.
90396**
90397** The arguments to this routine should be the same as the first six
90398** arguments to sqlite3GenerateConstraintChecks.
90399*/
90400SQLITE_PRIVATE void sqlite3CompleteInsertion(
90401  Parse *pParse,      /* The parser context */
90402  Table *pTab,        /* the table into which we are inserting */
90403  int baseCur,        /* Index of a read/write cursor pointing at pTab */
90404  int regRowid,       /* Range of content */
90405  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
90406  int isUpdate,       /* True for UPDATE, False for INSERT */
90407  int appendBias,     /* True if this is likely to be an append */
90408  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
90409){
90410  int i;
90411  Vdbe *v;
90412  int nIdx;
90413  Index *pIdx;
90414  u8 pik_flags;
90415  int regData;
90416  int regRec;
90417
90418  v = sqlite3GetVdbe(pParse);
90419  assert( v!=0 );
90420  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
90421  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
90422  for(i=nIdx-1; i>=0; i--){
90423    if( aRegIdx[i]==0 ) continue;
90424    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
90425    if( useSeekResult ){
90426      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
90427    }
90428  }
90429  regData = regRowid + 1;
90430  regRec = sqlite3GetTempReg(pParse);
90431  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
90432  sqlite3TableAffinityStr(v, pTab);
90433  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
90434  if( pParse->nested ){
90435    pik_flags = 0;
90436  }else{
90437    pik_flags = OPFLAG_NCHANGE;
90438    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
90439  }
90440  if( appendBias ){
90441    pik_flags |= OPFLAG_APPEND;
90442  }
90443  if( useSeekResult ){
90444    pik_flags |= OPFLAG_USESEEKRESULT;
90445  }
90446  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
90447  if( !pParse->nested ){
90448    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
90449  }
90450  sqlite3VdbeChangeP5(v, pik_flags);
90451}
90452
90453/*
90454** Generate code that will open cursors for a table and for all
90455** indices of that table.  The "baseCur" parameter is the cursor number used
90456** for the table.  Indices are opened on subsequent cursors.
90457**
90458** Return the number of indices on the table.
90459*/
90460SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
90461  Parse *pParse,   /* Parsing context */
90462  Table *pTab,     /* Table to be opened */
90463  int baseCur,     /* Cursor number assigned to the table */
90464  int op           /* OP_OpenRead or OP_OpenWrite */
90465){
90466  int i;
90467  int iDb;
90468  Index *pIdx;
90469  Vdbe *v;
90470
90471  if( IsVirtual(pTab) ) return 0;
90472  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
90473  v = sqlite3GetVdbe(pParse);
90474  assert( v!=0 );
90475  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
90476  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
90477    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
90478    assert( pIdx->pSchema==pTab->pSchema );
90479    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
90480                      (char*)pKey, P4_KEYINFO_HANDOFF);
90481    VdbeComment((v, "%s", pIdx->zName));
90482  }
90483  if( pParse->nTab<baseCur+i ){
90484    pParse->nTab = baseCur+i;
90485  }
90486  return i-1;
90487}
90488
90489
90490#ifdef SQLITE_TEST
90491/*
90492** The following global variable is incremented whenever the
90493** transfer optimization is used.  This is used for testing
90494** purposes only - to make sure the transfer optimization really
90495** is happening when it is suppose to.
90496*/
90497SQLITE_API int sqlite3_xferopt_count;
90498#endif /* SQLITE_TEST */
90499
90500
90501#ifndef SQLITE_OMIT_XFER_OPT
90502/*
90503** Check to collation names to see if they are compatible.
90504*/
90505static int xferCompatibleCollation(const char *z1, const char *z2){
90506  if( z1==0 ){
90507    return z2==0;
90508  }
90509  if( z2==0 ){
90510    return 0;
90511  }
90512  return sqlite3StrICmp(z1, z2)==0;
90513}
90514
90515
90516/*
90517** Check to see if index pSrc is compatible as a source of data
90518** for index pDest in an insert transfer optimization.  The rules
90519** for a compatible index:
90520**
90521**    *   The index is over the same set of columns
90522**    *   The same DESC and ASC markings occurs on all columns
90523**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
90524**    *   The same collating sequence on each column
90525*/
90526static int xferCompatibleIndex(Index *pDest, Index *pSrc){
90527  int i;
90528  assert( pDest && pSrc );
90529  assert( pDest->pTable!=pSrc->pTable );
90530  if( pDest->nColumn!=pSrc->nColumn ){
90531    return 0;   /* Different number of columns */
90532  }
90533  if( pDest->onError!=pSrc->onError ){
90534    return 0;   /* Different conflict resolution strategies */
90535  }
90536  for(i=0; i<pSrc->nColumn; i++){
90537    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
90538      return 0;   /* Different columns indexed */
90539    }
90540    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
90541      return 0;   /* Different sort orders */
90542    }
90543    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
90544      return 0;   /* Different collating sequences */
90545    }
90546  }
90547
90548  /* If no test above fails then the indices must be compatible */
90549  return 1;
90550}
90551
90552/*
90553** Attempt the transfer optimization on INSERTs of the form
90554**
90555**     INSERT INTO tab1 SELECT * FROM tab2;
90556**
90557** The xfer optimization transfers raw records from tab2 over to tab1.
90558** Columns are not decoded and reassemblied, which greatly improves
90559** performance.  Raw index records are transferred in the same way.
90560**
90561** The xfer optimization is only attempted if tab1 and tab2 are compatible.
90562** There are lots of rules for determining compatibility - see comments
90563** embedded in the code for details.
90564**
90565** This routine returns TRUE if the optimization is guaranteed to be used.
90566** Sometimes the xfer optimization will only work if the destination table
90567** is empty - a factor that can only be determined at run-time.  In that
90568** case, this routine generates code for the xfer optimization but also
90569** does a test to see if the destination table is empty and jumps over the
90570** xfer optimization code if the test fails.  In that case, this routine
90571** returns FALSE so that the caller will know to go ahead and generate
90572** an unoptimized transfer.  This routine also returns FALSE if there
90573** is no chance that the xfer optimization can be applied.
90574**
90575** This optimization is particularly useful at making VACUUM run faster.
90576*/
90577static int xferOptimization(
90578  Parse *pParse,        /* Parser context */
90579  Table *pDest,         /* The table we are inserting into */
90580  Select *pSelect,      /* A SELECT statement to use as the data source */
90581  int onError,          /* How to handle constraint errors */
90582  int iDbDest           /* The database of pDest */
90583){
90584  ExprList *pEList;                /* The result set of the SELECT */
90585  Table *pSrc;                     /* The table in the FROM clause of SELECT */
90586  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
90587  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
90588  int i;                           /* Loop counter */
90589  int iDbSrc;                      /* The database of pSrc */
90590  int iSrc, iDest;                 /* Cursors from source and destination */
90591  int addr1, addr2;                /* Loop addresses */
90592  int emptyDestTest;               /* Address of test for empty pDest */
90593  int emptySrcTest;                /* Address of test for empty pSrc */
90594  Vdbe *v;                         /* The VDBE we are building */
90595  KeyInfo *pKey;                   /* Key information for an index */
90596  int regAutoinc;                  /* Memory register used by AUTOINC */
90597  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
90598  int regData, regRowid;           /* Registers holding data and rowid */
90599
90600  if( pSelect==0 ){
90601    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
90602  }
90603  if( sqlite3TriggerList(pParse, pDest) ){
90604    return 0;   /* tab1 must not have triggers */
90605  }
90606#ifndef SQLITE_OMIT_VIRTUALTABLE
90607  if( pDest->tabFlags & TF_Virtual ){
90608    return 0;   /* tab1 must not be a virtual table */
90609  }
90610#endif
90611  if( onError==OE_Default ){
90612    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
90613    if( onError==OE_Default ) onError = OE_Abort;
90614  }
90615  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
90616  if( pSelect->pSrc->nSrc!=1 ){
90617    return 0;   /* FROM clause must have exactly one term */
90618  }
90619  if( pSelect->pSrc->a[0].pSelect ){
90620    return 0;   /* FROM clause cannot contain a subquery */
90621  }
90622  if( pSelect->pWhere ){
90623    return 0;   /* SELECT may not have a WHERE clause */
90624  }
90625  if( pSelect->pOrderBy ){
90626    return 0;   /* SELECT may not have an ORDER BY clause */
90627  }
90628  /* Do not need to test for a HAVING clause.  If HAVING is present but
90629  ** there is no ORDER BY, we will get an error. */
90630  if( pSelect->pGroupBy ){
90631    return 0;   /* SELECT may not have a GROUP BY clause */
90632  }
90633  if( pSelect->pLimit ){
90634    return 0;   /* SELECT may not have a LIMIT clause */
90635  }
90636  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
90637  if( pSelect->pPrior ){
90638    return 0;   /* SELECT may not be a compound query */
90639  }
90640  if( pSelect->selFlags & SF_Distinct ){
90641    return 0;   /* SELECT may not be DISTINCT */
90642  }
90643  pEList = pSelect->pEList;
90644  assert( pEList!=0 );
90645  if( pEList->nExpr!=1 ){
90646    return 0;   /* The result set must have exactly one column */
90647  }
90648  assert( pEList->a[0].pExpr );
90649  if( pEList->a[0].pExpr->op!=TK_ALL ){
90650    return 0;   /* The result set must be the special operator "*" */
90651  }
90652
90653  /* At this point we have established that the statement is of the
90654  ** correct syntactic form to participate in this optimization.  Now
90655  ** we have to check the semantics.
90656  */
90657  pItem = pSelect->pSrc->a;
90658  pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
90659  if( pSrc==0 ){
90660    return 0;   /* FROM clause does not contain a real table */
90661  }
90662  if( pSrc==pDest ){
90663    return 0;   /* tab1 and tab2 may not be the same table */
90664  }
90665#ifndef SQLITE_OMIT_VIRTUALTABLE
90666  if( pSrc->tabFlags & TF_Virtual ){
90667    return 0;   /* tab2 must not be a virtual table */
90668  }
90669#endif
90670  if( pSrc->pSelect ){
90671    return 0;   /* tab2 may not be a view */
90672  }
90673  if( pDest->nCol!=pSrc->nCol ){
90674    return 0;   /* Number of columns must be the same in tab1 and tab2 */
90675  }
90676  if( pDest->iPKey!=pSrc->iPKey ){
90677    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
90678  }
90679  for(i=0; i<pDest->nCol; i++){
90680    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
90681      return 0;    /* Affinity must be the same on all columns */
90682    }
90683    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
90684      return 0;    /* Collating sequence must be the same on all columns */
90685    }
90686    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
90687      return 0;    /* tab2 must be NOT NULL if tab1 is */
90688    }
90689  }
90690  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90691    if( pDestIdx->onError!=OE_None ){
90692      destHasUniqueIdx = 1;
90693    }
90694    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
90695      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90696    }
90697    if( pSrcIdx==0 ){
90698      return 0;    /* pDestIdx has no corresponding index in pSrc */
90699    }
90700  }
90701#ifndef SQLITE_OMIT_CHECK
90702  if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
90703    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
90704  }
90705#endif
90706#ifndef SQLITE_OMIT_FOREIGN_KEY
90707  /* Disallow the transfer optimization if the destination table constains
90708  ** any foreign key constraints.  This is more restrictive than necessary.
90709  ** But the main beneficiary of the transfer optimization is the VACUUM
90710  ** command, and the VACUUM command disables foreign key constraints.  So
90711  ** the extra complication to make this rule less restrictive is probably
90712  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
90713  */
90714  if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
90715    return 0;
90716  }
90717#endif
90718  if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
90719    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
90720  }
90721
90722  /* If we get this far, it means that the xfer optimization is at
90723  ** least a possibility, though it might only work if the destination
90724  ** table (tab1) is initially empty.
90725  */
90726#ifdef SQLITE_TEST
90727  sqlite3_xferopt_count++;
90728#endif
90729  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
90730  v = sqlite3GetVdbe(pParse);
90731  sqlite3CodeVerifySchema(pParse, iDbSrc);
90732  iSrc = pParse->nTab++;
90733  iDest = pParse->nTab++;
90734  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
90735  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
90736  if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
90737   || destHasUniqueIdx                              /* (2) */
90738   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
90739  ){
90740    /* In some circumstances, we are able to run the xfer optimization
90741    ** only if the destination table is initially empty.  This code makes
90742    ** that determination.  Conditions under which the destination must
90743    ** be empty:
90744    **
90745    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
90746    **     (If the destination is not initially empty, the rowid fields
90747    **     of index entries might need to change.)
90748    **
90749    ** (2) The destination has a unique index.  (The xfer optimization
90750    **     is unable to test uniqueness.)
90751    **
90752    ** (3) onError is something other than OE_Abort and OE_Rollback.
90753    */
90754    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
90755    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
90756    sqlite3VdbeJumpHere(v, addr1);
90757  }else{
90758    emptyDestTest = 0;
90759  }
90760  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
90761  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90762  regData = sqlite3GetTempReg(pParse);
90763  regRowid = sqlite3GetTempReg(pParse);
90764  if( pDest->iPKey>=0 ){
90765    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90766    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
90767    sqlite3HaltConstraint(
90768        pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
90769    sqlite3VdbeJumpHere(v, addr2);
90770    autoIncStep(pParse, regAutoinc, regRowid);
90771  }else if( pDest->pIndex==0 ){
90772    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
90773  }else{
90774    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90775    assert( (pDest->tabFlags & TF_Autoincrement)==0 );
90776  }
90777  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
90778  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
90779  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
90780  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
90781  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
90782  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90783    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
90784      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90785    }
90786    assert( pSrcIdx );
90787    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
90788    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90789    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
90790    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
90791                      (char*)pKey, P4_KEYINFO_HANDOFF);
90792    VdbeComment((v, "%s", pSrcIdx->zName));
90793    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
90794    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
90795                      (char*)pKey, P4_KEYINFO_HANDOFF);
90796    VdbeComment((v, "%s", pDestIdx->zName));
90797    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90798    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
90799    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
90800    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
90801    sqlite3VdbeJumpHere(v, addr1);
90802  }
90803  sqlite3VdbeJumpHere(v, emptySrcTest);
90804  sqlite3ReleaseTempReg(pParse, regRowid);
90805  sqlite3ReleaseTempReg(pParse, regData);
90806  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
90807  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90808  if( emptyDestTest ){
90809    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
90810    sqlite3VdbeJumpHere(v, emptyDestTest);
90811    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90812    return 0;
90813  }else{
90814    return 1;
90815  }
90816}
90817#endif /* SQLITE_OMIT_XFER_OPT */
90818
90819/************** End of insert.c **********************************************/
90820/************** Begin file legacy.c ******************************************/
90821/*
90822** 2001 September 15
90823**
90824** The author disclaims copyright to this source code.  In place of
90825** a legal notice, here is a blessing:
90826**
90827**    May you do good and not evil.
90828**    May you find forgiveness for yourself and forgive others.
90829**    May you share freely, never taking more than you give.
90830**
90831*************************************************************************
90832** Main file for the SQLite library.  The routines in this file
90833** implement the programmer interface to the library.  Routines in
90834** other files are for internal use by SQLite and should not be
90835** accessed by users of the library.
90836*/
90837
90838
90839/*
90840** Execute SQL code.  Return one of the SQLITE_ success/failure
90841** codes.  Also write an error message into memory obtained from
90842** malloc() and make *pzErrMsg point to that message.
90843**
90844** If the SQL is a query, then for each row in the query result
90845** the xCallback() function is called.  pArg becomes the first
90846** argument to xCallback().  If xCallback=NULL then no callback
90847** is invoked, even for queries.
90848*/
90849SQLITE_API int sqlite3_exec(
90850  sqlite3 *db,                /* The database on which the SQL executes */
90851  const char *zSql,           /* The SQL to be executed */
90852  sqlite3_callback xCallback, /* Invoke this callback routine */
90853  void *pArg,                 /* First argument to xCallback() */
90854  char **pzErrMsg             /* Write error messages here */
90855){
90856  int rc = SQLITE_OK;         /* Return code */
90857  const char *zLeftover;      /* Tail of unprocessed SQL */
90858  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
90859  char **azCols = 0;          /* Names of result columns */
90860  int nRetry = 0;             /* Number of retry attempts */
90861  int callbackIsInit;         /* True if callback data is initialized */
90862
90863  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
90864  if( zSql==0 ) zSql = "";
90865
90866  sqlite3_mutex_enter(db->mutex);
90867  sqlite3Error(db, SQLITE_OK, 0);
90868  while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
90869    int nCol;
90870    char **azVals = 0;
90871
90872    pStmt = 0;
90873    rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
90874    assert( rc==SQLITE_OK || pStmt==0 );
90875    if( rc!=SQLITE_OK ){
90876      continue;
90877    }
90878    if( !pStmt ){
90879      /* this happens for a comment or white-space */
90880      zSql = zLeftover;
90881      continue;
90882    }
90883
90884    callbackIsInit = 0;
90885    nCol = sqlite3_column_count(pStmt);
90886
90887    while( 1 ){
90888      int i;
90889      rc = sqlite3_step(pStmt);
90890
90891      /* Invoke the callback function if required */
90892      if( xCallback && (SQLITE_ROW==rc ||
90893          (SQLITE_DONE==rc && !callbackIsInit
90894                           && db->flags&SQLITE_NullCallback)) ){
90895        if( !callbackIsInit ){
90896          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
90897          if( azCols==0 ){
90898            goto exec_out;
90899          }
90900          for(i=0; i<nCol; i++){
90901            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
90902            /* sqlite3VdbeSetColName() installs column names as UTF8
90903            ** strings so there is no way for sqlite3_column_name() to fail. */
90904            assert( azCols[i]!=0 );
90905          }
90906          callbackIsInit = 1;
90907        }
90908        if( rc==SQLITE_ROW ){
90909          azVals = &azCols[nCol];
90910          for(i=0; i<nCol; i++){
90911            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
90912            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
90913              db->mallocFailed = 1;
90914              goto exec_out;
90915            }
90916          }
90917        }
90918        if( xCallback(pArg, nCol, azVals, azCols) ){
90919          rc = SQLITE_ABORT;
90920          sqlite3VdbeFinalize((Vdbe *)pStmt);
90921          pStmt = 0;
90922          sqlite3Error(db, SQLITE_ABORT, 0);
90923          goto exec_out;
90924        }
90925      }
90926
90927      if( rc!=SQLITE_ROW ){
90928        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
90929        pStmt = 0;
90930        if( rc!=SQLITE_SCHEMA ){
90931          nRetry = 0;
90932          zSql = zLeftover;
90933          while( sqlite3Isspace(zSql[0]) ) zSql++;
90934        }
90935        break;
90936      }
90937    }
90938
90939    sqlite3DbFree(db, azCols);
90940    azCols = 0;
90941  }
90942
90943exec_out:
90944  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
90945  sqlite3DbFree(db, azCols);
90946
90947  rc = sqlite3ApiExit(db, rc);
90948  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
90949    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
90950    *pzErrMsg = sqlite3Malloc(nErrMsg);
90951    if( *pzErrMsg ){
90952      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
90953    }else{
90954      rc = SQLITE_NOMEM;
90955      sqlite3Error(db, SQLITE_NOMEM, 0);
90956    }
90957  }else if( pzErrMsg ){
90958    *pzErrMsg = 0;
90959  }
90960
90961  assert( (rc&db->errMask)==rc );
90962  sqlite3_mutex_leave(db->mutex);
90963  return rc;
90964}
90965
90966/************** End of legacy.c **********************************************/
90967/************** Begin file loadext.c *****************************************/
90968/*
90969** 2006 June 7
90970**
90971** The author disclaims copyright to this source code.  In place of
90972** a legal notice, here is a blessing:
90973**
90974**    May you do good and not evil.
90975**    May you find forgiveness for yourself and forgive others.
90976**    May you share freely, never taking more than you give.
90977**
90978*************************************************************************
90979** This file contains code used to dynamically load extensions into
90980** the SQLite library.
90981*/
90982
90983#ifndef SQLITE_CORE
90984  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
90985#endif
90986/************** Include sqlite3ext.h in the middle of loadext.c **************/
90987/************** Begin file sqlite3ext.h **************************************/
90988/*
90989** 2006 June 7
90990**
90991** The author disclaims copyright to this source code.  In place of
90992** a legal notice, here is a blessing:
90993**
90994**    May you do good and not evil.
90995**    May you find forgiveness for yourself and forgive others.
90996**    May you share freely, never taking more than you give.
90997**
90998*************************************************************************
90999** This header file defines the SQLite interface for use by
91000** shared libraries that want to be imported as extensions into
91001** an SQLite instance.  Shared libraries that intend to be loaded
91002** as extensions by SQLite should #include this file instead of
91003** sqlite3.h.
91004*/
91005#ifndef _SQLITE3EXT_H_
91006#define _SQLITE3EXT_H_
91007
91008typedef struct sqlite3_api_routines sqlite3_api_routines;
91009
91010/*
91011** The following structure holds pointers to all of the SQLite API
91012** routines.
91013**
91014** WARNING:  In order to maintain backwards compatibility, add new
91015** interfaces to the end of this structure only.  If you insert new
91016** interfaces in the middle of this structure, then older different
91017** versions of SQLite will not be able to load each others' shared
91018** libraries!
91019*/
91020struct sqlite3_api_routines {
91021  void * (*aggregate_context)(sqlite3_context*,int nBytes);
91022  int  (*aggregate_count)(sqlite3_context*);
91023  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
91024  int  (*bind_double)(sqlite3_stmt*,int,double);
91025  int  (*bind_int)(sqlite3_stmt*,int,int);
91026  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
91027  int  (*bind_null)(sqlite3_stmt*,int);
91028  int  (*bind_parameter_count)(sqlite3_stmt*);
91029  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
91030  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
91031  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
91032  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
91033  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
91034  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
91035  int  (*busy_timeout)(sqlite3*,int ms);
91036  int  (*changes)(sqlite3*);
91037  int  (*close)(sqlite3*);
91038  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
91039                           int eTextRep,const char*));
91040  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
91041                             int eTextRep,const void*));
91042  const void * (*column_blob)(sqlite3_stmt*,int iCol);
91043  int  (*column_bytes)(sqlite3_stmt*,int iCol);
91044  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
91045  int  (*column_count)(sqlite3_stmt*pStmt);
91046  const char * (*column_database_name)(sqlite3_stmt*,int);
91047  const void * (*column_database_name16)(sqlite3_stmt*,int);
91048  const char * (*column_decltype)(sqlite3_stmt*,int i);
91049  const void * (*column_decltype16)(sqlite3_stmt*,int);
91050  double  (*column_double)(sqlite3_stmt*,int iCol);
91051  int  (*column_int)(sqlite3_stmt*,int iCol);
91052  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
91053  const char * (*column_name)(sqlite3_stmt*,int);
91054  const void * (*column_name16)(sqlite3_stmt*,int);
91055  const char * (*column_origin_name)(sqlite3_stmt*,int);
91056  const void * (*column_origin_name16)(sqlite3_stmt*,int);
91057  const char * (*column_table_name)(sqlite3_stmt*,int);
91058  const void * (*column_table_name16)(sqlite3_stmt*,int);
91059  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
91060  const void * (*column_text16)(sqlite3_stmt*,int iCol);
91061  int  (*column_type)(sqlite3_stmt*,int iCol);
91062  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
91063  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
91064  int  (*complete)(const char*sql);
91065  int  (*complete16)(const void*sql);
91066  int  (*create_collation)(sqlite3*,const char*,int,void*,
91067                           int(*)(void*,int,const void*,int,const void*));
91068  int  (*create_collation16)(sqlite3*,const void*,int,void*,
91069                             int(*)(void*,int,const void*,int,const void*));
91070  int  (*create_function)(sqlite3*,const char*,int,int,void*,
91071                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91072                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91073                          void (*xFinal)(sqlite3_context*));
91074  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
91075                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91076                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91077                            void (*xFinal)(sqlite3_context*));
91078  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
91079  int  (*data_count)(sqlite3_stmt*pStmt);
91080  sqlite3 * (*db_handle)(sqlite3_stmt*);
91081  int (*declare_vtab)(sqlite3*,const char*);
91082  int  (*enable_shared_cache)(int);
91083  int  (*errcode)(sqlite3*db);
91084  const char * (*errmsg)(sqlite3*);
91085  const void * (*errmsg16)(sqlite3*);
91086  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
91087  int  (*expired)(sqlite3_stmt*);
91088  int  (*finalize)(sqlite3_stmt*pStmt);
91089  void  (*free)(void*);
91090  void  (*free_table)(char**result);
91091  int  (*get_autocommit)(sqlite3*);
91092  void * (*get_auxdata)(sqlite3_context*,int);
91093  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
91094  int  (*global_recover)(void);
91095  void  (*interruptx)(sqlite3*);
91096  sqlite_int64  (*last_insert_rowid)(sqlite3*);
91097  const char * (*libversion)(void);
91098  int  (*libversion_number)(void);
91099  void *(*malloc)(int);
91100  char * (*mprintf)(const char*,...);
91101  int  (*open)(const char*,sqlite3**);
91102  int  (*open16)(const void*,sqlite3**);
91103  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
91104  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
91105  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
91106  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
91107  void *(*realloc)(void*,int);
91108  int  (*reset)(sqlite3_stmt*pStmt);
91109  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
91110  void  (*result_double)(sqlite3_context*,double);
91111  void  (*result_error)(sqlite3_context*,const char*,int);
91112  void  (*result_error16)(sqlite3_context*,const void*,int);
91113  void  (*result_int)(sqlite3_context*,int);
91114  void  (*result_int64)(sqlite3_context*,sqlite_int64);
91115  void  (*result_null)(sqlite3_context*);
91116  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
91117  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
91118  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
91119  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
91120  void  (*result_value)(sqlite3_context*,sqlite3_value*);
91121  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
91122  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
91123                         const char*,const char*),void*);
91124  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
91125  char * (*snprintf)(int,char*,const char*,...);
91126  int  (*step)(sqlite3_stmt*);
91127  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
91128                                char const**,char const**,int*,int*,int*);
91129  void  (*thread_cleanup)(void);
91130  int  (*total_changes)(sqlite3*);
91131  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
91132  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
91133  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
91134                                         sqlite_int64),void*);
91135  void * (*user_data)(sqlite3_context*);
91136  const void * (*value_blob)(sqlite3_value*);
91137  int  (*value_bytes)(sqlite3_value*);
91138  int  (*value_bytes16)(sqlite3_value*);
91139  double  (*value_double)(sqlite3_value*);
91140  int  (*value_int)(sqlite3_value*);
91141  sqlite_int64  (*value_int64)(sqlite3_value*);
91142  int  (*value_numeric_type)(sqlite3_value*);
91143  const unsigned char * (*value_text)(sqlite3_value*);
91144  const void * (*value_text16)(sqlite3_value*);
91145  const void * (*value_text16be)(sqlite3_value*);
91146  const void * (*value_text16le)(sqlite3_value*);
91147  int  (*value_type)(sqlite3_value*);
91148  char *(*vmprintf)(const char*,va_list);
91149  /* Added ??? */
91150  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
91151  /* Added by 3.3.13 */
91152  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
91153  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
91154  int (*clear_bindings)(sqlite3_stmt*);
91155  /* Added by 3.4.1 */
91156  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
91157                          void (*xDestroy)(void *));
91158  /* Added by 3.5.0 */
91159  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
91160  int (*blob_bytes)(sqlite3_blob*);
91161  int (*blob_close)(sqlite3_blob*);
91162  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
91163                   int,sqlite3_blob**);
91164  int (*blob_read)(sqlite3_blob*,void*,int,int);
91165  int (*blob_write)(sqlite3_blob*,const void*,int,int);
91166  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
91167                             int(*)(void*,int,const void*,int,const void*),
91168                             void(*)(void*));
91169  int (*file_control)(sqlite3*,const char*,int,void*);
91170  sqlite3_int64 (*memory_highwater)(int);
91171  sqlite3_int64 (*memory_used)(void);
91172  sqlite3_mutex *(*mutex_alloc)(int);
91173  void (*mutex_enter)(sqlite3_mutex*);
91174  void (*mutex_free)(sqlite3_mutex*);
91175  void (*mutex_leave)(sqlite3_mutex*);
91176  int (*mutex_try)(sqlite3_mutex*);
91177  int (*open_v2)(const char*,sqlite3**,int,const char*);
91178  int (*release_memory)(int);
91179  void (*result_error_nomem)(sqlite3_context*);
91180  void (*result_error_toobig)(sqlite3_context*);
91181  int (*sleep)(int);
91182  void (*soft_heap_limit)(int);
91183  sqlite3_vfs *(*vfs_find)(const char*);
91184  int (*vfs_register)(sqlite3_vfs*,int);
91185  int (*vfs_unregister)(sqlite3_vfs*);
91186  int (*xthreadsafe)(void);
91187  void (*result_zeroblob)(sqlite3_context*,int);
91188  void (*result_error_code)(sqlite3_context*,int);
91189  int (*test_control)(int, ...);
91190  void (*randomness)(int,void*);
91191  sqlite3 *(*context_db_handle)(sqlite3_context*);
91192  int (*extended_result_codes)(sqlite3*,int);
91193  int (*limit)(sqlite3*,int,int);
91194  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
91195  const char *(*sql)(sqlite3_stmt*);
91196  int (*status)(int,int*,int*,int);
91197  int (*backup_finish)(sqlite3_backup*);
91198  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
91199  int (*backup_pagecount)(sqlite3_backup*);
91200  int (*backup_remaining)(sqlite3_backup*);
91201  int (*backup_step)(sqlite3_backup*,int);
91202  const char *(*compileoption_get)(int);
91203  int (*compileoption_used)(const char*);
91204  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
91205                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91206                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91207                            void (*xFinal)(sqlite3_context*),
91208                            void(*xDestroy)(void*));
91209  int (*db_config)(sqlite3*,int,...);
91210  sqlite3_mutex *(*db_mutex)(sqlite3*);
91211  int (*db_status)(sqlite3*,int,int*,int*,int);
91212  int (*extended_errcode)(sqlite3*);
91213  void (*log)(int,const char*,...);
91214  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
91215  const char *(*sourceid)(void);
91216  int (*stmt_status)(sqlite3_stmt*,int,int);
91217  int (*strnicmp)(const char*,const char*,int);
91218  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
91219  int (*wal_autocheckpoint)(sqlite3*,int);
91220  int (*wal_checkpoint)(sqlite3*,const char*);
91221  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
91222  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
91223  int (*vtab_config)(sqlite3*,int op,...);
91224  int (*vtab_on_conflict)(sqlite3*);
91225};
91226
91227/*
91228** The following macros redefine the API routines so that they are
91229** redirected throught the global sqlite3_api structure.
91230**
91231** This header file is also used by the loadext.c source file
91232** (part of the main SQLite library - not an extension) so that
91233** it can get access to the sqlite3_api_routines structure
91234** definition.  But the main library does not want to redefine
91235** the API.  So the redefinition macros are only valid if the
91236** SQLITE_CORE macros is undefined.
91237*/
91238#ifndef SQLITE_CORE
91239#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
91240#ifndef SQLITE_OMIT_DEPRECATED
91241#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
91242#endif
91243#define sqlite3_bind_blob              sqlite3_api->bind_blob
91244#define sqlite3_bind_double            sqlite3_api->bind_double
91245#define sqlite3_bind_int               sqlite3_api->bind_int
91246#define sqlite3_bind_int64             sqlite3_api->bind_int64
91247#define sqlite3_bind_null              sqlite3_api->bind_null
91248#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
91249#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
91250#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
91251#define sqlite3_bind_text              sqlite3_api->bind_text
91252#define sqlite3_bind_text16            sqlite3_api->bind_text16
91253#define sqlite3_bind_value             sqlite3_api->bind_value
91254#define sqlite3_busy_handler           sqlite3_api->busy_handler
91255#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
91256#define sqlite3_changes                sqlite3_api->changes
91257#define sqlite3_close                  sqlite3_api->close
91258#define sqlite3_collation_needed       sqlite3_api->collation_needed
91259#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
91260#define sqlite3_column_blob            sqlite3_api->column_blob
91261#define sqlite3_column_bytes           sqlite3_api->column_bytes
91262#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
91263#define sqlite3_column_count           sqlite3_api->column_count
91264#define sqlite3_column_database_name   sqlite3_api->column_database_name
91265#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
91266#define sqlite3_column_decltype        sqlite3_api->column_decltype
91267#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
91268#define sqlite3_column_double          sqlite3_api->column_double
91269#define sqlite3_column_int             sqlite3_api->column_int
91270#define sqlite3_column_int64           sqlite3_api->column_int64
91271#define sqlite3_column_name            sqlite3_api->column_name
91272#define sqlite3_column_name16          sqlite3_api->column_name16
91273#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
91274#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
91275#define sqlite3_column_table_name      sqlite3_api->column_table_name
91276#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
91277#define sqlite3_column_text            sqlite3_api->column_text
91278#define sqlite3_column_text16          sqlite3_api->column_text16
91279#define sqlite3_column_type            sqlite3_api->column_type
91280#define sqlite3_column_value           sqlite3_api->column_value
91281#define sqlite3_commit_hook            sqlite3_api->commit_hook
91282#define sqlite3_complete               sqlite3_api->complete
91283#define sqlite3_complete16             sqlite3_api->complete16
91284#define sqlite3_create_collation       sqlite3_api->create_collation
91285#define sqlite3_create_collation16     sqlite3_api->create_collation16
91286#define sqlite3_create_function        sqlite3_api->create_function
91287#define sqlite3_create_function16      sqlite3_api->create_function16
91288#define sqlite3_create_module          sqlite3_api->create_module
91289#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
91290#define sqlite3_data_count             sqlite3_api->data_count
91291#define sqlite3_db_handle              sqlite3_api->db_handle
91292#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
91293#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
91294#define sqlite3_errcode                sqlite3_api->errcode
91295#define sqlite3_errmsg                 sqlite3_api->errmsg
91296#define sqlite3_errmsg16               sqlite3_api->errmsg16
91297#define sqlite3_exec                   sqlite3_api->exec
91298#ifndef SQLITE_OMIT_DEPRECATED
91299#define sqlite3_expired                sqlite3_api->expired
91300#endif
91301#define sqlite3_finalize               sqlite3_api->finalize
91302#define sqlite3_free                   sqlite3_api->free
91303#define sqlite3_free_table             sqlite3_api->free_table
91304#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
91305#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
91306#define sqlite3_get_table              sqlite3_api->get_table
91307#ifndef SQLITE_OMIT_DEPRECATED
91308#define sqlite3_global_recover         sqlite3_api->global_recover
91309#endif
91310#define sqlite3_interrupt              sqlite3_api->interruptx
91311#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
91312#define sqlite3_libversion             sqlite3_api->libversion
91313#define sqlite3_libversion_number      sqlite3_api->libversion_number
91314#define sqlite3_malloc                 sqlite3_api->malloc
91315#define sqlite3_mprintf                sqlite3_api->mprintf
91316#define sqlite3_open                   sqlite3_api->open
91317#define sqlite3_open16                 sqlite3_api->open16
91318#define sqlite3_prepare                sqlite3_api->prepare
91319#define sqlite3_prepare16              sqlite3_api->prepare16
91320#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
91321#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
91322#define sqlite3_profile                sqlite3_api->profile
91323#define sqlite3_progress_handler       sqlite3_api->progress_handler
91324#define sqlite3_realloc                sqlite3_api->realloc
91325#define sqlite3_reset                  sqlite3_api->reset
91326#define sqlite3_result_blob            sqlite3_api->result_blob
91327#define sqlite3_result_double          sqlite3_api->result_double
91328#define sqlite3_result_error           sqlite3_api->result_error
91329#define sqlite3_result_error16         sqlite3_api->result_error16
91330#define sqlite3_result_int             sqlite3_api->result_int
91331#define sqlite3_result_int64           sqlite3_api->result_int64
91332#define sqlite3_result_null            sqlite3_api->result_null
91333#define sqlite3_result_text            sqlite3_api->result_text
91334#define sqlite3_result_text16          sqlite3_api->result_text16
91335#define sqlite3_result_text16be        sqlite3_api->result_text16be
91336#define sqlite3_result_text16le        sqlite3_api->result_text16le
91337#define sqlite3_result_value           sqlite3_api->result_value
91338#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
91339#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
91340#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
91341#define sqlite3_snprintf               sqlite3_api->snprintf
91342#define sqlite3_step                   sqlite3_api->step
91343#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
91344#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
91345#define sqlite3_total_changes          sqlite3_api->total_changes
91346#define sqlite3_trace                  sqlite3_api->trace
91347#ifndef SQLITE_OMIT_DEPRECATED
91348#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
91349#endif
91350#define sqlite3_update_hook            sqlite3_api->update_hook
91351#define sqlite3_user_data              sqlite3_api->user_data
91352#define sqlite3_value_blob             sqlite3_api->value_blob
91353#define sqlite3_value_bytes            sqlite3_api->value_bytes
91354#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
91355#define sqlite3_value_double           sqlite3_api->value_double
91356#define sqlite3_value_int              sqlite3_api->value_int
91357#define sqlite3_value_int64            sqlite3_api->value_int64
91358#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
91359#define sqlite3_value_text             sqlite3_api->value_text
91360#define sqlite3_value_text16           sqlite3_api->value_text16
91361#define sqlite3_value_text16be         sqlite3_api->value_text16be
91362#define sqlite3_value_text16le         sqlite3_api->value_text16le
91363#define sqlite3_value_type             sqlite3_api->value_type
91364#define sqlite3_vmprintf               sqlite3_api->vmprintf
91365#define sqlite3_overload_function      sqlite3_api->overload_function
91366#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
91367#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
91368#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
91369#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
91370#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
91371#define sqlite3_blob_close             sqlite3_api->blob_close
91372#define sqlite3_blob_open              sqlite3_api->blob_open
91373#define sqlite3_blob_read              sqlite3_api->blob_read
91374#define sqlite3_blob_write             sqlite3_api->blob_write
91375#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
91376#define sqlite3_file_control           sqlite3_api->file_control
91377#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
91378#define sqlite3_memory_used            sqlite3_api->memory_used
91379#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
91380#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
91381#define sqlite3_mutex_free             sqlite3_api->mutex_free
91382#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
91383#define sqlite3_mutex_try              sqlite3_api->mutex_try
91384#define sqlite3_open_v2                sqlite3_api->open_v2
91385#define sqlite3_release_memory         sqlite3_api->release_memory
91386#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
91387#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
91388#define sqlite3_sleep                  sqlite3_api->sleep
91389#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
91390#define sqlite3_vfs_find               sqlite3_api->vfs_find
91391#define sqlite3_vfs_register           sqlite3_api->vfs_register
91392#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
91393#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
91394#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
91395#define sqlite3_result_error_code      sqlite3_api->result_error_code
91396#define sqlite3_test_control           sqlite3_api->test_control
91397#define sqlite3_randomness             sqlite3_api->randomness
91398#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
91399#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
91400#define sqlite3_limit                  sqlite3_api->limit
91401#define sqlite3_next_stmt              sqlite3_api->next_stmt
91402#define sqlite3_sql                    sqlite3_api->sql
91403#define sqlite3_status                 sqlite3_api->status
91404#define sqlite3_backup_finish          sqlite3_api->backup_finish
91405#define sqlite3_backup_init            sqlite3_api->backup_init
91406#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
91407#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
91408#define sqlite3_backup_step            sqlite3_api->backup_step
91409#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
91410#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
91411#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
91412#define sqlite3_db_config              sqlite3_api->db_config
91413#define sqlite3_db_mutex               sqlite3_api->db_mutex
91414#define sqlite3_db_status              sqlite3_api->db_status
91415#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
91416#define sqlite3_log                    sqlite3_api->log
91417#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
91418#define sqlite3_sourceid               sqlite3_api->sourceid
91419#define sqlite3_stmt_status            sqlite3_api->stmt_status
91420#define sqlite3_strnicmp               sqlite3_api->strnicmp
91421#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
91422#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
91423#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
91424#define sqlite3_wal_hook               sqlite3_api->wal_hook
91425#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
91426#define sqlite3_vtab_config            sqlite3_api->vtab_config
91427#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
91428#endif /* SQLITE_CORE */
91429
91430#define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
91431#define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
91432
91433#endif /* _SQLITE3EXT_H_ */
91434
91435/************** End of sqlite3ext.h ******************************************/
91436/************** Continuing where we left off in loadext.c ********************/
91437/* #include <string.h> */
91438
91439#ifndef SQLITE_OMIT_LOAD_EXTENSION
91440
91441/*
91442** Some API routines are omitted when various features are
91443** excluded from a build of SQLite.  Substitute a NULL pointer
91444** for any missing APIs.
91445*/
91446#ifndef SQLITE_ENABLE_COLUMN_METADATA
91447# define sqlite3_column_database_name   0
91448# define sqlite3_column_database_name16 0
91449# define sqlite3_column_table_name      0
91450# define sqlite3_column_table_name16    0
91451# define sqlite3_column_origin_name     0
91452# define sqlite3_column_origin_name16   0
91453# define sqlite3_table_column_metadata  0
91454#endif
91455
91456#ifdef SQLITE_OMIT_AUTHORIZATION
91457# define sqlite3_set_authorizer         0
91458#endif
91459
91460#ifdef SQLITE_OMIT_UTF16
91461# define sqlite3_bind_text16            0
91462# define sqlite3_collation_needed16     0
91463# define sqlite3_column_decltype16      0
91464# define sqlite3_column_name16          0
91465# define sqlite3_column_text16          0
91466# define sqlite3_complete16             0
91467# define sqlite3_create_collation16     0
91468# define sqlite3_create_function16      0
91469# define sqlite3_errmsg16               0
91470# define sqlite3_open16                 0
91471# define sqlite3_prepare16              0
91472# define sqlite3_prepare16_v2           0
91473# define sqlite3_result_error16         0
91474# define sqlite3_result_text16          0
91475# define sqlite3_result_text16be        0
91476# define sqlite3_result_text16le        0
91477# define sqlite3_value_text16           0
91478# define sqlite3_value_text16be         0
91479# define sqlite3_value_text16le         0
91480# define sqlite3_column_database_name16 0
91481# define sqlite3_column_table_name16    0
91482# define sqlite3_column_origin_name16   0
91483#endif
91484
91485#ifdef SQLITE_OMIT_COMPLETE
91486# define sqlite3_complete 0
91487# define sqlite3_complete16 0
91488#endif
91489
91490#ifdef SQLITE_OMIT_DECLTYPE
91491# define sqlite3_column_decltype16      0
91492# define sqlite3_column_decltype        0
91493#endif
91494
91495#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
91496# define sqlite3_progress_handler 0
91497#endif
91498
91499#ifdef SQLITE_OMIT_VIRTUALTABLE
91500# define sqlite3_create_module 0
91501# define sqlite3_create_module_v2 0
91502# define sqlite3_declare_vtab 0
91503# define sqlite3_vtab_config 0
91504# define sqlite3_vtab_on_conflict 0
91505#endif
91506
91507#ifdef SQLITE_OMIT_SHARED_CACHE
91508# define sqlite3_enable_shared_cache 0
91509#endif
91510
91511#ifdef SQLITE_OMIT_TRACE
91512# define sqlite3_profile       0
91513# define sqlite3_trace         0
91514#endif
91515
91516#ifdef SQLITE_OMIT_GET_TABLE
91517# define sqlite3_free_table    0
91518# define sqlite3_get_table     0
91519#endif
91520
91521#ifdef SQLITE_OMIT_INCRBLOB
91522#define sqlite3_bind_zeroblob  0
91523#define sqlite3_blob_bytes     0
91524#define sqlite3_blob_close     0
91525#define sqlite3_blob_open      0
91526#define sqlite3_blob_read      0
91527#define sqlite3_blob_write     0
91528#define sqlite3_blob_reopen    0
91529#endif
91530
91531/*
91532** The following structure contains pointers to all SQLite API routines.
91533** A pointer to this structure is passed into extensions when they are
91534** loaded so that the extension can make calls back into the SQLite
91535** library.
91536**
91537** When adding new APIs, add them to the bottom of this structure
91538** in order to preserve backwards compatibility.
91539**
91540** Extensions that use newer APIs should first call the
91541** sqlite3_libversion_number() to make sure that the API they
91542** intend to use is supported by the library.  Extensions should
91543** also check to make sure that the pointer to the function is
91544** not NULL before calling it.
91545*/
91546static const sqlite3_api_routines sqlite3Apis = {
91547  sqlite3_aggregate_context,
91548#ifndef SQLITE_OMIT_DEPRECATED
91549  sqlite3_aggregate_count,
91550#else
91551  0,
91552#endif
91553  sqlite3_bind_blob,
91554  sqlite3_bind_double,
91555  sqlite3_bind_int,
91556  sqlite3_bind_int64,
91557  sqlite3_bind_null,
91558  sqlite3_bind_parameter_count,
91559  sqlite3_bind_parameter_index,
91560  sqlite3_bind_parameter_name,
91561  sqlite3_bind_text,
91562  sqlite3_bind_text16,
91563  sqlite3_bind_value,
91564  sqlite3_busy_handler,
91565  sqlite3_busy_timeout,
91566  sqlite3_changes,
91567  sqlite3_close,
91568  sqlite3_collation_needed,
91569  sqlite3_collation_needed16,
91570  sqlite3_column_blob,
91571  sqlite3_column_bytes,
91572  sqlite3_column_bytes16,
91573  sqlite3_column_count,
91574  sqlite3_column_database_name,
91575  sqlite3_column_database_name16,
91576  sqlite3_column_decltype,
91577  sqlite3_column_decltype16,
91578  sqlite3_column_double,
91579  sqlite3_column_int,
91580  sqlite3_column_int64,
91581  sqlite3_column_name,
91582  sqlite3_column_name16,
91583  sqlite3_column_origin_name,
91584  sqlite3_column_origin_name16,
91585  sqlite3_column_table_name,
91586  sqlite3_column_table_name16,
91587  sqlite3_column_text,
91588  sqlite3_column_text16,
91589  sqlite3_column_type,
91590  sqlite3_column_value,
91591  sqlite3_commit_hook,
91592  sqlite3_complete,
91593  sqlite3_complete16,
91594  sqlite3_create_collation,
91595  sqlite3_create_collation16,
91596  sqlite3_create_function,
91597  sqlite3_create_function16,
91598  sqlite3_create_module,
91599  sqlite3_data_count,
91600  sqlite3_db_handle,
91601  sqlite3_declare_vtab,
91602  sqlite3_enable_shared_cache,
91603  sqlite3_errcode,
91604  sqlite3_errmsg,
91605  sqlite3_errmsg16,
91606  sqlite3_exec,
91607#ifndef SQLITE_OMIT_DEPRECATED
91608  sqlite3_expired,
91609#else
91610  0,
91611#endif
91612  sqlite3_finalize,
91613  sqlite3_free,
91614  sqlite3_free_table,
91615  sqlite3_get_autocommit,
91616  sqlite3_get_auxdata,
91617  sqlite3_get_table,
91618  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
91619  sqlite3_interrupt,
91620  sqlite3_last_insert_rowid,
91621  sqlite3_libversion,
91622  sqlite3_libversion_number,
91623  sqlite3_malloc,
91624  sqlite3_mprintf,
91625  sqlite3_open,
91626  sqlite3_open16,
91627  sqlite3_prepare,
91628  sqlite3_prepare16,
91629  sqlite3_profile,
91630  sqlite3_progress_handler,
91631  sqlite3_realloc,
91632  sqlite3_reset,
91633  sqlite3_result_blob,
91634  sqlite3_result_double,
91635  sqlite3_result_error,
91636  sqlite3_result_error16,
91637  sqlite3_result_int,
91638  sqlite3_result_int64,
91639  sqlite3_result_null,
91640  sqlite3_result_text,
91641  sqlite3_result_text16,
91642  sqlite3_result_text16be,
91643  sqlite3_result_text16le,
91644  sqlite3_result_value,
91645  sqlite3_rollback_hook,
91646  sqlite3_set_authorizer,
91647  sqlite3_set_auxdata,
91648  sqlite3_snprintf,
91649  sqlite3_step,
91650  sqlite3_table_column_metadata,
91651#ifndef SQLITE_OMIT_DEPRECATED
91652  sqlite3_thread_cleanup,
91653#else
91654  0,
91655#endif
91656  sqlite3_total_changes,
91657  sqlite3_trace,
91658#ifndef SQLITE_OMIT_DEPRECATED
91659  sqlite3_transfer_bindings,
91660#else
91661  0,
91662#endif
91663  sqlite3_update_hook,
91664  sqlite3_user_data,
91665  sqlite3_value_blob,
91666  sqlite3_value_bytes,
91667  sqlite3_value_bytes16,
91668  sqlite3_value_double,
91669  sqlite3_value_int,
91670  sqlite3_value_int64,
91671  sqlite3_value_numeric_type,
91672  sqlite3_value_text,
91673  sqlite3_value_text16,
91674  sqlite3_value_text16be,
91675  sqlite3_value_text16le,
91676  sqlite3_value_type,
91677  sqlite3_vmprintf,
91678  /*
91679  ** The original API set ends here.  All extensions can call any
91680  ** of the APIs above provided that the pointer is not NULL.  But
91681  ** before calling APIs that follow, extension should check the
91682  ** sqlite3_libversion_number() to make sure they are dealing with
91683  ** a library that is new enough to support that API.
91684  *************************************************************************
91685  */
91686  sqlite3_overload_function,
91687
91688  /*
91689  ** Added after 3.3.13
91690  */
91691  sqlite3_prepare_v2,
91692  sqlite3_prepare16_v2,
91693  sqlite3_clear_bindings,
91694
91695  /*
91696  ** Added for 3.4.1
91697  */
91698  sqlite3_create_module_v2,
91699
91700  /*
91701  ** Added for 3.5.0
91702  */
91703  sqlite3_bind_zeroblob,
91704  sqlite3_blob_bytes,
91705  sqlite3_blob_close,
91706  sqlite3_blob_open,
91707  sqlite3_blob_read,
91708  sqlite3_blob_write,
91709  sqlite3_create_collation_v2,
91710  sqlite3_file_control,
91711  sqlite3_memory_highwater,
91712  sqlite3_memory_used,
91713#ifdef SQLITE_MUTEX_OMIT
91714  0,
91715  0,
91716  0,
91717  0,
91718  0,
91719#else
91720  sqlite3_mutex_alloc,
91721  sqlite3_mutex_enter,
91722  sqlite3_mutex_free,
91723  sqlite3_mutex_leave,
91724  sqlite3_mutex_try,
91725#endif
91726  sqlite3_open_v2,
91727  sqlite3_release_memory,
91728  sqlite3_result_error_nomem,
91729  sqlite3_result_error_toobig,
91730  sqlite3_sleep,
91731  sqlite3_soft_heap_limit,
91732  sqlite3_vfs_find,
91733  sqlite3_vfs_register,
91734  sqlite3_vfs_unregister,
91735
91736  /*
91737  ** Added for 3.5.8
91738  */
91739  sqlite3_threadsafe,
91740  sqlite3_result_zeroblob,
91741  sqlite3_result_error_code,
91742  sqlite3_test_control,
91743  sqlite3_randomness,
91744  sqlite3_context_db_handle,
91745
91746  /*
91747  ** Added for 3.6.0
91748  */
91749  sqlite3_extended_result_codes,
91750  sqlite3_limit,
91751  sqlite3_next_stmt,
91752  sqlite3_sql,
91753  sqlite3_status,
91754
91755  /*
91756  ** Added for 3.7.4
91757  */
91758  sqlite3_backup_finish,
91759  sqlite3_backup_init,
91760  sqlite3_backup_pagecount,
91761  sqlite3_backup_remaining,
91762  sqlite3_backup_step,
91763#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
91764  sqlite3_compileoption_get,
91765  sqlite3_compileoption_used,
91766#else
91767  0,
91768  0,
91769#endif
91770  sqlite3_create_function_v2,
91771  sqlite3_db_config,
91772  sqlite3_db_mutex,
91773  sqlite3_db_status,
91774  sqlite3_extended_errcode,
91775  sqlite3_log,
91776  sqlite3_soft_heap_limit64,
91777  sqlite3_sourceid,
91778  sqlite3_stmt_status,
91779  sqlite3_strnicmp,
91780#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
91781  sqlite3_unlock_notify,
91782#else
91783  0,
91784#endif
91785#ifndef SQLITE_OMIT_WAL
91786  sqlite3_wal_autocheckpoint,
91787  sqlite3_wal_checkpoint,
91788  sqlite3_wal_hook,
91789#else
91790  0,
91791  0,
91792  0,
91793#endif
91794  sqlite3_blob_reopen,
91795  sqlite3_vtab_config,
91796  sqlite3_vtab_on_conflict,
91797};
91798
91799/*
91800** Attempt to load an SQLite extension library contained in the file
91801** zFile.  The entry point is zProc.  zProc may be 0 in which case a
91802** default entry point name (sqlite3_extension_init) is used.  Use
91803** of the default name is recommended.
91804**
91805** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
91806**
91807** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
91808** error message text.  The calling function should free this memory
91809** by calling sqlite3DbFree(db, ).
91810*/
91811static int sqlite3LoadExtension(
91812  sqlite3 *db,          /* Load the extension into this database connection */
91813  const char *zFile,    /* Name of the shared library containing extension */
91814  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
91815  char **pzErrMsg       /* Put error message here if not 0 */
91816){
91817  sqlite3_vfs *pVfs = db->pVfs;
91818  void *handle;
91819  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
91820  char *zErrmsg = 0;
91821  void **aHandle;
91822  int nMsg = 300 + sqlite3Strlen30(zFile);
91823
91824  if( pzErrMsg ) *pzErrMsg = 0;
91825
91826  /* Ticket #1863.  To avoid a creating security problems for older
91827  ** applications that relink against newer versions of SQLite, the
91828  ** ability to run load_extension is turned off by default.  One
91829  ** must call sqlite3_enable_load_extension() to turn on extension
91830  ** loading.  Otherwise you get the following error.
91831  */
91832  if( (db->flags & SQLITE_LoadExtension)==0 ){
91833    if( pzErrMsg ){
91834      *pzErrMsg = sqlite3_mprintf("not authorized");
91835    }
91836    return SQLITE_ERROR;
91837  }
91838
91839  if( zProc==0 ){
91840    zProc = "sqlite3_extension_init";
91841  }
91842
91843  handle = sqlite3OsDlOpen(pVfs, zFile);
91844  if( handle==0 ){
91845    if( pzErrMsg ){
91846      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
91847      if( zErrmsg ){
91848        sqlite3_snprintf(nMsg, zErrmsg,
91849            "unable to open shared library [%s]", zFile);
91850        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
91851      }
91852    }
91853    return SQLITE_ERROR;
91854  }
91855  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
91856                   sqlite3OsDlSym(pVfs, handle, zProc);
91857  if( xInit==0 ){
91858    if( pzErrMsg ){
91859      nMsg += sqlite3Strlen30(zProc);
91860      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
91861      if( zErrmsg ){
91862        sqlite3_snprintf(nMsg, zErrmsg,
91863            "no entry point [%s] in shared library [%s]", zProc,zFile);
91864        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
91865      }
91866      sqlite3OsDlClose(pVfs, handle);
91867    }
91868    return SQLITE_ERROR;
91869  }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
91870    if( pzErrMsg ){
91871      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
91872    }
91873    sqlite3_free(zErrmsg);
91874    sqlite3OsDlClose(pVfs, handle);
91875    return SQLITE_ERROR;
91876  }
91877
91878  /* Append the new shared library handle to the db->aExtension array. */
91879  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
91880  if( aHandle==0 ){
91881    return SQLITE_NOMEM;
91882  }
91883  if( db->nExtension>0 ){
91884    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
91885  }
91886  sqlite3DbFree(db, db->aExtension);
91887  db->aExtension = aHandle;
91888
91889  db->aExtension[db->nExtension++] = handle;
91890  return SQLITE_OK;
91891}
91892SQLITE_API int sqlite3_load_extension(
91893  sqlite3 *db,          /* Load the extension into this database connection */
91894  const char *zFile,    /* Name of the shared library containing extension */
91895  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
91896  char **pzErrMsg       /* Put error message here if not 0 */
91897){
91898  int rc;
91899  sqlite3_mutex_enter(db->mutex);
91900  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
91901  rc = sqlite3ApiExit(db, rc);
91902  sqlite3_mutex_leave(db->mutex);
91903  return rc;
91904}
91905
91906/*
91907** Call this routine when the database connection is closing in order
91908** to clean up loaded extensions
91909*/
91910SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
91911  int i;
91912  assert( sqlite3_mutex_held(db->mutex) );
91913  for(i=0; i<db->nExtension; i++){
91914    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
91915  }
91916  sqlite3DbFree(db, db->aExtension);
91917}
91918
91919/*
91920** Enable or disable extension loading.  Extension loading is disabled by
91921** default so as not to open security holes in older applications.
91922*/
91923SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
91924  sqlite3_mutex_enter(db->mutex);
91925  if( onoff ){
91926    db->flags |= SQLITE_LoadExtension;
91927  }else{
91928    db->flags &= ~SQLITE_LoadExtension;
91929  }
91930  sqlite3_mutex_leave(db->mutex);
91931  return SQLITE_OK;
91932}
91933
91934#endif /* SQLITE_OMIT_LOAD_EXTENSION */
91935
91936/*
91937** The auto-extension code added regardless of whether or not extension
91938** loading is supported.  We need a dummy sqlite3Apis pointer for that
91939** code if regular extension loading is not available.  This is that
91940** dummy pointer.
91941*/
91942#ifdef SQLITE_OMIT_LOAD_EXTENSION
91943static const sqlite3_api_routines sqlite3Apis = { 0 };
91944#endif
91945
91946
91947/*
91948** The following object holds the list of automatically loaded
91949** extensions.
91950**
91951** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
91952** mutex must be held while accessing this list.
91953*/
91954typedef struct sqlite3AutoExtList sqlite3AutoExtList;
91955static SQLITE_WSD struct sqlite3AutoExtList {
91956  int nExt;              /* Number of entries in aExt[] */
91957  void (**aExt)(void);   /* Pointers to the extension init functions */
91958} sqlite3Autoext = { 0, 0 };
91959
91960/* The "wsdAutoext" macro will resolve to the autoextension
91961** state vector.  If writable static data is unsupported on the target,
91962** we have to locate the state vector at run-time.  In the more common
91963** case where writable static data is supported, wsdStat can refer directly
91964** to the "sqlite3Autoext" state vector declared above.
91965*/
91966#ifdef SQLITE_OMIT_WSD
91967# define wsdAutoextInit \
91968  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
91969# define wsdAutoext x[0]
91970#else
91971# define wsdAutoextInit
91972# define wsdAutoext sqlite3Autoext
91973#endif
91974
91975
91976/*
91977** Register a statically linked extension that is automatically
91978** loaded by every new database connection.
91979*/
91980SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
91981  int rc = SQLITE_OK;
91982#ifndef SQLITE_OMIT_AUTOINIT
91983  rc = sqlite3_initialize();
91984  if( rc ){
91985    return rc;
91986  }else
91987#endif
91988  {
91989    int i;
91990#if SQLITE_THREADSAFE
91991    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
91992#endif
91993    wsdAutoextInit;
91994    sqlite3_mutex_enter(mutex);
91995    for(i=0; i<wsdAutoext.nExt; i++){
91996      if( wsdAutoext.aExt[i]==xInit ) break;
91997    }
91998    if( i==wsdAutoext.nExt ){
91999      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
92000      void (**aNew)(void);
92001      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
92002      if( aNew==0 ){
92003        rc = SQLITE_NOMEM;
92004      }else{
92005        wsdAutoext.aExt = aNew;
92006        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
92007        wsdAutoext.nExt++;
92008      }
92009    }
92010    sqlite3_mutex_leave(mutex);
92011    assert( (rc&0xff)==rc );
92012    return rc;
92013  }
92014}
92015
92016/*
92017** Reset the automatic extension loading mechanism.
92018*/
92019SQLITE_API void sqlite3_reset_auto_extension(void){
92020#ifndef SQLITE_OMIT_AUTOINIT
92021  if( sqlite3_initialize()==SQLITE_OK )
92022#endif
92023  {
92024#if SQLITE_THREADSAFE
92025    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
92026#endif
92027    wsdAutoextInit;
92028    sqlite3_mutex_enter(mutex);
92029    sqlite3_free(wsdAutoext.aExt);
92030    wsdAutoext.aExt = 0;
92031    wsdAutoext.nExt = 0;
92032    sqlite3_mutex_leave(mutex);
92033  }
92034}
92035
92036/*
92037** Load all automatic extensions.
92038**
92039** If anything goes wrong, set an error in the database connection.
92040*/
92041SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
92042  int i;
92043  int go = 1;
92044  int rc;
92045  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
92046
92047  wsdAutoextInit;
92048  if( wsdAutoext.nExt==0 ){
92049    /* Common case: early out without every having to acquire a mutex */
92050    return;
92051  }
92052  for(i=0; go; i++){
92053    char *zErrmsg;
92054#if SQLITE_THREADSAFE
92055    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
92056#endif
92057    sqlite3_mutex_enter(mutex);
92058    if( i>=wsdAutoext.nExt ){
92059      xInit = 0;
92060      go = 0;
92061    }else{
92062      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
92063              wsdAutoext.aExt[i];
92064    }
92065    sqlite3_mutex_leave(mutex);
92066    zErrmsg = 0;
92067    if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
92068      sqlite3Error(db, rc,
92069            "automatic extension loading failed: %s", zErrmsg);
92070      go = 0;
92071    }
92072    sqlite3_free(zErrmsg);
92073  }
92074}
92075
92076/************** End of loadext.c *********************************************/
92077/************** Begin file pragma.c ******************************************/
92078/*
92079** 2003 April 6
92080**
92081** The author disclaims copyright to this source code.  In place of
92082** a legal notice, here is a blessing:
92083**
92084**    May you do good and not evil.
92085**    May you find forgiveness for yourself and forgive others.
92086**    May you share freely, never taking more than you give.
92087**
92088*************************************************************************
92089** This file contains code used to implement the PRAGMA command.
92090*/
92091
92092/*
92093** Interpret the given string as a safety level.  Return 0 for OFF,
92094** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
92095** unrecognized string argument.  The FULL option is disallowed
92096** if the omitFull parameter it 1.
92097**
92098** Note that the values returned are one less that the values that
92099** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
92100** to support legacy SQL code.  The safety level used to be boolean
92101** and older scripts may have used numbers 0 for OFF and 1 for ON.
92102*/
92103static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
92104                             /* 123456789 123456789 */
92105  static const char zText[] = "onoffalseyestruefull";
92106  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
92107  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
92108  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
92109  int i, n;
92110  if( sqlite3Isdigit(*z) ){
92111    return (u8)sqlite3Atoi(z);
92112  }
92113  n = sqlite3Strlen30(z);
92114  for(i=0; i<ArraySize(iLength)-omitFull; i++){
92115    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
92116      return iValue[i];
92117    }
92118  }
92119  return dflt;
92120}
92121
92122/*
92123** Interpret the given string as a boolean value.
92124*/
92125SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
92126  return getSafetyLevel(z,1,dflt)!=0;
92127}
92128
92129/* The sqlite3GetBoolean() function is used by other modules but the
92130** remainder of this file is specific to PRAGMA processing.  So omit
92131** the rest of the file if PRAGMAs are omitted from the build.
92132*/
92133#if !defined(SQLITE_OMIT_PRAGMA)
92134
92135/*
92136** Interpret the given string as a locking mode value.
92137*/
92138static int getLockingMode(const char *z){
92139  if( z ){
92140    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
92141    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
92142  }
92143  return PAGER_LOCKINGMODE_QUERY;
92144}
92145
92146#ifndef SQLITE_OMIT_AUTOVACUUM
92147/*
92148** Interpret the given string as an auto-vacuum mode value.
92149**
92150** The following strings, "none", "full" and "incremental" are
92151** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
92152*/
92153static int getAutoVacuum(const char *z){
92154  int i;
92155  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
92156  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
92157  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
92158  i = sqlite3Atoi(z);
92159  return (u8)((i>=0&&i<=2)?i:0);
92160}
92161#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
92162
92163#ifndef SQLITE_OMIT_PAGER_PRAGMAS
92164/*
92165** Interpret the given string as a temp db location. Return 1 for file
92166** backed temporary databases, 2 for the Red-Black tree in memory database
92167** and 0 to use the compile-time default.
92168*/
92169static int getTempStore(const char *z){
92170  if( z[0]>='0' && z[0]<='2' ){
92171    return z[0] - '0';
92172  }else if( sqlite3StrICmp(z, "file")==0 ){
92173    return 1;
92174  }else if( sqlite3StrICmp(z, "memory")==0 ){
92175    return 2;
92176  }else{
92177    return 0;
92178  }
92179}
92180#endif /* SQLITE_PAGER_PRAGMAS */
92181
92182#ifndef SQLITE_OMIT_PAGER_PRAGMAS
92183/*
92184** Invalidate temp storage, either when the temp storage is changed
92185** from default, or when 'file' and the temp_store_directory has changed
92186*/
92187static int invalidateTempStorage(Parse *pParse){
92188  sqlite3 *db = pParse->db;
92189  if( db->aDb[1].pBt!=0 ){
92190    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
92191      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
92192        "from within a transaction");
92193      return SQLITE_ERROR;
92194    }
92195    sqlite3BtreeClose(db->aDb[1].pBt);
92196    db->aDb[1].pBt = 0;
92197    sqlite3ResetInternalSchema(db, -1);
92198  }
92199  return SQLITE_OK;
92200}
92201#endif /* SQLITE_PAGER_PRAGMAS */
92202
92203#ifndef SQLITE_OMIT_PAGER_PRAGMAS
92204/*
92205** If the TEMP database is open, close it and mark the database schema
92206** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
92207** or DEFAULT_TEMP_STORE pragmas.
92208*/
92209static int changeTempStorage(Parse *pParse, const char *zStorageType){
92210  int ts = getTempStore(zStorageType);
92211  sqlite3 *db = pParse->db;
92212  if( db->temp_store==ts ) return SQLITE_OK;
92213  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
92214    return SQLITE_ERROR;
92215  }
92216  db->temp_store = (u8)ts;
92217  return SQLITE_OK;
92218}
92219#endif /* SQLITE_PAGER_PRAGMAS */
92220
92221/*
92222** Generate code to return a single integer value.
92223*/
92224static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
92225  Vdbe *v = sqlite3GetVdbe(pParse);
92226  int mem = ++pParse->nMem;
92227  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
92228  if( pI64 ){
92229    memcpy(pI64, &value, sizeof(value));
92230  }
92231  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
92232  sqlite3VdbeSetNumCols(v, 1);
92233  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
92234  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
92235}
92236
92237#ifndef SQLITE_OMIT_FLAG_PRAGMAS
92238/*
92239** Check to see if zRight and zLeft refer to a pragma that queries
92240** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
92241** Also, implement the pragma.
92242*/
92243static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
92244  static const struct sPragmaType {
92245    const char *zName;  /* Name of the pragma */
92246    int mask;           /* Mask for the db->flags value */
92247  } aPragma[] = {
92248    { "full_column_names",        SQLITE_FullColNames  },
92249    { "short_column_names",       SQLITE_ShortColNames },
92250    { "count_changes",            SQLITE_CountRows     },
92251    { "empty_result_callbacks",   SQLITE_NullCallback  },
92252    { "legacy_file_format",       SQLITE_LegacyFileFmt },
92253    { "fullfsync",                SQLITE_FullFSync     },
92254    { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
92255    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
92256#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
92257    { "automatic_index",          SQLITE_AutoIndex     },
92258#endif
92259#ifdef SQLITE_DEBUG
92260    { "sql_trace",                SQLITE_SqlTrace      },
92261    { "vdbe_listing",             SQLITE_VdbeListing   },
92262    { "vdbe_trace",               SQLITE_VdbeTrace     },
92263#endif
92264#ifndef SQLITE_OMIT_CHECK
92265    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
92266#endif
92267    /* The following is VERY experimental */
92268    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
92269
92270    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
92271    ** flag if there are any active statements. */
92272    { "read_uncommitted",         SQLITE_ReadUncommitted },
92273    { "recursive_triggers",       SQLITE_RecTriggers },
92274
92275    /* This flag may only be set if both foreign-key and trigger support
92276    ** are present in the build.  */
92277#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
92278    { "foreign_keys",             SQLITE_ForeignKeys },
92279#endif
92280  };
92281  int i;
92282  const struct sPragmaType *p;
92283  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
92284    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
92285      sqlite3 *db = pParse->db;
92286      Vdbe *v;
92287      v = sqlite3GetVdbe(pParse);
92288      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
92289      if( ALWAYS(v) ){
92290        if( zRight==0 ){
92291          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
92292        }else{
92293          int mask = p->mask;          /* Mask of bits to set or clear. */
92294          if( db->autoCommit==0 ){
92295            /* Foreign key support may not be enabled or disabled while not
92296            ** in auto-commit mode.  */
92297            mask &= ~(SQLITE_ForeignKeys);
92298          }
92299
92300          if( sqlite3GetBoolean(zRight, 0) ){
92301            db->flags |= mask;
92302          }else{
92303            db->flags &= ~mask;
92304          }
92305
92306          /* Many of the flag-pragmas modify the code generated by the SQL
92307          ** compiler (eg. count_changes). So add an opcode to expire all
92308          ** compiled SQL statements after modifying a pragma value.
92309          */
92310          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
92311        }
92312      }
92313
92314      return 1;
92315    }
92316  }
92317  return 0;
92318}
92319#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
92320
92321/*
92322** Return a human-readable name for a constraint resolution action.
92323*/
92324#ifndef SQLITE_OMIT_FOREIGN_KEY
92325static const char *actionName(u8 action){
92326  const char *zName;
92327  switch( action ){
92328    case OE_SetNull:  zName = "SET NULL";        break;
92329    case OE_SetDflt:  zName = "SET DEFAULT";     break;
92330    case OE_Cascade:  zName = "CASCADE";         break;
92331    case OE_Restrict: zName = "RESTRICT";        break;
92332    default:          zName = "NO ACTION";
92333                      assert( action==OE_None ); break;
92334  }
92335  return zName;
92336}
92337#endif
92338
92339
92340/*
92341** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
92342** defined in pager.h. This function returns the associated lowercase
92343** journal-mode name.
92344*/
92345SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
92346  static char * const azModeName[] = {
92347    "delete", "persist", "off", "truncate", "memory"
92348#ifndef SQLITE_OMIT_WAL
92349     , "wal"
92350#endif
92351  };
92352  assert( PAGER_JOURNALMODE_DELETE==0 );
92353  assert( PAGER_JOURNALMODE_PERSIST==1 );
92354  assert( PAGER_JOURNALMODE_OFF==2 );
92355  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
92356  assert( PAGER_JOURNALMODE_MEMORY==4 );
92357  assert( PAGER_JOURNALMODE_WAL==5 );
92358  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
92359
92360  if( eMode==ArraySize(azModeName) ) return 0;
92361  return azModeName[eMode];
92362}
92363
92364/*
92365** Process a pragma statement.
92366**
92367** Pragmas are of this form:
92368**
92369**      PRAGMA [database.]id [= value]
92370**
92371** The identifier might also be a string.  The value is a string, and
92372** identifier, or a number.  If minusFlag is true, then the value is
92373** a number that was preceded by a minus sign.
92374**
92375** If the left side is "database.id" then pId1 is the database name
92376** and pId2 is the id.  If the left side is just "id" then pId1 is the
92377** id and pId2 is any empty string.
92378*/
92379SQLITE_PRIVATE void sqlite3Pragma(
92380  Parse *pParse,
92381  Token *pId1,        /* First part of [database.]id field */
92382  Token *pId2,        /* Second part of [database.]id field, or NULL */
92383  Token *pValue,      /* Token for <value>, or NULL */
92384  int minusFlag       /* True if a '-' sign preceded <value> */
92385){
92386  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
92387  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
92388  const char *zDb = 0;   /* The database name */
92389  Token *pId;            /* Pointer to <id> token */
92390  int iDb;               /* Database index for <database> */
92391  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
92392  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
92393  sqlite3 *db = pParse->db;    /* The database connection */
92394  Db *pDb;                     /* The specific database being pragmaed */
92395  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);  /* Prepared statement */
92396
92397  if( v==0 ) return;
92398  sqlite3VdbeRunOnlyOnce(v);
92399  pParse->nMem = 2;
92400
92401  /* Interpret the [database.] part of the pragma statement. iDb is the
92402  ** index of the database this pragma is being applied to in db.aDb[]. */
92403  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
92404  if( iDb<0 ) return;
92405  pDb = &db->aDb[iDb];
92406
92407  /* If the temp database has been explicitly named as part of the
92408  ** pragma, make sure it is open.
92409  */
92410  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
92411    return;
92412  }
92413
92414  zLeft = sqlite3NameFromToken(db, pId);
92415  if( !zLeft ) return;
92416  if( minusFlag ){
92417    zRight = sqlite3MPrintf(db, "-%T", pValue);
92418  }else{
92419    zRight = sqlite3NameFromToken(db, pValue);
92420  }
92421
92422  assert( pId2 );
92423  zDb = pId2->n>0 ? pDb->zName : 0;
92424  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
92425    goto pragma_out;
92426  }
92427
92428  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
92429  ** connection.  If it returns SQLITE_OK, then assume that the VFS
92430  ** handled the pragma and generate a no-op prepared statement.
92431  */
92432  aFcntl[0] = 0;
92433  aFcntl[1] = zLeft;
92434  aFcntl[2] = zRight;
92435  aFcntl[3] = 0;
92436  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
92437  if( rc==SQLITE_OK ){
92438    if( aFcntl[0] ){
92439      int mem = ++pParse->nMem;
92440      sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
92441      sqlite3VdbeSetNumCols(v, 1);
92442      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
92443      sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
92444      sqlite3_free(aFcntl[0]);
92445    }
92446  }else if( rc!=SQLITE_NOTFOUND ){
92447    if( aFcntl[0] ){
92448      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
92449      sqlite3_free(aFcntl[0]);
92450    }
92451    pParse->nErr++;
92452    pParse->rc = rc;
92453  }else
92454
92455
92456#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
92457  /*
92458  **  PRAGMA [database.]default_cache_size
92459  **  PRAGMA [database.]default_cache_size=N
92460  **
92461  ** The first form reports the current persistent setting for the
92462  ** page cache size.  The value returned is the maximum number of
92463  ** pages in the page cache.  The second form sets both the current
92464  ** page cache size value and the persistent page cache size value
92465  ** stored in the database file.
92466  **
92467  ** Older versions of SQLite would set the default cache size to a
92468  ** negative number to indicate synchronous=OFF.  These days, synchronous
92469  ** is always on by default regardless of the sign of the default cache
92470  ** size.  But continue to take the absolute value of the default cache
92471  ** size of historical compatibility.
92472  */
92473  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
92474    static const VdbeOpList getCacheSize[] = {
92475      { OP_Transaction, 0, 0,        0},                         /* 0 */
92476      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
92477      { OP_IfPos,       1, 7,        0},
92478      { OP_Integer,     0, 2,        0},
92479      { OP_Subtract,    1, 2,        1},
92480      { OP_IfPos,       1, 7,        0},
92481      { OP_Integer,     0, 1,        0},                         /* 6 */
92482      { OP_ResultRow,   1, 1,        0},
92483    };
92484    int addr;
92485    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92486    sqlite3VdbeUsesBtree(v, iDb);
92487    if( !zRight ){
92488      sqlite3VdbeSetNumCols(v, 1);
92489      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
92490      pParse->nMem += 2;
92491      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
92492      sqlite3VdbeChangeP1(v, addr, iDb);
92493      sqlite3VdbeChangeP1(v, addr+1, iDb);
92494      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
92495    }else{
92496      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
92497      sqlite3BeginWriteOperation(pParse, 0, iDb);
92498      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
92499      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
92500      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92501      pDb->pSchema->cache_size = size;
92502      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92503    }
92504  }else
92505#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
92506
92507#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
92508  /*
92509  **  PRAGMA [database.]page_size
92510  **  PRAGMA [database.]page_size=N
92511  **
92512  ** The first form reports the current setting for the
92513  ** database page size in bytes.  The second form sets the
92514  ** database page size value.  The value can only be set if
92515  ** the database has not yet been created.
92516  */
92517  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
92518    Btree *pBt = pDb->pBt;
92519    assert( pBt!=0 );
92520    if( !zRight ){
92521      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
92522      returnSingleInt(pParse, "page_size", size);
92523    }else{
92524      /* Malloc may fail when setting the page-size, as there is an internal
92525      ** buffer that the pager module resizes using sqlite3_realloc().
92526      */
92527      db->nextPagesize = sqlite3Atoi(zRight);
92528      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
92529        db->mallocFailed = 1;
92530      }
92531    }
92532  }else
92533
92534  /*
92535  **  PRAGMA [database.]secure_delete
92536  **  PRAGMA [database.]secure_delete=ON/OFF
92537  **
92538  ** The first form reports the current setting for the
92539  ** secure_delete flag.  The second form changes the secure_delete
92540  ** flag setting and reports thenew value.
92541  */
92542  if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
92543    Btree *pBt = pDb->pBt;
92544    int b = -1;
92545    assert( pBt!=0 );
92546    if( zRight ){
92547      b = sqlite3GetBoolean(zRight, 0);
92548    }
92549    if( pId2->n==0 && b>=0 ){
92550      int ii;
92551      for(ii=0; ii<db->nDb; ii++){
92552        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
92553      }
92554    }
92555    b = sqlite3BtreeSecureDelete(pBt, b);
92556    returnSingleInt(pParse, "secure_delete", b);
92557  }else
92558
92559  /*
92560  **  PRAGMA [database.]max_page_count
92561  **  PRAGMA [database.]max_page_count=N
92562  **
92563  ** The first form reports the current setting for the
92564  ** maximum number of pages in the database file.  The
92565  ** second form attempts to change this setting.  Both
92566  ** forms return the current setting.
92567  **
92568  ** The absolute value of N is used.  This is undocumented and might
92569  ** change.  The only purpose is to provide an easy way to test
92570  ** the sqlite3AbsInt32() function.
92571  **
92572  **  PRAGMA [database.]page_count
92573  **
92574  ** Return the number of pages in the specified database.
92575  */
92576  if( sqlite3StrICmp(zLeft,"page_count")==0
92577   || sqlite3StrICmp(zLeft,"max_page_count")==0
92578  ){
92579    int iReg;
92580    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92581    sqlite3CodeVerifySchema(pParse, iDb);
92582    iReg = ++pParse->nMem;
92583    if( sqlite3Tolower(zLeft[0])=='p' ){
92584      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
92585    }else{
92586      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
92587                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
92588    }
92589    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
92590    sqlite3VdbeSetNumCols(v, 1);
92591    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
92592  }else
92593
92594  /*
92595  **  PRAGMA [database.]locking_mode
92596  **  PRAGMA [database.]locking_mode = (normal|exclusive)
92597  */
92598  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
92599    const char *zRet = "normal";
92600    int eMode = getLockingMode(zRight);
92601
92602    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
92603      /* Simple "PRAGMA locking_mode;" statement. This is a query for
92604      ** the current default locking mode (which may be different to
92605      ** the locking-mode of the main database).
92606      */
92607      eMode = db->dfltLockMode;
92608    }else{
92609      Pager *pPager;
92610      if( pId2->n==0 ){
92611        /* This indicates that no database name was specified as part
92612        ** of the PRAGMA command. In this case the locking-mode must be
92613        ** set on all attached databases, as well as the main db file.
92614        **
92615        ** Also, the sqlite3.dfltLockMode variable is set so that
92616        ** any subsequently attached databases also use the specified
92617        ** locking mode.
92618        */
92619        int ii;
92620        assert(pDb==&db->aDb[0]);
92621        for(ii=2; ii<db->nDb; ii++){
92622          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
92623          sqlite3PagerLockingMode(pPager, eMode);
92624        }
92625        db->dfltLockMode = (u8)eMode;
92626      }
92627      pPager = sqlite3BtreePager(pDb->pBt);
92628      eMode = sqlite3PagerLockingMode(pPager, eMode);
92629    }
92630
92631    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
92632    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
92633      zRet = "exclusive";
92634    }
92635    sqlite3VdbeSetNumCols(v, 1);
92636    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
92637    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
92638    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92639  }else
92640
92641  /*
92642  **  PRAGMA [database.]journal_mode
92643  **  PRAGMA [database.]journal_mode =
92644  **                      (delete|persist|off|truncate|memory|wal|off)
92645  */
92646  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
92647    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
92648    int ii;           /* Loop counter */
92649
92650    /* Force the schema to be loaded on all databases.  This causes all
92651    ** database files to be opened and the journal_modes set.  This is
92652    ** necessary because subsequent processing must know if the databases
92653    ** are in WAL mode. */
92654    if( sqlite3ReadSchema(pParse) ){
92655      goto pragma_out;
92656    }
92657
92658    sqlite3VdbeSetNumCols(v, 1);
92659    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
92660
92661    if( zRight==0 ){
92662      /* If there is no "=MODE" part of the pragma, do a query for the
92663      ** current mode */
92664      eMode = PAGER_JOURNALMODE_QUERY;
92665    }else{
92666      const char *zMode;
92667      int n = sqlite3Strlen30(zRight);
92668      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
92669        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
92670      }
92671      if( !zMode ){
92672        /* If the "=MODE" part does not match any known journal mode,
92673        ** then do a query */
92674        eMode = PAGER_JOURNALMODE_QUERY;
92675      }
92676    }
92677    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
92678      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
92679      iDb = 0;
92680      pId2->n = 1;
92681    }
92682    for(ii=db->nDb-1; ii>=0; ii--){
92683      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
92684        sqlite3VdbeUsesBtree(v, ii);
92685        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
92686      }
92687    }
92688    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92689  }else
92690
92691  /*
92692  **  PRAGMA [database.]journal_size_limit
92693  **  PRAGMA [database.]journal_size_limit=N
92694  **
92695  ** Get or set the size limit on rollback journal files.
92696  */
92697  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
92698    Pager *pPager = sqlite3BtreePager(pDb->pBt);
92699    i64 iLimit = -2;
92700    if( zRight ){
92701      sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
92702      if( iLimit<-1 ) iLimit = -1;
92703    }
92704    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
92705    returnSingleInt(pParse, "journal_size_limit", iLimit);
92706  }else
92707
92708#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
92709
92710  /*
92711  **  PRAGMA [database.]auto_vacuum
92712  **  PRAGMA [database.]auto_vacuum=N
92713  **
92714  ** Get or set the value of the database 'auto-vacuum' parameter.
92715  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
92716  */
92717#ifndef SQLITE_OMIT_AUTOVACUUM
92718  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
92719    Btree *pBt = pDb->pBt;
92720    assert( pBt!=0 );
92721    if( sqlite3ReadSchema(pParse) ){
92722      goto pragma_out;
92723    }
92724    if( !zRight ){
92725      int auto_vacuum;
92726      if( ALWAYS(pBt) ){
92727         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
92728      }else{
92729         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
92730      }
92731      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
92732    }else{
92733      int eAuto = getAutoVacuum(zRight);
92734      assert( eAuto>=0 && eAuto<=2 );
92735      db->nextAutovac = (u8)eAuto;
92736      if( ALWAYS(eAuto>=0) ){
92737        /* Call SetAutoVacuum() to set initialize the internal auto and
92738        ** incr-vacuum flags. This is required in case this connection
92739        ** creates the database file. It is important that it is created
92740        ** as an auto-vacuum capable db.
92741        */
92742        rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
92743        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
92744          /* When setting the auto_vacuum mode to either "full" or
92745          ** "incremental", write the value of meta[6] in the database
92746          ** file. Before writing to meta[6], check that meta[3] indicates
92747          ** that this really is an auto-vacuum capable database.
92748          */
92749          static const VdbeOpList setMeta6[] = {
92750            { OP_Transaction,    0,         1,                 0},    /* 0 */
92751            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
92752            { OP_If,             1,         0,                 0},    /* 2 */
92753            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
92754            { OP_Integer,        0,         1,                 0},    /* 4 */
92755            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
92756          };
92757          int iAddr;
92758          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
92759          sqlite3VdbeChangeP1(v, iAddr, iDb);
92760          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
92761          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
92762          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
92763          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
92764          sqlite3VdbeUsesBtree(v, iDb);
92765        }
92766      }
92767    }
92768  }else
92769#endif
92770
92771  /*
92772  **  PRAGMA [database.]incremental_vacuum(N)
92773  **
92774  ** Do N steps of incremental vacuuming on a database.
92775  */
92776#ifndef SQLITE_OMIT_AUTOVACUUM
92777  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
92778    int iLimit, addr;
92779    if( sqlite3ReadSchema(pParse) ){
92780      goto pragma_out;
92781    }
92782    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
92783      iLimit = 0x7fffffff;
92784    }
92785    sqlite3BeginWriteOperation(pParse, 0, iDb);
92786    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
92787    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
92788    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
92789    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
92790    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
92791    sqlite3VdbeJumpHere(v, addr);
92792  }else
92793#endif
92794
92795#ifndef SQLITE_OMIT_PAGER_PRAGMAS
92796  /*
92797  **  PRAGMA [database.]cache_size
92798  **  PRAGMA [database.]cache_size=N
92799  **
92800  ** The first form reports the current local setting for the
92801  ** page cache size. The second form sets the local
92802  ** page cache size value.  If N is positive then that is the
92803  ** number of pages in the cache.  If N is negative, then the
92804  ** number of pages is adjusted so that the cache uses -N kibibytes
92805  ** of memory.
92806  */
92807  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
92808    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92809    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92810    if( !zRight ){
92811      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
92812    }else{
92813      int size = sqlite3Atoi(zRight);
92814      pDb->pSchema->cache_size = size;
92815      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92816    }
92817  }else
92818
92819  /*
92820  **   PRAGMA temp_store
92821  **   PRAGMA temp_store = "default"|"memory"|"file"
92822  **
92823  ** Return or set the local value of the temp_store flag.  Changing
92824  ** the local value does not make changes to the disk file and the default
92825  ** value will be restored the next time the database is opened.
92826  **
92827  ** Note that it is possible for the library compile-time options to
92828  ** override this setting
92829  */
92830  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
92831    if( !zRight ){
92832      returnSingleInt(pParse, "temp_store", db->temp_store);
92833    }else{
92834      changeTempStorage(pParse, zRight);
92835    }
92836  }else
92837
92838  /*
92839  **   PRAGMA temp_store_directory
92840  **   PRAGMA temp_store_directory = ""|"directory_name"
92841  **
92842  ** Return or set the local value of the temp_store_directory flag.  Changing
92843  ** the value sets a specific directory to be used for temporary files.
92844  ** Setting to a null string reverts to the default temporary directory search.
92845  ** If temporary directory is changed, then invalidateTempStorage.
92846  **
92847  */
92848  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
92849    if( !zRight ){
92850      if( sqlite3_temp_directory ){
92851        sqlite3VdbeSetNumCols(v, 1);
92852        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
92853            "temp_store_directory", SQLITE_STATIC);
92854        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
92855        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92856      }
92857    }else{
92858#ifndef SQLITE_OMIT_WSD
92859      if( zRight[0] ){
92860        int res;
92861        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
92862        if( rc!=SQLITE_OK || res==0 ){
92863          sqlite3ErrorMsg(pParse, "not a writable directory");
92864          goto pragma_out;
92865        }
92866      }
92867      if( SQLITE_TEMP_STORE==0
92868       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
92869       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
92870      ){
92871        invalidateTempStorage(pParse);
92872      }
92873      sqlite3_free(sqlite3_temp_directory);
92874      if( zRight[0] ){
92875        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
92876      }else{
92877        sqlite3_temp_directory = 0;
92878      }
92879#endif /* SQLITE_OMIT_WSD */
92880    }
92881  }else
92882
92883#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
92884#  if defined(__APPLE__)
92885#    define SQLITE_ENABLE_LOCKING_STYLE 1
92886#  else
92887#    define SQLITE_ENABLE_LOCKING_STYLE 0
92888#  endif
92889#endif
92890#if SQLITE_ENABLE_LOCKING_STYLE
92891  /*
92892   **   PRAGMA [database.]lock_proxy_file
92893   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
92894   **
92895   ** Return or set the value of the lock_proxy_file flag.  Changing
92896   ** the value sets a specific file to be used for database access locks.
92897   **
92898   */
92899  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
92900    if( !zRight ){
92901      Pager *pPager = sqlite3BtreePager(pDb->pBt);
92902      char *proxy_file_path = NULL;
92903      sqlite3_file *pFile = sqlite3PagerFile(pPager);
92904      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
92905                           &proxy_file_path);
92906
92907      if( proxy_file_path ){
92908        sqlite3VdbeSetNumCols(v, 1);
92909        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
92910                              "lock_proxy_file", SQLITE_STATIC);
92911        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
92912        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92913      }
92914    }else{
92915      Pager *pPager = sqlite3BtreePager(pDb->pBt);
92916      sqlite3_file *pFile = sqlite3PagerFile(pPager);
92917      int res;
92918      if( zRight[0] ){
92919        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
92920                                     zRight);
92921      } else {
92922        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
92923                                     NULL);
92924      }
92925      if( res!=SQLITE_OK ){
92926        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
92927        goto pragma_out;
92928      }
92929    }
92930  }else
92931#endif /* SQLITE_ENABLE_LOCKING_STYLE */
92932
92933  /*
92934  **   PRAGMA [database.]synchronous
92935  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
92936  **
92937  ** Return or set the local value of the synchronous flag.  Changing
92938  ** the local value does not make changes to the disk file and the
92939  ** default value will be restored the next time the database is
92940  ** opened.
92941  */
92942  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
92943    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92944    if( !zRight ){
92945      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
92946    }else{
92947      if( !db->autoCommit ){
92948        sqlite3ErrorMsg(pParse,
92949            "Safety level may not be changed inside a transaction");
92950      }else{
92951        pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
92952      }
92953    }
92954  }else
92955#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
92956
92957#ifndef SQLITE_OMIT_FLAG_PRAGMAS
92958  if( flagPragma(pParse, zLeft, zRight) ){
92959    /* The flagPragma() subroutine also generates any necessary code
92960    ** there is nothing more to do here */
92961  }else
92962#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
92963
92964#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
92965  /*
92966  **   PRAGMA table_info(<table>)
92967  **
92968  ** Return a single row for each column of the named table. The columns of
92969  ** the returned data set are:
92970  **
92971  ** cid:        Column id (numbered from left to right, starting at 0)
92972  ** name:       Column name
92973  ** type:       Column declaration type.
92974  ** notnull:    True if 'NOT NULL' is part of column declaration
92975  ** dflt_value: The default value for the column, if any.
92976  */
92977  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
92978    Table *pTab;
92979    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92980    pTab = sqlite3FindTable(db, zRight, zDb);
92981    if( pTab ){
92982      int i;
92983      int nHidden = 0;
92984      Column *pCol;
92985      sqlite3VdbeSetNumCols(v, 6);
92986      pParse->nMem = 6;
92987      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
92988      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
92989      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
92990      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
92991      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
92992      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
92993      sqlite3ViewGetColumnNames(pParse, pTab);
92994      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
92995        if( IsHiddenColumn(pCol) ){
92996          nHidden++;
92997          continue;
92998        }
92999        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
93000        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
93001        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93002           pCol->zType ? pCol->zType : "", 0);
93003        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
93004        if( pCol->zDflt ){
93005          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
93006        }else{
93007          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
93008        }
93009        sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
93010        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
93011      }
93012    }
93013  }else
93014
93015  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
93016    Index *pIdx;
93017    Table *pTab;
93018    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93019    pIdx = sqlite3FindIndex(db, zRight, zDb);
93020    if( pIdx ){
93021      int i;
93022      pTab = pIdx->pTable;
93023      sqlite3VdbeSetNumCols(v, 3);
93024      pParse->nMem = 3;
93025      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
93026      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
93027      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
93028      for(i=0; i<pIdx->nColumn; i++){
93029        int cnum = pIdx->aiColumn[i];
93030        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93031        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
93032        assert( pTab->nCol>cnum );
93033        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
93034        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93035      }
93036    }
93037  }else
93038
93039  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
93040    Index *pIdx;
93041    Table *pTab;
93042    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93043    pTab = sqlite3FindTable(db, zRight, zDb);
93044    if( pTab ){
93045      v = sqlite3GetVdbe(pParse);
93046      pIdx = pTab->pIndex;
93047      if( pIdx ){
93048        int i = 0;
93049        sqlite3VdbeSetNumCols(v, 3);
93050        pParse->nMem = 3;
93051        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93052        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93053        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
93054        while(pIdx){
93055          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93056          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
93057          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
93058          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93059          ++i;
93060          pIdx = pIdx->pNext;
93061        }
93062      }
93063    }
93064  }else
93065
93066  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
93067    int i;
93068    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93069    sqlite3VdbeSetNumCols(v, 3);
93070    pParse->nMem = 3;
93071    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93072    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93073    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
93074    for(i=0; i<db->nDb; i++){
93075      if( db->aDb[i].pBt==0 ) continue;
93076      assert( db->aDb[i].zName!=0 );
93077      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93078      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
93079      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93080           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
93081      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93082    }
93083  }else
93084
93085  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
93086    int i = 0;
93087    HashElem *p;
93088    sqlite3VdbeSetNumCols(v, 2);
93089    pParse->nMem = 2;
93090    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93091    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93092    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
93093      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
93094      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
93095      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
93096      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
93097    }
93098  }else
93099#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
93100
93101#ifndef SQLITE_OMIT_FOREIGN_KEY
93102  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
93103    FKey *pFK;
93104    Table *pTab;
93105    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93106    pTab = sqlite3FindTable(db, zRight, zDb);
93107    if( pTab ){
93108      v = sqlite3GetVdbe(pParse);
93109      pFK = pTab->pFKey;
93110      if( pFK ){
93111        int i = 0;
93112        sqlite3VdbeSetNumCols(v, 8);
93113        pParse->nMem = 8;
93114        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
93115        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
93116        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
93117        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
93118        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
93119        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
93120        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
93121        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
93122        while(pFK){
93123          int j;
93124          for(j=0; j<pFK->nCol; j++){
93125            char *zCol = pFK->aCol[j].zCol;
93126            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
93127            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
93128            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93129            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
93130            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
93131            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
93132                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
93133            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
93134            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
93135            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
93136            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
93137            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
93138          }
93139          ++i;
93140          pFK = pFK->pNextFrom;
93141        }
93142      }
93143    }
93144  }else
93145#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
93146
93147#ifndef NDEBUG
93148  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
93149    if( zRight ){
93150      if( sqlite3GetBoolean(zRight, 0) ){
93151        sqlite3ParserTrace(stderr, "parser: ");
93152      }else{
93153        sqlite3ParserTrace(0, 0);
93154      }
93155    }
93156  }else
93157#endif
93158
93159  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
93160  ** used will be case sensitive or not depending on the RHS.
93161  */
93162  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
93163    if( zRight ){
93164      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
93165    }
93166  }else
93167
93168#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
93169# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
93170#endif
93171
93172#ifndef SQLITE_OMIT_INTEGRITY_CHECK
93173  /* Pragma "quick_check" is an experimental reduced version of
93174  ** integrity_check designed to detect most database corruption
93175  ** without most of the overhead of a full integrity-check.
93176  */
93177  if( sqlite3StrICmp(zLeft, "integrity_check")==0
93178   || sqlite3StrICmp(zLeft, "quick_check")==0
93179  ){
93180    int i, j, addr, mxErr;
93181
93182    /* Code that appears at the end of the integrity check.  If no error
93183    ** messages have been generated, output OK.  Otherwise output the
93184    ** error message
93185    */
93186    static const VdbeOpList endCode[] = {
93187      { OP_AddImm,      1, 0,        0},    /* 0 */
93188      { OP_IfNeg,       1, 0,        0},    /* 1 */
93189      { OP_String8,     0, 3,        0},    /* 2 */
93190      { OP_ResultRow,   3, 1,        0},
93191    };
93192
93193    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
93194
93195    /* Initialize the VDBE program */
93196    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93197    pParse->nMem = 6;
93198    sqlite3VdbeSetNumCols(v, 1);
93199    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
93200
93201    /* Set the maximum error count */
93202    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
93203    if( zRight ){
93204      sqlite3GetInt32(zRight, &mxErr);
93205      if( mxErr<=0 ){
93206        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
93207      }
93208    }
93209    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
93210
93211    /* Do an integrity check on each database file */
93212    for(i=0; i<db->nDb; i++){
93213      HashElem *x;
93214      Hash *pTbls;
93215      int cnt = 0;
93216
93217      if( OMIT_TEMPDB && i==1 ) continue;
93218
93219      sqlite3CodeVerifySchema(pParse, i);
93220      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
93221      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93222      sqlite3VdbeJumpHere(v, addr);
93223
93224      /* Do an integrity check of the B-Tree
93225      **
93226      ** Begin by filling registers 2, 3, ... with the root pages numbers
93227      ** for all tables and indices in the database.
93228      */
93229      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93230      pTbls = &db->aDb[i].pSchema->tblHash;
93231      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
93232        Table *pTab = sqliteHashData(x);
93233        Index *pIdx;
93234        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
93235        cnt++;
93236        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93237          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
93238          cnt++;
93239        }
93240      }
93241
93242      /* Make sure sufficient number of registers have been allocated */
93243      if( pParse->nMem < cnt+4 ){
93244        pParse->nMem = cnt+4;
93245      }
93246
93247      /* Do the b-tree integrity checks */
93248      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
93249      sqlite3VdbeChangeP5(v, (u8)i);
93250      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
93251      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93252         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
93253         P4_DYNAMIC);
93254      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
93255      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
93256      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
93257      sqlite3VdbeJumpHere(v, addr);
93258
93259      /* Make sure all the indices are constructed correctly.
93260      */
93261      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
93262        Table *pTab = sqliteHashData(x);
93263        Index *pIdx;
93264        int loopTop;
93265
93266        if( pTab->pIndex==0 ) continue;
93267        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
93268        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93269        sqlite3VdbeJumpHere(v, addr);
93270        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
93271        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
93272        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
93273        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
93274        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93275          int jmp2;
93276          int r1;
93277          static const VdbeOpList idxErr[] = {
93278            { OP_AddImm,      1, -1,  0},
93279            { OP_String8,     0,  3,  0},    /* 1 */
93280            { OP_Rowid,       1,  4,  0},
93281            { OP_String8,     0,  5,  0},    /* 3 */
93282            { OP_String8,     0,  6,  0},    /* 4 */
93283            { OP_Concat,      4,  3,  3},
93284            { OP_Concat,      5,  3,  3},
93285            { OP_Concat,      6,  3,  3},
93286            { OP_ResultRow,   3,  1,  0},
93287            { OP_IfPos,       1,  0,  0},    /* 9 */
93288            { OP_Halt,        0,  0,  0},
93289          };
93290          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
93291          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
93292          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
93293          sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
93294          sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
93295          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
93296          sqlite3VdbeJumpHere(v, addr+9);
93297          sqlite3VdbeJumpHere(v, jmp2);
93298        }
93299        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
93300        sqlite3VdbeJumpHere(v, loopTop);
93301        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93302          static const VdbeOpList cntIdx[] = {
93303             { OP_Integer,      0,  3,  0},
93304             { OP_Rewind,       0,  0,  0},  /* 1 */
93305             { OP_AddImm,       3,  1,  0},
93306             { OP_Next,         0,  0,  0},  /* 3 */
93307             { OP_Eq,           2,  0,  3},  /* 4 */
93308             { OP_AddImm,       1, -1,  0},
93309             { OP_String8,      0,  2,  0},  /* 6 */
93310             { OP_String8,      0,  3,  0},  /* 7 */
93311             { OP_Concat,       3,  2,  2},
93312             { OP_ResultRow,    2,  1,  0},
93313          };
93314          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
93315          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93316          sqlite3VdbeJumpHere(v, addr);
93317          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
93318          sqlite3VdbeChangeP1(v, addr+1, j+2);
93319          sqlite3VdbeChangeP2(v, addr+1, addr+4);
93320          sqlite3VdbeChangeP1(v, addr+3, j+2);
93321          sqlite3VdbeChangeP2(v, addr+3, addr+2);
93322          sqlite3VdbeJumpHere(v, addr+4);
93323          sqlite3VdbeChangeP4(v, addr+6,
93324                     "wrong # of entries in index ", P4_STATIC);
93325          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
93326        }
93327      }
93328    }
93329    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
93330    sqlite3VdbeChangeP2(v, addr, -mxErr);
93331    sqlite3VdbeJumpHere(v, addr+1);
93332    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
93333  }else
93334#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
93335
93336#ifndef SQLITE_OMIT_UTF16
93337  /*
93338  **   PRAGMA encoding
93339  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
93340  **
93341  ** In its first form, this pragma returns the encoding of the main
93342  ** database. If the database is not initialized, it is initialized now.
93343  **
93344  ** The second form of this pragma is a no-op if the main database file
93345  ** has not already been initialized. In this case it sets the default
93346  ** encoding that will be used for the main database file if a new file
93347  ** is created. If an existing main database file is opened, then the
93348  ** default text encoding for the existing database is used.
93349  **
93350  ** In all cases new databases created using the ATTACH command are
93351  ** created to use the same default text encoding as the main database. If
93352  ** the main database has not been initialized and/or created when ATTACH
93353  ** is executed, this is done before the ATTACH operation.
93354  **
93355  ** In the second form this pragma sets the text encoding to be used in
93356  ** new database files created using this database handle. It is only
93357  ** useful if invoked immediately after the main database i
93358  */
93359  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
93360    static const struct EncName {
93361      char *zName;
93362      u8 enc;
93363    } encnames[] = {
93364      { "UTF8",     SQLITE_UTF8        },
93365      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
93366      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
93367      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
93368      { "UTF16le",  SQLITE_UTF16LE     },
93369      { "UTF16be",  SQLITE_UTF16BE     },
93370      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
93371      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
93372      { 0, 0 }
93373    };
93374    const struct EncName *pEnc;
93375    if( !zRight ){    /* "PRAGMA encoding" */
93376      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93377      sqlite3VdbeSetNumCols(v, 1);
93378      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
93379      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
93380      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
93381      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
93382      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
93383      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
93384      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93385    }else{                        /* "PRAGMA encoding = XXX" */
93386      /* Only change the value of sqlite.enc if the database handle is not
93387      ** initialized. If the main database exists, the new sqlite.enc value
93388      ** will be overwritten when the schema is next loaded. If it does not
93389      ** already exists, it will be created to use the new encoding value.
93390      */
93391      if(
93392        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
93393        DbHasProperty(db, 0, DB_Empty)
93394      ){
93395        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
93396          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
93397            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
93398            break;
93399          }
93400        }
93401        if( !pEnc->zName ){
93402          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
93403        }
93404      }
93405    }
93406  }else
93407#endif /* SQLITE_OMIT_UTF16 */
93408
93409#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
93410  /*
93411  **   PRAGMA [database.]schema_version
93412  **   PRAGMA [database.]schema_version = <integer>
93413  **
93414  **   PRAGMA [database.]user_version
93415  **   PRAGMA [database.]user_version = <integer>
93416  **
93417  ** The pragma's schema_version and user_version are used to set or get
93418  ** the value of the schema-version and user-version, respectively. Both
93419  ** the schema-version and the user-version are 32-bit signed integers
93420  ** stored in the database header.
93421  **
93422  ** The schema-cookie is usually only manipulated internally by SQLite. It
93423  ** is incremented by SQLite whenever the database schema is modified (by
93424  ** creating or dropping a table or index). The schema version is used by
93425  ** SQLite each time a query is executed to ensure that the internal cache
93426  ** of the schema used when compiling the SQL query matches the schema of
93427  ** the database against which the compiled query is actually executed.
93428  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
93429  ** the schema-version is potentially dangerous and may lead to program
93430  ** crashes or database corruption. Use with caution!
93431  **
93432  ** The user-version is not used internally by SQLite. It may be used by
93433  ** applications for any purpose.
93434  */
93435  if( sqlite3StrICmp(zLeft, "schema_version")==0
93436   || sqlite3StrICmp(zLeft, "user_version")==0
93437   || sqlite3StrICmp(zLeft, "freelist_count")==0
93438  ){
93439    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
93440    sqlite3VdbeUsesBtree(v, iDb);
93441    switch( zLeft[0] ){
93442      case 'f': case 'F':
93443        iCookie = BTREE_FREE_PAGE_COUNT;
93444        break;
93445      case 's': case 'S':
93446        iCookie = BTREE_SCHEMA_VERSION;
93447        break;
93448      default:
93449        iCookie = BTREE_USER_VERSION;
93450        break;
93451    }
93452
93453    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
93454      /* Write the specified cookie value */
93455      static const VdbeOpList setCookie[] = {
93456        { OP_Transaction,    0,  1,  0},    /* 0 */
93457        { OP_Integer,        0,  1,  0},    /* 1 */
93458        { OP_SetCookie,      0,  0,  1},    /* 2 */
93459      };
93460      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
93461      sqlite3VdbeChangeP1(v, addr, iDb);
93462      sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
93463      sqlite3VdbeChangeP1(v, addr+2, iDb);
93464      sqlite3VdbeChangeP2(v, addr+2, iCookie);
93465    }else{
93466      /* Read the specified cookie value */
93467      static const VdbeOpList readCookie[] = {
93468        { OP_Transaction,     0,  0,  0},    /* 0 */
93469        { OP_ReadCookie,      0,  1,  0},    /* 1 */
93470        { OP_ResultRow,       1,  1,  0}
93471      };
93472      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
93473      sqlite3VdbeChangeP1(v, addr, iDb);
93474      sqlite3VdbeChangeP1(v, addr+1, iDb);
93475      sqlite3VdbeChangeP3(v, addr+1, iCookie);
93476      sqlite3VdbeSetNumCols(v, 1);
93477      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
93478    }
93479  }else
93480#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
93481
93482#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
93483  /*
93484  **   PRAGMA compile_options
93485  **
93486  ** Return the names of all compile-time options used in this build,
93487  ** one option per row.
93488  */
93489  if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
93490    int i = 0;
93491    const char *zOpt;
93492    sqlite3VdbeSetNumCols(v, 1);
93493    pParse->nMem = 1;
93494    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
93495    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
93496      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
93497      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93498    }
93499  }else
93500#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
93501
93502#ifndef SQLITE_OMIT_WAL
93503  /*
93504  **   PRAGMA [database.]wal_checkpoint = passive|full|restart
93505  **
93506  ** Checkpoint the database.
93507  */
93508  if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
93509    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
93510    int eMode = SQLITE_CHECKPOINT_PASSIVE;
93511    if( zRight ){
93512      if( sqlite3StrICmp(zRight, "full")==0 ){
93513        eMode = SQLITE_CHECKPOINT_FULL;
93514      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
93515        eMode = SQLITE_CHECKPOINT_RESTART;
93516      }
93517    }
93518    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93519    sqlite3VdbeSetNumCols(v, 3);
93520    pParse->nMem = 3;
93521    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
93522    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
93523    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
93524
93525    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
93526    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93527  }else
93528
93529  /*
93530  **   PRAGMA wal_autocheckpoint
93531  **   PRAGMA wal_autocheckpoint = N
93532  **
93533  ** Configure a database connection to automatically checkpoint a database
93534  ** after accumulating N frames in the log. Or query for the current value
93535  ** of N.
93536  */
93537  if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
93538    if( zRight ){
93539      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
93540    }
93541    returnSingleInt(pParse, "wal_autocheckpoint",
93542       db->xWalCallback==sqlite3WalDefaultHook ?
93543           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
93544  }else
93545#endif
93546
93547  /*
93548  **  PRAGMA shrink_memory
93549  **
93550  ** This pragma attempts to free as much memory as possible from the
93551  ** current database connection.
93552  */
93553  if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
93554    sqlite3_db_release_memory(db);
93555  }else
93556
93557#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
93558  /*
93559  ** Report the current state of file logs for all databases
93560  */
93561  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
93562    static const char *const azLockName[] = {
93563      "unlocked", "shared", "reserved", "pending", "exclusive"
93564    };
93565    int i;
93566    sqlite3VdbeSetNumCols(v, 2);
93567    pParse->nMem = 2;
93568    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
93569    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
93570    for(i=0; i<db->nDb; i++){
93571      Btree *pBt;
93572      Pager *pPager;
93573      const char *zState = "unknown";
93574      int j;
93575      if( db->aDb[i].zName==0 ) continue;
93576      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
93577      pBt = db->aDb[i].pBt;
93578      if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
93579        zState = "closed";
93580      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
93581                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
93582         zState = azLockName[j];
93583      }
93584      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
93585      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
93586    }
93587
93588  }else
93589#endif
93590
93591#ifdef SQLITE_HAS_CODEC
93592  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
93593    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
93594  }else
93595  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
93596    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
93597  }else
93598  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
93599                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
93600    int i, h1, h2;
93601    char zKey[40];
93602    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
93603      h1 += 9*(1&(h1>>6));
93604      h2 += 9*(1&(h2>>6));
93605      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
93606    }
93607    if( (zLeft[3] & 0xf)==0xb ){
93608      sqlite3_key(db, zKey, i/2);
93609    }else{
93610      sqlite3_rekey(db, zKey, i/2);
93611    }
93612  }else
93613#endif
93614#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
93615  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
93616#ifdef SQLITE_HAS_CODEC
93617    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
93618      sqlite3_activate_see(&zRight[4]);
93619    }
93620#endif
93621#ifdef SQLITE_ENABLE_CEROD
93622    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
93623      sqlite3_activate_cerod(&zRight[6]);
93624    }
93625#endif
93626  }else
93627#endif
93628
93629
93630  {/* Empty ELSE clause */}
93631
93632  /*
93633  ** Reset the safety level, in case the fullfsync flag or synchronous
93634  ** setting changed.
93635  */
93636#ifndef SQLITE_OMIT_PAGER_PRAGMAS
93637  if( db->autoCommit ){
93638    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
93639               (db->flags&SQLITE_FullFSync)!=0,
93640               (db->flags&SQLITE_CkptFullFSync)!=0);
93641  }
93642#endif
93643pragma_out:
93644  sqlite3DbFree(db, zLeft);
93645  sqlite3DbFree(db, zRight);
93646}
93647
93648#endif /* SQLITE_OMIT_PRAGMA */
93649
93650/************** End of pragma.c **********************************************/
93651/************** Begin file prepare.c *****************************************/
93652/*
93653** 2005 May 25
93654**
93655** The author disclaims copyright to this source code.  In place of
93656** a legal notice, here is a blessing:
93657**
93658**    May you do good and not evil.
93659**    May you find forgiveness for yourself and forgive others.
93660**    May you share freely, never taking more than you give.
93661**
93662*************************************************************************
93663** This file contains the implementation of the sqlite3_prepare()
93664** interface, and routines that contribute to loading the database schema
93665** from disk.
93666*/
93667
93668/*
93669** Fill the InitData structure with an error message that indicates
93670** that the database is corrupt.
93671*/
93672static void corruptSchema(
93673  InitData *pData,     /* Initialization context */
93674  const char *zObj,    /* Object being parsed at the point of error */
93675  const char *zExtra   /* Error information */
93676){
93677  sqlite3 *db = pData->db;
93678  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
93679    if( zObj==0 ) zObj = "?";
93680    sqlite3SetString(pData->pzErrMsg, db,
93681      "malformed database schema (%s)", zObj);
93682    if( zExtra ){
93683      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
93684                                 "%s - %s", *pData->pzErrMsg, zExtra);
93685    }
93686  }
93687  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
93688}
93689
93690/*
93691** This is the callback routine for the code that initializes the
93692** database.  See sqlite3Init() below for additional information.
93693** This routine is also called from the OP_ParseSchema opcode of the VDBE.
93694**
93695** Each callback contains the following information:
93696**
93697**     argv[0] = name of thing being created
93698**     argv[1] = root page number for table or index. 0 for trigger or view.
93699**     argv[2] = SQL text for the CREATE statement.
93700**
93701*/
93702SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
93703  InitData *pData = (InitData*)pInit;
93704  sqlite3 *db = pData->db;
93705  int iDb = pData->iDb;
93706
93707  assert( argc==3 );
93708  UNUSED_PARAMETER2(NotUsed, argc);
93709  assert( sqlite3_mutex_held(db->mutex) );
93710  DbClearProperty(db, iDb, DB_Empty);
93711  if( db->mallocFailed ){
93712    corruptSchema(pData, argv[0], 0);
93713    return 1;
93714  }
93715
93716  assert( iDb>=0 && iDb<db->nDb );
93717  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
93718  if( argv[1]==0 ){
93719    corruptSchema(pData, argv[0], 0);
93720  }else if( argv[2] && argv[2][0] ){
93721    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
93722    ** But because db->init.busy is set to 1, no VDBE code is generated
93723    ** or executed.  All the parser does is build the internal data
93724    ** structures that describe the table, index, or view.
93725    */
93726    int rc;
93727    sqlite3_stmt *pStmt;
93728    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
93729
93730    assert( db->init.busy );
93731    db->init.iDb = iDb;
93732    db->init.newTnum = sqlite3Atoi(argv[1]);
93733    db->init.orphanTrigger = 0;
93734    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
93735    rc = db->errCode;
93736    assert( (rc&0xFF)==(rcp&0xFF) );
93737    db->init.iDb = 0;
93738    if( SQLITE_OK!=rc ){
93739      if( db->init.orphanTrigger ){
93740        assert( iDb==1 );
93741      }else{
93742        pData->rc = rc;
93743        if( rc==SQLITE_NOMEM ){
93744          db->mallocFailed = 1;
93745        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
93746          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
93747        }
93748      }
93749    }
93750    sqlite3_finalize(pStmt);
93751  }else if( argv[0]==0 ){
93752    corruptSchema(pData, 0, 0);
93753  }else{
93754    /* If the SQL column is blank it means this is an index that
93755    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
93756    ** constraint for a CREATE TABLE.  The index should have already
93757    ** been created when we processed the CREATE TABLE.  All we have
93758    ** to do here is record the root page number for that index.
93759    */
93760    Index *pIndex;
93761    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
93762    if( pIndex==0 ){
93763      /* This can occur if there exists an index on a TEMP table which
93764      ** has the same name as another index on a permanent index.  Since
93765      ** the permanent table is hidden by the TEMP table, we can also
93766      ** safely ignore the index on the permanent table.
93767      */
93768      /* Do Nothing */;
93769    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
93770      corruptSchema(pData, argv[0], "invalid rootpage");
93771    }
93772  }
93773  return 0;
93774}
93775
93776/*
93777** Attempt to read the database schema and initialize internal
93778** data structures for a single database file.  The index of the
93779** database file is given by iDb.  iDb==0 is used for the main
93780** database.  iDb==1 should never be used.  iDb>=2 is used for
93781** auxiliary databases.  Return one of the SQLITE_ error codes to
93782** indicate success or failure.
93783*/
93784static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
93785  int rc;
93786  int i;
93787  int size;
93788  Table *pTab;
93789  Db *pDb;
93790  char const *azArg[4];
93791  int meta[5];
93792  InitData initData;
93793  char const *zMasterSchema;
93794  char const *zMasterName;
93795  int openedTransaction = 0;
93796
93797  /*
93798  ** The master database table has a structure like this
93799  */
93800  static const char master_schema[] =
93801     "CREATE TABLE sqlite_master(\n"
93802     "  type text,\n"
93803     "  name text,\n"
93804     "  tbl_name text,\n"
93805     "  rootpage integer,\n"
93806     "  sql text\n"
93807     ")"
93808  ;
93809#ifndef SQLITE_OMIT_TEMPDB
93810  static const char temp_master_schema[] =
93811     "CREATE TEMP TABLE sqlite_temp_master(\n"
93812     "  type text,\n"
93813     "  name text,\n"
93814     "  tbl_name text,\n"
93815     "  rootpage integer,\n"
93816     "  sql text\n"
93817     ")"
93818  ;
93819#else
93820  #define temp_master_schema 0
93821#endif
93822
93823  assert( iDb>=0 && iDb<db->nDb );
93824  assert( db->aDb[iDb].pSchema );
93825  assert( sqlite3_mutex_held(db->mutex) );
93826  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
93827
93828  /* zMasterSchema and zInitScript are set to point at the master schema
93829  ** and initialisation script appropriate for the database being
93830  ** initialised. zMasterName is the name of the master table.
93831  */
93832  if( !OMIT_TEMPDB && iDb==1 ){
93833    zMasterSchema = temp_master_schema;
93834  }else{
93835    zMasterSchema = master_schema;
93836  }
93837  zMasterName = SCHEMA_TABLE(iDb);
93838
93839  /* Construct the schema tables.  */
93840  azArg[0] = zMasterName;
93841  azArg[1] = "1";
93842  azArg[2] = zMasterSchema;
93843  azArg[3] = 0;
93844  initData.db = db;
93845  initData.iDb = iDb;
93846  initData.rc = SQLITE_OK;
93847  initData.pzErrMsg = pzErrMsg;
93848  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
93849  if( initData.rc ){
93850    rc = initData.rc;
93851    goto error_out;
93852  }
93853  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
93854  if( ALWAYS(pTab) ){
93855    pTab->tabFlags |= TF_Readonly;
93856  }
93857
93858  /* Create a cursor to hold the database open
93859  */
93860  pDb = &db->aDb[iDb];
93861  if( pDb->pBt==0 ){
93862    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
93863      DbSetProperty(db, 1, DB_SchemaLoaded);
93864    }
93865    return SQLITE_OK;
93866  }
93867
93868  /* If there is not already a read-only (or read-write) transaction opened
93869  ** on the b-tree database, open one now. If a transaction is opened, it
93870  ** will be closed before this function returns.  */
93871  sqlite3BtreeEnter(pDb->pBt);
93872  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
93873    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
93874    if( rc!=SQLITE_OK ){
93875      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
93876      goto initone_error_out;
93877    }
93878    openedTransaction = 1;
93879  }
93880
93881  /* Get the database meta information.
93882  **
93883  ** Meta values are as follows:
93884  **    meta[0]   Schema cookie.  Changes with each schema change.
93885  **    meta[1]   File format of schema layer.
93886  **    meta[2]   Size of the page cache.
93887  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
93888  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
93889  **    meta[5]   User version
93890  **    meta[6]   Incremental vacuum mode
93891  **    meta[7]   unused
93892  **    meta[8]   unused
93893  **    meta[9]   unused
93894  **
93895  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
93896  ** the possible values of meta[4].
93897  */
93898  for(i=0; i<ArraySize(meta); i++){
93899    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
93900  }
93901  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
93902
93903  /* If opening a non-empty database, check the text encoding. For the
93904  ** main database, set sqlite3.enc to the encoding of the main database.
93905  ** For an attached db, it is an error if the encoding is not the same
93906  ** as sqlite3.enc.
93907  */
93908  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
93909    if( iDb==0 ){
93910      u8 encoding;
93911      /* If opening the main database, set ENC(db). */
93912      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
93913      if( encoding==0 ) encoding = SQLITE_UTF8;
93914      ENC(db) = encoding;
93915      db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
93916    }else{
93917      /* If opening an attached database, the encoding much match ENC(db) */
93918      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
93919        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
93920            " text encoding as main database");
93921        rc = SQLITE_ERROR;
93922        goto initone_error_out;
93923      }
93924    }
93925  }else{
93926    DbSetProperty(db, iDb, DB_Empty);
93927  }
93928  pDb->pSchema->enc = ENC(db);
93929
93930  if( pDb->pSchema->cache_size==0 ){
93931#ifndef SQLITE_OMIT_DEPRECATED
93932    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
93933    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
93934    pDb->pSchema->cache_size = size;
93935#else
93936    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
93937#endif
93938    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
93939  }
93940
93941  /*
93942  ** file_format==1    Version 3.0.0.
93943  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
93944  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
93945  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
93946  */
93947  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
93948  if( pDb->pSchema->file_format==0 ){
93949    pDb->pSchema->file_format = 1;
93950  }
93951  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
93952    sqlite3SetString(pzErrMsg, db, "unsupported file format");
93953    rc = SQLITE_CORRUPT_BKPT; // Android Change from "rc = SQLITE_ERROR;"
93954    goto initone_error_out;
93955  }
93956
93957  /* Ticket #2804:  When we open a database in the newer file format,
93958  ** clear the legacy_file_format pragma flag so that a VACUUM will
93959  ** not downgrade the database and thus invalidate any descending
93960  ** indices that the user might have created.
93961  */
93962  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
93963    db->flags &= ~SQLITE_LegacyFileFmt;
93964  }
93965
93966  /* Read the schema information out of the schema tables
93967  */
93968  assert( db->init.busy );
93969  {
93970    char *zSql;
93971    zSql = sqlite3MPrintf(db,
93972        "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
93973        db->aDb[iDb].zName, zMasterName);
93974#ifndef SQLITE_OMIT_AUTHORIZATION
93975    {
93976      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
93977      xAuth = db->xAuth;
93978      db->xAuth = 0;
93979#endif
93980      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
93981#ifndef SQLITE_OMIT_AUTHORIZATION
93982      db->xAuth = xAuth;
93983    }
93984#endif
93985    if( rc==SQLITE_OK ) rc = initData.rc;
93986    sqlite3DbFree(db, zSql);
93987#ifndef SQLITE_OMIT_ANALYZE
93988    if( rc==SQLITE_OK ){
93989      sqlite3AnalysisLoad(db, iDb);
93990    }
93991#endif
93992  }
93993  if( db->mallocFailed ){
93994    rc = SQLITE_NOMEM;
93995    sqlite3ResetInternalSchema(db, -1);
93996  }
93997  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
93998    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
93999    ** the schema loaded, even if errors occurred. In this situation the
94000    ** current sqlite3_prepare() operation will fail, but the following one
94001    ** will attempt to compile the supplied statement against whatever subset
94002    ** of the schema was loaded before the error occurred. The primary
94003    ** purpose of this is to allow access to the sqlite_master table
94004    ** even when its contents have been corrupted.
94005    */
94006    DbSetProperty(db, iDb, DB_SchemaLoaded);
94007    rc = SQLITE_OK;
94008  }
94009
94010  /* Jump here for an error that occurs after successfully allocating
94011  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
94012  ** before that point, jump to error_out.
94013  */
94014initone_error_out:
94015  if( openedTransaction ){
94016    sqlite3BtreeCommit(pDb->pBt);
94017  }
94018  sqlite3BtreeLeave(pDb->pBt);
94019
94020error_out:
94021  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
94022    db->mallocFailed = 1;
94023  }
94024  return rc;
94025}
94026
94027/*
94028** Initialize all database files - the main database file, the file
94029** used to store temporary tables, and any additional database files
94030** created using ATTACH statements.  Return a success code.  If an
94031** error occurs, write an error message into *pzErrMsg.
94032**
94033** After a database is initialized, the DB_SchemaLoaded bit is set
94034** bit is set in the flags field of the Db structure. If the database
94035** file was of zero-length, then the DB_Empty flag is also set.
94036*/
94037SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
94038  int i, rc;
94039  int commit_internal = !(db->flags&SQLITE_InternChanges);
94040
94041  assert( sqlite3_mutex_held(db->mutex) );
94042  rc = SQLITE_OK;
94043  db->init.busy = 1;
94044  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
94045    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
94046    rc = sqlite3InitOne(db, i, pzErrMsg);
94047    if( rc ){
94048      sqlite3ResetInternalSchema(db, i);
94049    }
94050  }
94051
94052  /* Once all the other databases have been initialised, load the schema
94053  ** for the TEMP database. This is loaded last, as the TEMP database
94054  ** schema may contain references to objects in other databases.
94055  */
94056#ifndef SQLITE_OMIT_TEMPDB
94057  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
94058                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
94059    rc = sqlite3InitOne(db, 1, pzErrMsg);
94060    if( rc ){
94061      sqlite3ResetInternalSchema(db, 1);
94062    }
94063  }
94064#endif
94065
94066  db->init.busy = 0;
94067  if( rc==SQLITE_OK && commit_internal ){
94068    sqlite3CommitInternalChanges(db);
94069  }
94070
94071  return rc;
94072}
94073
94074/*
94075** This routine is a no-op if the database schema is already initialised.
94076** Otherwise, the schema is loaded. An error code is returned.
94077*/
94078SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
94079  int rc = SQLITE_OK;
94080  sqlite3 *db = pParse->db;
94081  assert( sqlite3_mutex_held(db->mutex) );
94082  if( !db->init.busy ){
94083    rc = sqlite3Init(db, &pParse->zErrMsg);
94084  }
94085  if( rc!=SQLITE_OK ){
94086    pParse->rc = rc;
94087    pParse->nErr++;
94088  }
94089  return rc;
94090}
94091
94092
94093/*
94094** Check schema cookies in all databases.  If any cookie is out
94095** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
94096** make no changes to pParse->rc.
94097*/
94098static void schemaIsValid(Parse *pParse){
94099  sqlite3 *db = pParse->db;
94100  int iDb;
94101  int rc;
94102  int cookie;
94103
94104  assert( pParse->checkSchema );
94105  assert( sqlite3_mutex_held(db->mutex) );
94106  for(iDb=0; iDb<db->nDb; iDb++){
94107    int openedTransaction = 0;         /* True if a transaction is opened */
94108    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
94109    if( pBt==0 ) continue;
94110
94111    /* If there is not already a read-only (or read-write) transaction opened
94112    ** on the b-tree database, open one now. If a transaction is opened, it
94113    ** will be closed immediately after reading the meta-value. */
94114    if( !sqlite3BtreeIsInReadTrans(pBt) ){
94115      rc = sqlite3BtreeBeginTrans(pBt, 0);
94116      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
94117        db->mallocFailed = 1;
94118      }
94119      if( rc!=SQLITE_OK ) return;
94120      openedTransaction = 1;
94121    }
94122
94123    /* Read the schema cookie from the database. If it does not match the
94124    ** value stored as part of the in-memory schema representation,
94125    ** set Parse.rc to SQLITE_SCHEMA. */
94126    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
94127    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94128    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
94129      sqlite3ResetInternalSchema(db, iDb);
94130      pParse->rc = SQLITE_SCHEMA;
94131    }
94132
94133    /* Close the transaction, if one was opened. */
94134    if( openedTransaction ){
94135      sqlite3BtreeCommit(pBt);
94136    }
94137  }
94138}
94139
94140/*
94141** Convert a schema pointer into the iDb index that indicates
94142** which database file in db->aDb[] the schema refers to.
94143**
94144** If the same database is attached more than once, the first
94145** attached database is returned.
94146*/
94147SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
94148  int i = -1000000;
94149
94150  /* If pSchema is NULL, then return -1000000. This happens when code in
94151  ** expr.c is trying to resolve a reference to a transient table (i.e. one
94152  ** created by a sub-select). In this case the return value of this
94153  ** function should never be used.
94154  **
94155  ** We return -1000000 instead of the more usual -1 simply because using
94156  ** -1000000 as the incorrect index into db->aDb[] is much
94157  ** more likely to cause a segfault than -1 (of course there are assert()
94158  ** statements too, but it never hurts to play the odds).
94159  */
94160  assert( sqlite3_mutex_held(db->mutex) );
94161  if( pSchema ){
94162    for(i=0; ALWAYS(i<db->nDb); i++){
94163      if( db->aDb[i].pSchema==pSchema ){
94164        break;
94165      }
94166    }
94167    assert( i>=0 && i<db->nDb );
94168  }
94169  return i;
94170}
94171
94172/*
94173** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
94174*/
94175static int sqlite3Prepare(
94176  sqlite3 *db,              /* Database handle. */
94177  const char *zSql,         /* UTF-8 encoded SQL statement. */
94178  int nBytes,               /* Length of zSql in bytes. */
94179  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
94180  Vdbe *pReprepare,         /* VM being reprepared */
94181  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94182  const char **pzTail       /* OUT: End of parsed string */
94183){
94184  Parse *pParse;            /* Parsing context */
94185  char *zErrMsg = 0;        /* Error message */
94186  int rc = SQLITE_OK;       /* Result code */
94187  int i;                    /* Loop counter */
94188
94189  /* Allocate the parsing context */
94190  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
94191  if( pParse==0 ){
94192    rc = SQLITE_NOMEM;
94193    goto end_prepare;
94194  }
94195  pParse->pReprepare = pReprepare;
94196  assert( ppStmt && *ppStmt==0 );
94197  assert( !db->mallocFailed );
94198  assert( sqlite3_mutex_held(db->mutex) );
94199
94200  /* Check to verify that it is possible to get a read lock on all
94201  ** database schemas.  The inability to get a read lock indicates that
94202  ** some other database connection is holding a write-lock, which in
94203  ** turn means that the other connection has made uncommitted changes
94204  ** to the schema.
94205  **
94206  ** Were we to proceed and prepare the statement against the uncommitted
94207  ** schema changes and if those schema changes are subsequently rolled
94208  ** back and different changes are made in their place, then when this
94209  ** prepared statement goes to run the schema cookie would fail to detect
94210  ** the schema change.  Disaster would follow.
94211  **
94212  ** This thread is currently holding mutexes on all Btrees (because
94213  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
94214  ** is not possible for another thread to start a new schema change
94215  ** while this routine is running.  Hence, we do not need to hold
94216  ** locks on the schema, we just need to make sure nobody else is
94217  ** holding them.
94218  **
94219  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
94220  ** but it does *not* override schema lock detection, so this all still
94221  ** works even if READ_UNCOMMITTED is set.
94222  */
94223  for(i=0; i<db->nDb; i++) {
94224    Btree *pBt = db->aDb[i].pBt;
94225    if( pBt ){
94226      assert( sqlite3BtreeHoldsMutex(pBt) );
94227      rc = sqlite3BtreeSchemaLocked(pBt);
94228      if( rc ){
94229        const char *zDb = db->aDb[i].zName;
94230        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
94231        testcase( db->flags & SQLITE_ReadUncommitted );
94232        goto end_prepare;
94233      }
94234    }
94235  }
94236
94237  sqlite3VtabUnlockList(db);
94238
94239  pParse->db = db;
94240  pParse->nQueryLoop = (double)1;
94241  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
94242    char *zSqlCopy;
94243    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
94244    testcase( nBytes==mxLen );
94245    testcase( nBytes==mxLen+1 );
94246    if( nBytes>mxLen ){
94247      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
94248      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
94249      goto end_prepare;
94250    }
94251    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
94252    if( zSqlCopy ){
94253      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
94254      sqlite3DbFree(db, zSqlCopy);
94255      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
94256    }else{
94257      pParse->zTail = &zSql[nBytes];
94258    }
94259  }else{
94260    sqlite3RunParser(pParse, zSql, &zErrMsg);
94261  }
94262  assert( 1==(int)pParse->nQueryLoop );
94263
94264  if( db->mallocFailed ){
94265    pParse->rc = SQLITE_NOMEM;
94266  }
94267  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
94268  if( pParse->checkSchema ){
94269    schemaIsValid(pParse);
94270  }
94271  if( db->mallocFailed ){
94272    pParse->rc = SQLITE_NOMEM;
94273  }
94274  if( pzTail ){
94275    *pzTail = pParse->zTail;
94276  }
94277  rc = pParse->rc;
94278
94279#ifndef SQLITE_OMIT_EXPLAIN
94280  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
94281    static const char * const azColName[] = {
94282       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
94283       "selectid", "order", "from", "detail"
94284    };
94285    int iFirst, mx;
94286    if( pParse->explain==2 ){
94287      sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
94288      iFirst = 8;
94289      mx = 12;
94290    }else{
94291      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
94292      iFirst = 0;
94293      mx = 8;
94294    }
94295    for(i=iFirst; i<mx; i++){
94296      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
94297                            azColName[i], SQLITE_STATIC);
94298    }
94299  }
94300#endif
94301
94302  assert( db->init.busy==0 || saveSqlFlag==0 );
94303  if( db->init.busy==0 ){
94304    Vdbe *pVdbe = pParse->pVdbe;
94305    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
94306  }
94307  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
94308    sqlite3VdbeFinalize(pParse->pVdbe);
94309    assert(!(*ppStmt));
94310  }else{
94311    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
94312  }
94313
94314  if( zErrMsg ){
94315    sqlite3Error(db, rc, "%s", zErrMsg);
94316    sqlite3DbFree(db, zErrMsg);
94317  }else{
94318    sqlite3Error(db, rc, 0);
94319  }
94320
94321  /* Delete any TriggerPrg structures allocated while parsing this statement. */
94322  while( pParse->pTriggerPrg ){
94323    TriggerPrg *pT = pParse->pTriggerPrg;
94324    pParse->pTriggerPrg = pT->pNext;
94325    sqlite3DbFree(db, pT);
94326  }
94327
94328end_prepare:
94329
94330  sqlite3StackFree(db, pParse);
94331  rc = sqlite3ApiExit(db, rc);
94332  assert( (rc&db->errMask)==rc );
94333  return rc;
94334}
94335static int sqlite3LockAndPrepare(
94336  sqlite3 *db,              /* Database handle. */
94337  const char *zSql,         /* UTF-8 encoded SQL statement. */
94338  int nBytes,               /* Length of zSql in bytes. */
94339  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
94340  Vdbe *pOld,               /* VM being reprepared */
94341  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94342  const char **pzTail       /* OUT: End of parsed string */
94343){
94344  int rc;
94345  assert( ppStmt!=0 );
94346  *ppStmt = 0;
94347  if( !sqlite3SafetyCheckOk(db) ){
94348    return SQLITE_MISUSE_BKPT;
94349  }
94350  sqlite3_mutex_enter(db->mutex);
94351  sqlite3BtreeEnterAll(db);
94352  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94353  if( rc==SQLITE_SCHEMA ){
94354    sqlite3_finalize(*ppStmt);
94355    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94356  }
94357  sqlite3BtreeLeaveAll(db);
94358  sqlite3_mutex_leave(db->mutex);
94359  return rc;
94360}
94361
94362/*
94363** Rerun the compilation of a statement after a schema change.
94364**
94365** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
94366** if the statement cannot be recompiled because another connection has
94367** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
94368** occurs, return SQLITE_SCHEMA.
94369*/
94370SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
94371  int rc;
94372  sqlite3_stmt *pNew;
94373  const char *zSql;
94374  sqlite3 *db;
94375
94376  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
94377  zSql = sqlite3_sql((sqlite3_stmt *)p);
94378  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
94379  db = sqlite3VdbeDb(p);
94380  assert( sqlite3_mutex_held(db->mutex) );
94381  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
94382  if( rc ){
94383    if( rc==SQLITE_NOMEM ){
94384      db->mallocFailed = 1;
94385    }
94386    assert( pNew==0 );
94387    return rc;
94388  }else{
94389    assert( pNew!=0 );
94390  }
94391  sqlite3VdbeSwap((Vdbe*)pNew, p);
94392  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
94393  sqlite3VdbeResetStepResult((Vdbe*)pNew);
94394  sqlite3VdbeFinalize((Vdbe*)pNew);
94395  return SQLITE_OK;
94396}
94397
94398
94399/*
94400** Two versions of the official API.  Legacy and new use.  In the legacy
94401** version, the original SQL text is not saved in the prepared statement
94402** and so if a schema change occurs, SQLITE_SCHEMA is returned by
94403** sqlite3_step().  In the new version, the original SQL text is retained
94404** and the statement is automatically recompiled if an schema change
94405** occurs.
94406*/
94407SQLITE_API int sqlite3_prepare(
94408  sqlite3 *db,              /* Database handle. */
94409  const char *zSql,         /* UTF-8 encoded SQL statement. */
94410  int nBytes,               /* Length of zSql in bytes. */
94411  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94412  const char **pzTail       /* OUT: End of parsed string */
94413){
94414  int rc;
94415  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
94416  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94417  return rc;
94418}
94419SQLITE_API int sqlite3_prepare_v2(
94420  sqlite3 *db,              /* Database handle. */
94421  const char *zSql,         /* UTF-8 encoded SQL statement. */
94422  int nBytes,               /* Length of zSql in bytes. */
94423  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94424  const char **pzTail       /* OUT: End of parsed string */
94425){
94426  int rc;
94427  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
94428  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94429  return rc;
94430}
94431
94432
94433#ifndef SQLITE_OMIT_UTF16
94434/*
94435** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
94436*/
94437static int sqlite3Prepare16(
94438  sqlite3 *db,              /* Database handle. */
94439  const void *zSql,         /* UTF-16 encoded SQL statement. */
94440  int nBytes,               /* Length of zSql in bytes. */
94441  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
94442  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94443  const void **pzTail       /* OUT: End of parsed string */
94444){
94445  /* This function currently works by first transforming the UTF-16
94446  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
94447  ** tricky bit is figuring out the pointer to return in *pzTail.
94448  */
94449  char *zSql8;
94450  const char *zTail8 = 0;
94451  int rc = SQLITE_OK;
94452
94453  assert( ppStmt );
94454  *ppStmt = 0;
94455  if( !sqlite3SafetyCheckOk(db) ){
94456    return SQLITE_MISUSE_BKPT;
94457  }
94458  sqlite3_mutex_enter(db->mutex);
94459  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
94460  if( zSql8 ){
94461    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
94462  }
94463
94464  if( zTail8 && pzTail ){
94465    /* If sqlite3_prepare returns a tail pointer, we calculate the
94466    ** equivalent pointer into the UTF-16 string by counting the unicode
94467    ** characters between zSql8 and zTail8, and then returning a pointer
94468    ** the same number of characters into the UTF-16 string.
94469    */
94470    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
94471    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
94472  }
94473  sqlite3DbFree(db, zSql8);
94474  rc = sqlite3ApiExit(db, rc);
94475  sqlite3_mutex_leave(db->mutex);
94476  return rc;
94477}
94478
94479/*
94480** Two versions of the official API.  Legacy and new use.  In the legacy
94481** version, the original SQL text is not saved in the prepared statement
94482** and so if a schema change occurs, SQLITE_SCHEMA is returned by
94483** sqlite3_step().  In the new version, the original SQL text is retained
94484** and the statement is automatically recompiled if an schema change
94485** occurs.
94486*/
94487SQLITE_API int sqlite3_prepare16(
94488  sqlite3 *db,              /* Database handle. */
94489  const void *zSql,         /* UTF-16 encoded SQL statement. */
94490  int nBytes,               /* Length of zSql in bytes. */
94491  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94492  const void **pzTail       /* OUT: End of parsed string */
94493){
94494  int rc;
94495  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
94496  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94497  return rc;
94498}
94499SQLITE_API int sqlite3_prepare16_v2(
94500  sqlite3 *db,              /* Database handle. */
94501  const void *zSql,         /* UTF-16 encoded SQL statement. */
94502  int nBytes,               /* Length of zSql in bytes. */
94503  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94504  const void **pzTail       /* OUT: End of parsed string */
94505){
94506  int rc;
94507  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
94508  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94509  return rc;
94510}
94511
94512#endif /* SQLITE_OMIT_UTF16 */
94513
94514/************** End of prepare.c *********************************************/
94515/************** Begin file select.c ******************************************/
94516/*
94517** 2001 September 15
94518**
94519** The author disclaims copyright to this source code.  In place of
94520** a legal notice, here is a blessing:
94521**
94522**    May you do good and not evil.
94523**    May you find forgiveness for yourself and forgive others.
94524**    May you share freely, never taking more than you give.
94525**
94526*************************************************************************
94527** This file contains C code routines that are called by the parser
94528** to handle SELECT statements in SQLite.
94529*/
94530
94531
94532/*
94533** Delete all the content of a Select structure but do not deallocate
94534** the select structure itself.
94535*/
94536static void clearSelect(sqlite3 *db, Select *p){
94537  sqlite3ExprListDelete(db, p->pEList);
94538  sqlite3SrcListDelete(db, p->pSrc);
94539  sqlite3ExprDelete(db, p->pWhere);
94540  sqlite3ExprListDelete(db, p->pGroupBy);
94541  sqlite3ExprDelete(db, p->pHaving);
94542  sqlite3ExprListDelete(db, p->pOrderBy);
94543  sqlite3SelectDelete(db, p->pPrior);
94544  sqlite3ExprDelete(db, p->pLimit);
94545  sqlite3ExprDelete(db, p->pOffset);
94546}
94547
94548/*
94549** Initialize a SelectDest structure.
94550*/
94551SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
94552  pDest->eDest = (u8)eDest;
94553  pDest->iParm = iParm;
94554  pDest->affinity = 0;
94555  pDest->iMem = 0;
94556  pDest->nMem = 0;
94557}
94558
94559
94560/*
94561** Allocate a new Select structure and return a pointer to that
94562** structure.
94563*/
94564SQLITE_PRIVATE Select *sqlite3SelectNew(
94565  Parse *pParse,        /* Parsing context */
94566  ExprList *pEList,     /* which columns to include in the result */
94567  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
94568  Expr *pWhere,         /* the WHERE clause */
94569  ExprList *pGroupBy,   /* the GROUP BY clause */
94570  Expr *pHaving,        /* the HAVING clause */
94571  ExprList *pOrderBy,   /* the ORDER BY clause */
94572  int isDistinct,       /* true if the DISTINCT keyword is present */
94573  Expr *pLimit,         /* LIMIT value.  NULL means not used */
94574  Expr *pOffset         /* OFFSET value.  NULL means no offset */
94575){
94576  Select *pNew;
94577  Select standin;
94578  sqlite3 *db = pParse->db;
94579  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
94580  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
94581  if( pNew==0 ){
94582    assert( db->mallocFailed );
94583    pNew = &standin;
94584    memset(pNew, 0, sizeof(*pNew));
94585  }
94586  if( pEList==0 ){
94587    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
94588  }
94589  pNew->pEList = pEList;
94590  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
94591  pNew->pSrc = pSrc;
94592  pNew->pWhere = pWhere;
94593  pNew->pGroupBy = pGroupBy;
94594  pNew->pHaving = pHaving;
94595  pNew->pOrderBy = pOrderBy;
94596  pNew->selFlags = isDistinct ? SF_Distinct : 0;
94597  pNew->op = TK_SELECT;
94598  pNew->pLimit = pLimit;
94599  pNew->pOffset = pOffset;
94600  assert( pOffset==0 || pLimit!=0 );
94601  pNew->addrOpenEphm[0] = -1;
94602  pNew->addrOpenEphm[1] = -1;
94603  pNew->addrOpenEphm[2] = -1;
94604  if( db->mallocFailed ) {
94605    clearSelect(db, pNew);
94606    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
94607    pNew = 0;
94608  }else{
94609    assert( pNew->pSrc!=0 || pParse->nErr>0 );
94610  }
94611  assert( pNew!=&standin );
94612  return pNew;
94613}
94614
94615/*
94616** Delete the given Select structure and all of its substructures.
94617*/
94618SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
94619  if( p ){
94620    clearSelect(db, p);
94621    sqlite3DbFree(db, p);
94622  }
94623}
94624
94625/*
94626** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
94627** type of join.  Return an integer constant that expresses that type
94628** in terms of the following bit values:
94629**
94630**     JT_INNER
94631**     JT_CROSS
94632**     JT_OUTER
94633**     JT_NATURAL
94634**     JT_LEFT
94635**     JT_RIGHT
94636**
94637** A full outer join is the combination of JT_LEFT and JT_RIGHT.
94638**
94639** If an illegal or unsupported join type is seen, then still return
94640** a join type, but put an error in the pParse structure.
94641*/
94642SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
94643  int jointype = 0;
94644  Token *apAll[3];
94645  Token *p;
94646                             /*   0123456789 123456789 123456789 123 */
94647  static const char zKeyText[] = "naturaleftouterightfullinnercross";
94648  static const struct {
94649    u8 i;        /* Beginning of keyword text in zKeyText[] */
94650    u8 nChar;    /* Length of the keyword in characters */
94651    u8 code;     /* Join type mask */
94652  } aKeyword[] = {
94653    /* natural */ { 0,  7, JT_NATURAL                },
94654    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
94655    /* outer   */ { 10, 5, JT_OUTER                  },
94656    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
94657    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
94658    /* inner   */ { 23, 5, JT_INNER                  },
94659    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
94660  };
94661  int i, j;
94662  apAll[0] = pA;
94663  apAll[1] = pB;
94664  apAll[2] = pC;
94665  for(i=0; i<3 && apAll[i]; i++){
94666    p = apAll[i];
94667    for(j=0; j<ArraySize(aKeyword); j++){
94668      if( p->n==aKeyword[j].nChar
94669          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
94670        jointype |= aKeyword[j].code;
94671        break;
94672      }
94673    }
94674    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
94675    if( j>=ArraySize(aKeyword) ){
94676      jointype |= JT_ERROR;
94677      break;
94678    }
94679  }
94680  if(
94681     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
94682     (jointype & JT_ERROR)!=0
94683  ){
94684    const char *zSp = " ";
94685    assert( pB!=0 );
94686    if( pC==0 ){ zSp++; }
94687    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
94688       "%T %T%s%T", pA, pB, zSp, pC);
94689    jointype = JT_INNER;
94690  }else if( (jointype & JT_OUTER)!=0
94691         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
94692    sqlite3ErrorMsg(pParse,
94693      "RIGHT and FULL OUTER JOINs are not currently supported");
94694    jointype = JT_INNER;
94695  }
94696  return jointype;
94697}
94698
94699/*
94700** Return the index of a column in a table.  Return -1 if the column
94701** is not contained in the table.
94702*/
94703static int columnIndex(Table *pTab, const char *zCol){
94704  int i;
94705  for(i=0; i<pTab->nCol; i++){
94706    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
94707  }
94708  return -1;
94709}
94710
94711/*
94712** Search the first N tables in pSrc, from left to right, looking for a
94713** table that has a column named zCol.
94714**
94715** When found, set *piTab and *piCol to the table index and column index
94716** of the matching column and return TRUE.
94717**
94718** If not found, return FALSE.
94719*/
94720static int tableAndColumnIndex(
94721  SrcList *pSrc,       /* Array of tables to search */
94722  int N,               /* Number of tables in pSrc->a[] to search */
94723  const char *zCol,    /* Name of the column we are looking for */
94724  int *piTab,          /* Write index of pSrc->a[] here */
94725  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
94726){
94727  int i;               /* For looping over tables in pSrc */
94728  int iCol;            /* Index of column matching zCol */
94729
94730  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
94731  for(i=0; i<N; i++){
94732    iCol = columnIndex(pSrc->a[i].pTab, zCol);
94733    if( iCol>=0 ){
94734      if( piTab ){
94735        *piTab = i;
94736        *piCol = iCol;
94737      }
94738      return 1;
94739    }
94740  }
94741  return 0;
94742}
94743
94744/*
94745** This function is used to add terms implied by JOIN syntax to the
94746** WHERE clause expression of a SELECT statement. The new term, which
94747** is ANDed with the existing WHERE clause, is of the form:
94748**
94749**    (tab1.col1 = tab2.col2)
94750**
94751** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
94752** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
94753** column iColRight of tab2.
94754*/
94755static void addWhereTerm(
94756  Parse *pParse,                  /* Parsing context */
94757  SrcList *pSrc,                  /* List of tables in FROM clause */
94758  int iLeft,                      /* Index of first table to join in pSrc */
94759  int iColLeft,                   /* Index of column in first table */
94760  int iRight,                     /* Index of second table in pSrc */
94761  int iColRight,                  /* Index of column in second table */
94762  int isOuterJoin,                /* True if this is an OUTER join */
94763  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
94764){
94765  sqlite3 *db = pParse->db;
94766  Expr *pE1;
94767  Expr *pE2;
94768  Expr *pEq;
94769
94770  assert( iLeft<iRight );
94771  assert( pSrc->nSrc>iRight );
94772  assert( pSrc->a[iLeft].pTab );
94773  assert( pSrc->a[iRight].pTab );
94774
94775  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
94776  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
94777
94778  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
94779  if( pEq && isOuterJoin ){
94780    ExprSetProperty(pEq, EP_FromJoin);
94781    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
94782    ExprSetIrreducible(pEq);
94783    pEq->iRightJoinTable = (i16)pE2->iTable;
94784  }
94785  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
94786}
94787
94788/*
94789** Set the EP_FromJoin property on all terms of the given expression.
94790** And set the Expr.iRightJoinTable to iTable for every term in the
94791** expression.
94792**
94793** The EP_FromJoin property is used on terms of an expression to tell
94794** the LEFT OUTER JOIN processing logic that this term is part of the
94795** join restriction specified in the ON or USING clause and not a part
94796** of the more general WHERE clause.  These terms are moved over to the
94797** WHERE clause during join processing but we need to remember that they
94798** originated in the ON or USING clause.
94799**
94800** The Expr.iRightJoinTable tells the WHERE clause processing that the
94801** expression depends on table iRightJoinTable even if that table is not
94802** explicitly mentioned in the expression.  That information is needed
94803** for cases like this:
94804**
94805**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
94806**
94807** The where clause needs to defer the handling of the t1.x=5
94808** term until after the t2 loop of the join.  In that way, a
94809** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
94810** defer the handling of t1.x=5, it will be processed immediately
94811** after the t1 loop and rows with t1.x!=5 will never appear in
94812** the output, which is incorrect.
94813*/
94814static void setJoinExpr(Expr *p, int iTable){
94815  while( p ){
94816    ExprSetProperty(p, EP_FromJoin);
94817    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
94818    ExprSetIrreducible(p);
94819    p->iRightJoinTable = (i16)iTable;
94820    setJoinExpr(p->pLeft, iTable);
94821    p = p->pRight;
94822  }
94823}
94824
94825/*
94826** This routine processes the join information for a SELECT statement.
94827** ON and USING clauses are converted into extra terms of the WHERE clause.
94828** NATURAL joins also create extra WHERE clause terms.
94829**
94830** The terms of a FROM clause are contained in the Select.pSrc structure.
94831** The left most table is the first entry in Select.pSrc.  The right-most
94832** table is the last entry.  The join operator is held in the entry to
94833** the left.  Thus entry 0 contains the join operator for the join between
94834** entries 0 and 1.  Any ON or USING clauses associated with the join are
94835** also attached to the left entry.
94836**
94837** This routine returns the number of errors encountered.
94838*/
94839static int sqliteProcessJoin(Parse *pParse, Select *p){
94840  SrcList *pSrc;                  /* All tables in the FROM clause */
94841  int i, j;                       /* Loop counters */
94842  struct SrcList_item *pLeft;     /* Left table being joined */
94843  struct SrcList_item *pRight;    /* Right table being joined */
94844
94845  pSrc = p->pSrc;
94846  pLeft = &pSrc->a[0];
94847  pRight = &pLeft[1];
94848  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
94849    Table *pLeftTab = pLeft->pTab;
94850    Table *pRightTab = pRight->pTab;
94851    int isOuter;
94852
94853    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
94854    isOuter = (pRight->jointype & JT_OUTER)!=0;
94855
94856    /* When the NATURAL keyword is present, add WHERE clause terms for
94857    ** every column that the two tables have in common.
94858    */
94859    if( pRight->jointype & JT_NATURAL ){
94860      if( pRight->pOn || pRight->pUsing ){
94861        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
94862           "an ON or USING clause", 0);
94863        return 1;
94864      }
94865      for(j=0; j<pRightTab->nCol; j++){
94866        char *zName;   /* Name of column in the right table */
94867        int iLeft;     /* Matching left table */
94868        int iLeftCol;  /* Matching column in the left table */
94869
94870        zName = pRightTab->aCol[j].zName;
94871        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
94872          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
94873                       isOuter, &p->pWhere);
94874        }
94875      }
94876    }
94877
94878    /* Disallow both ON and USING clauses in the same join
94879    */
94880    if( pRight->pOn && pRight->pUsing ){
94881      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
94882        "clauses in the same join");
94883      return 1;
94884    }
94885
94886    /* Add the ON clause to the end of the WHERE clause, connected by
94887    ** an AND operator.
94888    */
94889    if( pRight->pOn ){
94890      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
94891      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
94892      pRight->pOn = 0;
94893    }
94894
94895    /* Create extra terms on the WHERE clause for each column named
94896    ** in the USING clause.  Example: If the two tables to be joined are
94897    ** A and B and the USING clause names X, Y, and Z, then add this
94898    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
94899    ** Report an error if any column mentioned in the USING clause is
94900    ** not contained in both tables to be joined.
94901    */
94902    if( pRight->pUsing ){
94903      IdList *pList = pRight->pUsing;
94904      for(j=0; j<pList->nId; j++){
94905        char *zName;     /* Name of the term in the USING clause */
94906        int iLeft;       /* Table on the left with matching column name */
94907        int iLeftCol;    /* Column number of matching column on the left */
94908        int iRightCol;   /* Column number of matching column on the right */
94909
94910        zName = pList->a[j].zName;
94911        iRightCol = columnIndex(pRightTab, zName);
94912        if( iRightCol<0
94913         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
94914        ){
94915          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
94916            "not present in both tables", zName);
94917          return 1;
94918        }
94919        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
94920                     isOuter, &p->pWhere);
94921      }
94922    }
94923  }
94924  return 0;
94925}
94926
94927/*
94928** Insert code into "v" that will push the record on the top of the
94929** stack into the sorter.
94930*/
94931static void pushOntoSorter(
94932  Parse *pParse,         /* Parser context */
94933  ExprList *pOrderBy,    /* The ORDER BY clause */
94934  Select *pSelect,       /* The whole SELECT statement */
94935  int regData            /* Register holding data to be sorted */
94936){
94937  Vdbe *v = pParse->pVdbe;
94938  int nExpr = pOrderBy->nExpr;
94939  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
94940  int regRecord = sqlite3GetTempReg(pParse);
94941  int op;
94942  sqlite3ExprCacheClear(pParse);
94943  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
94944  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
94945  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
94946  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
94947  if( pSelect->selFlags & SF_UseSorter ){
94948    op = OP_SorterInsert;
94949  }else{
94950    op = OP_IdxInsert;
94951  }
94952  sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
94953  sqlite3ReleaseTempReg(pParse, regRecord);
94954  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
94955  if( pSelect->iLimit ){
94956    int addr1, addr2;
94957    int iLimit;
94958    if( pSelect->iOffset ){
94959      iLimit = pSelect->iOffset+1;
94960    }else{
94961      iLimit = pSelect->iLimit;
94962    }
94963    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
94964    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
94965    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
94966    sqlite3VdbeJumpHere(v, addr1);
94967    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
94968    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
94969    sqlite3VdbeJumpHere(v, addr2);
94970  }
94971}
94972
94973/*
94974** Add code to implement the OFFSET
94975*/
94976static void codeOffset(
94977  Vdbe *v,          /* Generate code into this VM */
94978  Select *p,        /* The SELECT statement being coded */
94979  int iContinue     /* Jump here to skip the current record */
94980){
94981  if( p->iOffset && iContinue!=0 ){
94982    int addr;
94983    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
94984    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
94985    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
94986    VdbeComment((v, "skip OFFSET records"));
94987    sqlite3VdbeJumpHere(v, addr);
94988  }
94989}
94990
94991/*
94992** Add code that will check to make sure the N registers starting at iMem
94993** form a distinct entry.  iTab is a sorting index that holds previously
94994** seen combinations of the N values.  A new entry is made in iTab
94995** if the current N values are new.
94996**
94997** A jump to addrRepeat is made and the N+1 values are popped from the
94998** stack if the top N elements are not distinct.
94999*/
95000static void codeDistinct(
95001  Parse *pParse,     /* Parsing and code generating context */
95002  int iTab,          /* A sorting index used to test for distinctness */
95003  int addrRepeat,    /* Jump to here if not distinct */
95004  int N,             /* Number of elements */
95005  int iMem           /* First element */
95006){
95007  Vdbe *v;
95008  int r1;
95009
95010  v = pParse->pVdbe;
95011  r1 = sqlite3GetTempReg(pParse);
95012  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
95013  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
95014  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
95015  sqlite3ReleaseTempReg(pParse, r1);
95016}
95017
95018#ifndef SQLITE_OMIT_SUBQUERY
95019/*
95020** Generate an error message when a SELECT is used within a subexpression
95021** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
95022** column.  We do this in a subroutine because the error used to occur
95023** in multiple places.  (The error only occurs in one place now, but we
95024** retain the subroutine to minimize code disruption.)
95025*/
95026static int checkForMultiColumnSelectError(
95027  Parse *pParse,       /* Parse context. */
95028  SelectDest *pDest,   /* Destination of SELECT results */
95029  int nExpr            /* Number of result columns returned by SELECT */
95030){
95031  int eDest = pDest->eDest;
95032  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
95033    sqlite3ErrorMsg(pParse, "only a single result allowed for "
95034       "a SELECT that is part of an expression");
95035    return 1;
95036  }else{
95037    return 0;
95038  }
95039}
95040#endif
95041
95042/*
95043** This routine generates the code for the inside of the inner loop
95044** of a SELECT.
95045**
95046** If srcTab and nColumn are both zero, then the pEList expressions
95047** are evaluated in order to get the data for this row.  If nColumn>0
95048** then data is pulled from srcTab and pEList is used only to get the
95049** datatypes for each column.
95050*/
95051static void selectInnerLoop(
95052  Parse *pParse,          /* The parser context */
95053  Select *p,              /* The complete select statement being coded */
95054  ExprList *pEList,       /* List of values being extracted */
95055  int srcTab,             /* Pull data from this table */
95056  int nColumn,            /* Number of columns in the source table */
95057  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
95058  int distinct,           /* If >=0, make sure results are distinct */
95059  SelectDest *pDest,      /* How to dispose of the results */
95060  int iContinue,          /* Jump here to continue with next row */
95061  int iBreak              /* Jump here to break out of the inner loop */
95062){
95063  Vdbe *v = pParse->pVdbe;
95064  int i;
95065  int hasDistinct;        /* True if the DISTINCT keyword is present */
95066  int regResult;              /* Start of memory holding result set */
95067  int eDest = pDest->eDest;   /* How to dispose of results */
95068  int iParm = pDest->iParm;   /* First argument to disposal method */
95069  int nResultCol;             /* Number of result columns */
95070
95071  assert( v );
95072  if( NEVER(v==0) ) return;
95073  assert( pEList!=0 );
95074  hasDistinct = distinct>=0;
95075  if( pOrderBy==0 && !hasDistinct ){
95076    codeOffset(v, p, iContinue);
95077  }
95078
95079  /* Pull the requested columns.
95080  */
95081  if( nColumn>0 ){
95082    nResultCol = nColumn;
95083  }else{
95084    nResultCol = pEList->nExpr;
95085  }
95086  if( pDest->iMem==0 ){
95087    pDest->iMem = pParse->nMem+1;
95088    pDest->nMem = nResultCol;
95089    pParse->nMem += nResultCol;
95090  }else{
95091    assert( pDest->nMem==nResultCol );
95092  }
95093  regResult = pDest->iMem;
95094  if( nColumn>0 ){
95095    for(i=0; i<nColumn; i++){
95096      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
95097    }
95098  }else if( eDest!=SRT_Exists ){
95099    /* If the destination is an EXISTS(...) expression, the actual
95100    ** values returned by the SELECT are not required.
95101    */
95102    sqlite3ExprCacheClear(pParse);
95103    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
95104  }
95105  nColumn = nResultCol;
95106
95107  /* If the DISTINCT keyword was present on the SELECT statement
95108  ** and this row has been seen before, then do not make this row
95109  ** part of the result.
95110  */
95111  if( hasDistinct ){
95112    assert( pEList!=0 );
95113    assert( pEList->nExpr==nColumn );
95114    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
95115    if( pOrderBy==0 ){
95116      codeOffset(v, p, iContinue);
95117    }
95118  }
95119
95120  switch( eDest ){
95121    /* In this mode, write each query result to the key of the temporary
95122    ** table iParm.
95123    */
95124#ifndef SQLITE_OMIT_COMPOUND_SELECT
95125    case SRT_Union: {
95126      int r1;
95127      r1 = sqlite3GetTempReg(pParse);
95128      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95129      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
95130      sqlite3ReleaseTempReg(pParse, r1);
95131      break;
95132    }
95133
95134    /* Construct a record from the query result, but instead of
95135    ** saving that record, use it as a key to delete elements from
95136    ** the temporary table iParm.
95137    */
95138    case SRT_Except: {
95139      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
95140      break;
95141    }
95142#endif
95143
95144    /* Store the result as data using a unique key.
95145    */
95146    case SRT_Table:
95147    case SRT_EphemTab: {
95148      int r1 = sqlite3GetTempReg(pParse);
95149      testcase( eDest==SRT_Table );
95150      testcase( eDest==SRT_EphemTab );
95151      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95152      if( pOrderBy ){
95153        pushOntoSorter(pParse, pOrderBy, p, r1);
95154      }else{
95155        int r2 = sqlite3GetTempReg(pParse);
95156        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
95157        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
95158        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95159        sqlite3ReleaseTempReg(pParse, r2);
95160      }
95161      sqlite3ReleaseTempReg(pParse, r1);
95162      break;
95163    }
95164
95165#ifndef SQLITE_OMIT_SUBQUERY
95166    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
95167    ** then there should be a single item on the stack.  Write this
95168    ** item into the set table with bogus data.
95169    */
95170    case SRT_Set: {
95171      assert( nColumn==1 );
95172      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
95173      if( pOrderBy ){
95174        /* At first glance you would think we could optimize out the
95175        ** ORDER BY in this case since the order of entries in the set
95176        ** does not matter.  But there might be a LIMIT clause, in which
95177        ** case the order does matter */
95178        pushOntoSorter(pParse, pOrderBy, p, regResult);
95179      }else{
95180        int r1 = sqlite3GetTempReg(pParse);
95181        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
95182        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
95183        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
95184        sqlite3ReleaseTempReg(pParse, r1);
95185      }
95186      break;
95187    }
95188
95189    /* If any row exist in the result set, record that fact and abort.
95190    */
95191    case SRT_Exists: {
95192      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
95193      /* The LIMIT clause will terminate the loop for us */
95194      break;
95195    }
95196
95197    /* If this is a scalar select that is part of an expression, then
95198    ** store the results in the appropriate memory cell and break out
95199    ** of the scan loop.
95200    */
95201    case SRT_Mem: {
95202      assert( nColumn==1 );
95203      if( pOrderBy ){
95204        pushOntoSorter(pParse, pOrderBy, p, regResult);
95205      }else{
95206        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
95207        /* The LIMIT clause will jump out of the loop for us */
95208      }
95209      break;
95210    }
95211#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
95212
95213    /* Send the data to the callback function or to a subroutine.  In the
95214    ** case of a subroutine, the subroutine itself is responsible for
95215    ** popping the data from the stack.
95216    */
95217    case SRT_Coroutine:
95218    case SRT_Output: {
95219      testcase( eDest==SRT_Coroutine );
95220      testcase( eDest==SRT_Output );
95221      if( pOrderBy ){
95222        int r1 = sqlite3GetTempReg(pParse);
95223        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95224        pushOntoSorter(pParse, pOrderBy, p, r1);
95225        sqlite3ReleaseTempReg(pParse, r1);
95226      }else if( eDest==SRT_Coroutine ){
95227        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
95228      }else{
95229        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
95230        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
95231      }
95232      break;
95233    }
95234
95235#if !defined(SQLITE_OMIT_TRIGGER)
95236    /* Discard the results.  This is used for SELECT statements inside
95237    ** the body of a TRIGGER.  The purpose of such selects is to call
95238    ** user-defined functions that have side effects.  We do not care
95239    ** about the actual results of the select.
95240    */
95241    default: {
95242      assert( eDest==SRT_Discard );
95243      break;
95244    }
95245#endif
95246  }
95247
95248  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
95249  ** there is a sorter, in which case the sorter has already limited
95250  ** the output for us.
95251  */
95252  if( pOrderBy==0 && p->iLimit ){
95253    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
95254  }
95255}
95256
95257/*
95258** Given an expression list, generate a KeyInfo structure that records
95259** the collating sequence for each expression in that expression list.
95260**
95261** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
95262** KeyInfo structure is appropriate for initializing a virtual index to
95263** implement that clause.  If the ExprList is the result set of a SELECT
95264** then the KeyInfo structure is appropriate for initializing a virtual
95265** index to implement a DISTINCT test.
95266**
95267** Space to hold the KeyInfo structure is obtain from malloc.  The calling
95268** function is responsible for seeing that this structure is eventually
95269** freed.  Add the KeyInfo structure to the P4 field of an opcode using
95270** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
95271*/
95272static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
95273  sqlite3 *db = pParse->db;
95274  int nExpr;
95275  KeyInfo *pInfo;
95276  struct ExprList_item *pItem;
95277  int i;
95278
95279  nExpr = pList->nExpr;
95280  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
95281  if( pInfo ){
95282    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
95283    pInfo->nField = (u16)nExpr;
95284    pInfo->enc = ENC(db);
95285    pInfo->db = db;
95286    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
95287      CollSeq *pColl;
95288      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
95289      if( !pColl ){
95290        pColl = db->pDfltColl;
95291      }
95292      pInfo->aColl[i] = pColl;
95293      pInfo->aSortOrder[i] = pItem->sortOrder;
95294    }
95295  }
95296  return pInfo;
95297}
95298
95299#ifndef SQLITE_OMIT_COMPOUND_SELECT
95300/*
95301** Name of the connection operator, used for error messages.
95302*/
95303static const char *selectOpName(int id){
95304  char *z;
95305  switch( id ){
95306    case TK_ALL:       z = "UNION ALL";   break;
95307    case TK_INTERSECT: z = "INTERSECT";   break;
95308    case TK_EXCEPT:    z = "EXCEPT";      break;
95309    default:           z = "UNION";       break;
95310  }
95311  return z;
95312}
95313#endif /* SQLITE_OMIT_COMPOUND_SELECT */
95314
95315#ifndef SQLITE_OMIT_EXPLAIN
95316/*
95317** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
95318** is a no-op. Otherwise, it adds a single row of output to the EQP result,
95319** where the caption is of the form:
95320**
95321**   "USE TEMP B-TREE FOR xxx"
95322**
95323** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
95324** is determined by the zUsage argument.
95325*/
95326static void explainTempTable(Parse *pParse, const char *zUsage){
95327  if( pParse->explain==2 ){
95328    Vdbe *v = pParse->pVdbe;
95329    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
95330    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95331  }
95332}
95333
95334/*
95335** Assign expression b to lvalue a. A second, no-op, version of this macro
95336** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
95337** in sqlite3Select() to assign values to structure member variables that
95338** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
95339** code with #ifndef directives.
95340*/
95341# define explainSetInteger(a, b) a = b
95342
95343#else
95344/* No-op versions of the explainXXX() functions and macros. */
95345# define explainTempTable(y,z)
95346# define explainSetInteger(y,z)
95347#endif
95348
95349#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
95350/*
95351** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
95352** is a no-op. Otherwise, it adds a single row of output to the EQP result,
95353** where the caption is of one of the two forms:
95354**
95355**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
95356**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
95357**
95358** where iSub1 and iSub2 are the integers passed as the corresponding
95359** function parameters, and op is the text representation of the parameter
95360** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
95361** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
95362** false, or the second form if it is true.
95363*/
95364static void explainComposite(
95365  Parse *pParse,                  /* Parse context */
95366  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
95367  int iSub1,                      /* Subquery id 1 */
95368  int iSub2,                      /* Subquery id 2 */
95369  int bUseTmp                     /* True if a temp table was used */
95370){
95371  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
95372  if( pParse->explain==2 ){
95373    Vdbe *v = pParse->pVdbe;
95374    char *zMsg = sqlite3MPrintf(
95375        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
95376        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
95377    );
95378    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95379  }
95380}
95381#else
95382/* No-op versions of the explainXXX() functions and macros. */
95383# define explainComposite(v,w,x,y,z)
95384#endif
95385
95386/*
95387** If the inner loop was generated using a non-null pOrderBy argument,
95388** then the results were placed in a sorter.  After the loop is terminated
95389** we need to run the sorter and output the results.  The following
95390** routine generates the code needed to do that.
95391*/
95392static void generateSortTail(
95393  Parse *pParse,    /* Parsing context */
95394  Select *p,        /* The SELECT statement */
95395  Vdbe *v,          /* Generate code into this VDBE */
95396  int nColumn,      /* Number of columns of data */
95397  SelectDest *pDest /* Write the sorted results here */
95398){
95399  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
95400  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
95401  int addr;
95402  int iTab;
95403  int pseudoTab = 0;
95404  ExprList *pOrderBy = p->pOrderBy;
95405
95406  int eDest = pDest->eDest;
95407  int iParm = pDest->iParm;
95408
95409  int regRow;
95410  int regRowid;
95411
95412  iTab = pOrderBy->iECursor;
95413  regRow = sqlite3GetTempReg(pParse);
95414  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95415    pseudoTab = pParse->nTab++;
95416    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
95417    regRowid = 0;
95418  }else{
95419    regRowid = sqlite3GetTempReg(pParse);
95420  }
95421  if( p->selFlags & SF_UseSorter ){
95422    int regSortOut = ++pParse->nMem;
95423    int ptab2 = pParse->nTab++;
95424    sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
95425    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
95426    codeOffset(v, p, addrContinue);
95427    sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
95428    sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
95429    sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95430  }else{
95431    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
95432    codeOffset(v, p, addrContinue);
95433    sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
95434  }
95435  switch( eDest ){
95436    case SRT_Table:
95437    case SRT_EphemTab: {
95438      testcase( eDest==SRT_Table );
95439      testcase( eDest==SRT_EphemTab );
95440      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
95441      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
95442      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95443      break;
95444    }
95445#ifndef SQLITE_OMIT_SUBQUERY
95446    case SRT_Set: {
95447      assert( nColumn==1 );
95448      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
95449      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
95450      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
95451      break;
95452    }
95453    case SRT_Mem: {
95454      assert( nColumn==1 );
95455      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
95456      /* The LIMIT clause will terminate the loop for us */
95457      break;
95458    }
95459#endif
95460    default: {
95461      int i;
95462      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
95463      testcase( eDest==SRT_Output );
95464      testcase( eDest==SRT_Coroutine );
95465      for(i=0; i<nColumn; i++){
95466        assert( regRow!=pDest->iMem+i );
95467        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
95468        if( i==0 ){
95469          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95470        }
95471      }
95472      if( eDest==SRT_Output ){
95473        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
95474        sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
95475      }else{
95476        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
95477      }
95478      break;
95479    }
95480  }
95481  sqlite3ReleaseTempReg(pParse, regRow);
95482  sqlite3ReleaseTempReg(pParse, regRowid);
95483
95484  /* The bottom of the loop
95485  */
95486  sqlite3VdbeResolveLabel(v, addrContinue);
95487  if( p->selFlags & SF_UseSorter ){
95488    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
95489  }else{
95490    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
95491  }
95492  sqlite3VdbeResolveLabel(v, addrBreak);
95493  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95494    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
95495  }
95496}
95497
95498/*
95499** Return a pointer to a string containing the 'declaration type' of the
95500** expression pExpr. The string may be treated as static by the caller.
95501**
95502** The declaration type is the exact datatype definition extracted from the
95503** original CREATE TABLE statement if the expression is a column. The
95504** declaration type for a ROWID field is INTEGER. Exactly when an expression
95505** is considered a column can be complex in the presence of subqueries. The
95506** result-set expression in all of the following SELECT statements is
95507** considered a column by this function.
95508**
95509**   SELECT col FROM tbl;
95510**   SELECT (SELECT col FROM tbl;
95511**   SELECT (SELECT col FROM tbl);
95512**   SELECT abc FROM (SELECT col AS abc FROM tbl);
95513**
95514** The declaration type for any expression other than a column is NULL.
95515*/
95516static const char *columnType(
95517  NameContext *pNC,
95518  Expr *pExpr,
95519  const char **pzOriginDb,
95520  const char **pzOriginTab,
95521  const char **pzOriginCol
95522){
95523  char const *zType = 0;
95524  char const *zOriginDb = 0;
95525  char const *zOriginTab = 0;
95526  char const *zOriginCol = 0;
95527  int j;
95528  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
95529
95530  switch( pExpr->op ){
95531    case TK_AGG_COLUMN:
95532    case TK_COLUMN: {
95533      /* The expression is a column. Locate the table the column is being
95534      ** extracted from in NameContext.pSrcList. This table may be real
95535      ** database table or a subquery.
95536      */
95537      Table *pTab = 0;            /* Table structure column is extracted from */
95538      Select *pS = 0;             /* Select the column is extracted from */
95539      int iCol = pExpr->iColumn;  /* Index of column in pTab */
95540      testcase( pExpr->op==TK_AGG_COLUMN );
95541      testcase( pExpr->op==TK_COLUMN );
95542      while( pNC && !pTab ){
95543        SrcList *pTabList = pNC->pSrcList;
95544        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
95545        if( j<pTabList->nSrc ){
95546          pTab = pTabList->a[j].pTab;
95547          pS = pTabList->a[j].pSelect;
95548        }else{
95549          pNC = pNC->pNext;
95550        }
95551      }
95552
95553      if( pTab==0 ){
95554        /* At one time, code such as "SELECT new.x" within a trigger would
95555        ** cause this condition to run.  Since then, we have restructured how
95556        ** trigger code is generated and so this condition is no longer
95557        ** possible. However, it can still be true for statements like
95558        ** the following:
95559        **
95560        **   CREATE TABLE t1(col INTEGER);
95561        **   SELECT (SELECT t1.col) FROM FROM t1;
95562        **
95563        ** when columnType() is called on the expression "t1.col" in the
95564        ** sub-select. In this case, set the column type to NULL, even
95565        ** though it should really be "INTEGER".
95566        **
95567        ** This is not a problem, as the column type of "t1.col" is never
95568        ** used. When columnType() is called on the expression
95569        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
95570        ** branch below.  */
95571        break;
95572      }
95573
95574      assert( pTab && pExpr->pTab==pTab );
95575      if( pS ){
95576        /* The "table" is actually a sub-select or a view in the FROM clause
95577        ** of the SELECT statement. Return the declaration type and origin
95578        ** data for the result-set column of the sub-select.
95579        */
95580        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
95581          /* If iCol is less than zero, then the expression requests the
95582          ** rowid of the sub-select or view. This expression is legal (see
95583          ** test case misc2.2.2) - it always evaluates to NULL.
95584          */
95585          NameContext sNC;
95586          Expr *p = pS->pEList->a[iCol].pExpr;
95587          sNC.pSrcList = pS->pSrc;
95588          sNC.pNext = pNC;
95589          sNC.pParse = pNC->pParse;
95590          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
95591        }
95592      }else if( ALWAYS(pTab->pSchema) ){
95593        /* A real table */
95594        assert( !pS );
95595        if( iCol<0 ) iCol = pTab->iPKey;
95596        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95597        if( iCol<0 ){
95598          zType = "INTEGER";
95599          zOriginCol = "rowid";
95600        }else{
95601          zType = pTab->aCol[iCol].zType;
95602          zOriginCol = pTab->aCol[iCol].zName;
95603        }
95604        zOriginTab = pTab->zName;
95605        if( pNC->pParse ){
95606          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
95607          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
95608        }
95609      }
95610      break;
95611    }
95612#ifndef SQLITE_OMIT_SUBQUERY
95613    case TK_SELECT: {
95614      /* The expression is a sub-select. Return the declaration type and
95615      ** origin info for the single column in the result set of the SELECT
95616      ** statement.
95617      */
95618      NameContext sNC;
95619      Select *pS = pExpr->x.pSelect;
95620      Expr *p = pS->pEList->a[0].pExpr;
95621      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
95622      sNC.pSrcList = pS->pSrc;
95623      sNC.pNext = pNC;
95624      sNC.pParse = pNC->pParse;
95625      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
95626      break;
95627    }
95628#endif
95629  }
95630
95631  if( pzOriginDb ){
95632    assert( pzOriginTab && pzOriginCol );
95633    *pzOriginDb = zOriginDb;
95634    *pzOriginTab = zOriginTab;
95635    *pzOriginCol = zOriginCol;
95636  }
95637  return zType;
95638}
95639
95640/*
95641** Generate code that will tell the VDBE the declaration types of columns
95642** in the result set.
95643*/
95644static void generateColumnTypes(
95645  Parse *pParse,      /* Parser context */
95646  SrcList *pTabList,  /* List of tables */
95647  ExprList *pEList    /* Expressions defining the result set */
95648){
95649#ifndef SQLITE_OMIT_DECLTYPE
95650  Vdbe *v = pParse->pVdbe;
95651  int i;
95652  NameContext sNC;
95653  sNC.pSrcList = pTabList;
95654  sNC.pParse = pParse;
95655  for(i=0; i<pEList->nExpr; i++){
95656    Expr *p = pEList->a[i].pExpr;
95657    const char *zType;
95658#ifdef SQLITE_ENABLE_COLUMN_METADATA
95659    const char *zOrigDb = 0;
95660    const char *zOrigTab = 0;
95661    const char *zOrigCol = 0;
95662    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
95663
95664    /* The vdbe must make its own copy of the column-type and other
95665    ** column specific strings, in case the schema is reset before this
95666    ** virtual machine is deleted.
95667    */
95668    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
95669    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
95670    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
95671#else
95672    zType = columnType(&sNC, p, 0, 0, 0);
95673#endif
95674    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
95675  }
95676#endif /* SQLITE_OMIT_DECLTYPE */
95677}
95678
95679/*
95680** Generate code that will tell the VDBE the names of columns
95681** in the result set.  This information is used to provide the
95682** azCol[] values in the callback.
95683*/
95684static void generateColumnNames(
95685  Parse *pParse,      /* Parser context */
95686  SrcList *pTabList,  /* List of tables */
95687  ExprList *pEList    /* Expressions defining the result set */
95688){
95689  Vdbe *v = pParse->pVdbe;
95690  int i, j;
95691  sqlite3 *db = pParse->db;
95692  int fullNames, shortNames;
95693
95694#ifndef SQLITE_OMIT_EXPLAIN
95695  /* If this is an EXPLAIN, skip this step */
95696  if( pParse->explain ){
95697    return;
95698  }
95699#endif
95700
95701  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
95702  pParse->colNamesSet = 1;
95703  fullNames = (db->flags & SQLITE_FullColNames)!=0;
95704  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
95705  sqlite3VdbeSetNumCols(v, pEList->nExpr);
95706  for(i=0; i<pEList->nExpr; i++){
95707    Expr *p;
95708    p = pEList->a[i].pExpr;
95709    if( NEVER(p==0) ) continue;
95710    if( pEList->a[i].zName ){
95711      char *zName = pEList->a[i].zName;
95712      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
95713    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
95714      Table *pTab;
95715      char *zCol;
95716      int iCol = p->iColumn;
95717      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
95718        if( pTabList->a[j].iCursor==p->iTable ) break;
95719      }
95720      assert( j<pTabList->nSrc );
95721      pTab = pTabList->a[j].pTab;
95722      if( iCol<0 ) iCol = pTab->iPKey;
95723      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95724      if( iCol<0 ){
95725        zCol = "rowid";
95726      }else{
95727        zCol = pTab->aCol[iCol].zName;
95728      }
95729      if( !shortNames && !fullNames ){
95730        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
95731            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
95732      }else if( fullNames ){
95733        char *zName = 0;
95734        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
95735        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
95736      }else{
95737        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
95738      }
95739    }else{
95740      sqlite3VdbeSetColName(v, i, COLNAME_NAME,
95741          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
95742    }
95743  }
95744  generateColumnTypes(pParse, pTabList, pEList);
95745}
95746
95747/*
95748** Given a an expression list (which is really the list of expressions
95749** that form the result set of a SELECT statement) compute appropriate
95750** column names for a table that would hold the expression list.
95751**
95752** All column names will be unique.
95753**
95754** Only the column names are computed.  Column.zType, Column.zColl,
95755** and other fields of Column are zeroed.
95756**
95757** Return SQLITE_OK on success.  If a memory allocation error occurs,
95758** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
95759*/
95760static int selectColumnsFromExprList(
95761  Parse *pParse,          /* Parsing context */
95762  ExprList *pEList,       /* Expr list from which to derive column names */
95763  int *pnCol,             /* Write the number of columns here */
95764  Column **paCol          /* Write the new column list here */
95765){
95766  sqlite3 *db = pParse->db;   /* Database connection */
95767  int i, j;                   /* Loop counters */
95768  int cnt;                    /* Index added to make the name unique */
95769  Column *aCol, *pCol;        /* For looping over result columns */
95770  int nCol;                   /* Number of columns in the result set */
95771  Expr *p;                    /* Expression for a single result column */
95772  char *zName;                /* Column name */
95773  int nName;                  /* Size of name in zName[] */
95774
95775  *pnCol = nCol = pEList ? pEList->nExpr : 0;
95776  aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
95777  if( aCol==0 ) return SQLITE_NOMEM;
95778  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
95779    /* Get an appropriate name for the column
95780    */
95781    p = pEList->a[i].pExpr;
95782    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
95783               || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
95784    if( (zName = pEList->a[i].zName)!=0 ){
95785      /* If the column contains an "AS <name>" phrase, use <name> as the name */
95786      zName = sqlite3DbStrDup(db, zName);
95787    }else{
95788      Expr *pColExpr = p;  /* The expression that is the result column name */
95789      Table *pTab;         /* Table associated with this expression */
95790      while( pColExpr->op==TK_DOT ){
95791        pColExpr = pColExpr->pRight;
95792        assert( pColExpr!=0 );
95793      }
95794      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
95795        /* For columns use the column name name */
95796        int iCol = pColExpr->iColumn;
95797        pTab = pColExpr->pTab;
95798        if( iCol<0 ) iCol = pTab->iPKey;
95799        zName = sqlite3MPrintf(db, "%s",
95800                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
95801      }else if( pColExpr->op==TK_ID ){
95802        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
95803        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
95804      }else{
95805        /* Use the original text of the column expression as its name */
95806        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
95807      }
95808    }
95809    if( db->mallocFailed ){
95810      sqlite3DbFree(db, zName);
95811      break;
95812    }
95813
95814    /* Make sure the column name is unique.  If the name is not unique,
95815    ** append a integer to the name so that it becomes unique.
95816    */
95817    nName = sqlite3Strlen30(zName);
95818    for(j=cnt=0; j<i; j++){
95819      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
95820        char *zNewName;
95821        zName[nName] = 0;
95822        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
95823        sqlite3DbFree(db, zName);
95824        zName = zNewName;
95825        j = -1;
95826        if( zName==0 ) break;
95827      }
95828    }
95829    pCol->zName = zName;
95830  }
95831  if( db->mallocFailed ){
95832    for(j=0; j<i; j++){
95833      sqlite3DbFree(db, aCol[j].zName);
95834    }
95835    sqlite3DbFree(db, aCol);
95836    *paCol = 0;
95837    *pnCol = 0;
95838    return SQLITE_NOMEM;
95839  }
95840  return SQLITE_OK;
95841}
95842
95843/*
95844** Add type and collation information to a column list based on
95845** a SELECT statement.
95846**
95847** The column list presumably came from selectColumnNamesFromExprList().
95848** The column list has only names, not types or collations.  This
95849** routine goes through and adds the types and collations.
95850**
95851** This routine requires that all identifiers in the SELECT
95852** statement be resolved.
95853*/
95854static void selectAddColumnTypeAndCollation(
95855  Parse *pParse,        /* Parsing contexts */
95856  int nCol,             /* Number of columns */
95857  Column *aCol,         /* List of columns */
95858  Select *pSelect       /* SELECT used to determine types and collations */
95859){
95860  sqlite3 *db = pParse->db;
95861  NameContext sNC;
95862  Column *pCol;
95863  CollSeq *pColl;
95864  int i;
95865  Expr *p;
95866  struct ExprList_item *a;
95867
95868  assert( pSelect!=0 );
95869  assert( (pSelect->selFlags & SF_Resolved)!=0 );
95870  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
95871  if( db->mallocFailed ) return;
95872  memset(&sNC, 0, sizeof(sNC));
95873  sNC.pSrcList = pSelect->pSrc;
95874  a = pSelect->pEList->a;
95875  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
95876    p = a[i].pExpr;
95877    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
95878    pCol->affinity = sqlite3ExprAffinity(p);
95879    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
95880    pColl = sqlite3ExprCollSeq(pParse, p);
95881    if( pColl ){
95882      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
95883    }
95884  }
95885}
95886
95887/*
95888** Given a SELECT statement, generate a Table structure that describes
95889** the result set of that SELECT.
95890*/
95891SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
95892  Table *pTab;
95893  sqlite3 *db = pParse->db;
95894  int savedFlags;
95895
95896  savedFlags = db->flags;
95897  db->flags &= ~SQLITE_FullColNames;
95898  db->flags |= SQLITE_ShortColNames;
95899  sqlite3SelectPrep(pParse, pSelect, 0);
95900  if( pParse->nErr ) return 0;
95901  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
95902  db->flags = savedFlags;
95903  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
95904  if( pTab==0 ){
95905    return 0;
95906  }
95907  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
95908  ** is disabled */
95909  assert( db->lookaside.bEnabled==0 );
95910  pTab->nRef = 1;
95911  pTab->zName = 0;
95912  pTab->nRowEst = 1000000;
95913  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
95914  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
95915  pTab->iPKey = -1;
95916  if( db->mallocFailed ){
95917    sqlite3DeleteTable(db, pTab);
95918    return 0;
95919  }
95920  return pTab;
95921}
95922
95923/*
95924** Get a VDBE for the given parser context.  Create a new one if necessary.
95925** If an error occurs, return NULL and leave a message in pParse.
95926*/
95927SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
95928  Vdbe *v = pParse->pVdbe;
95929  if( v==0 ){
95930    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
95931#ifndef SQLITE_OMIT_TRACE
95932    if( v ){
95933      sqlite3VdbeAddOp0(v, OP_Trace);
95934    }
95935#endif
95936  }
95937  return v;
95938}
95939
95940
95941/*
95942** Compute the iLimit and iOffset fields of the SELECT based on the
95943** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
95944** that appear in the original SQL statement after the LIMIT and OFFSET
95945** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
95946** are the integer memory register numbers for counters used to compute
95947** the limit and offset.  If there is no limit and/or offset, then
95948** iLimit and iOffset are negative.
95949**
95950** This routine changes the values of iLimit and iOffset only if
95951** a limit or offset is defined by pLimit and pOffset.  iLimit and
95952** iOffset should have been preset to appropriate default values
95953** (usually but not always -1) prior to calling this routine.
95954** Only if pLimit!=0 or pOffset!=0 do the limit registers get
95955** redefined.  The UNION ALL operator uses this property to force
95956** the reuse of the same limit and offset registers across multiple
95957** SELECT statements.
95958*/
95959static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
95960  Vdbe *v = 0;
95961  int iLimit = 0;
95962  int iOffset;
95963  int addr1, n;
95964  if( p->iLimit ) return;
95965
95966  /*
95967  ** "LIMIT -1" always shows all rows.  There is some
95968  ** contraversy about what the correct behavior should be.
95969  ** The current implementation interprets "LIMIT 0" to mean
95970  ** no rows.
95971  */
95972  sqlite3ExprCacheClear(pParse);
95973  assert( p->pOffset==0 || p->pLimit!=0 );
95974  if( p->pLimit ){
95975    p->iLimit = iLimit = ++pParse->nMem;
95976    v = sqlite3GetVdbe(pParse);
95977    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
95978    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
95979      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
95980      VdbeComment((v, "LIMIT counter"));
95981      if( n==0 ){
95982        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
95983      }else{
95984        if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
95985      }
95986    }else{
95987      sqlite3ExprCode(pParse, p->pLimit, iLimit);
95988      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
95989      VdbeComment((v, "LIMIT counter"));
95990      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
95991    }
95992    if( p->pOffset ){
95993      p->iOffset = iOffset = ++pParse->nMem;
95994      pParse->nMem++;   /* Allocate an extra register for limit+offset */
95995      sqlite3ExprCode(pParse, p->pOffset, iOffset);
95996      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
95997      VdbeComment((v, "OFFSET counter"));
95998      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
95999      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
96000      sqlite3VdbeJumpHere(v, addr1);
96001      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
96002      VdbeComment((v, "LIMIT+OFFSET"));
96003      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
96004      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
96005      sqlite3VdbeJumpHere(v, addr1);
96006    }
96007  }
96008}
96009
96010#ifndef SQLITE_OMIT_COMPOUND_SELECT
96011/*
96012** Return the appropriate collating sequence for the iCol-th column of
96013** the result set for the compound-select statement "p".  Return NULL if
96014** the column has no default collating sequence.
96015**
96016** The collating sequence for the compound select is taken from the
96017** left-most term of the select that has a collating sequence.
96018*/
96019static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
96020  CollSeq *pRet;
96021  if( p->pPrior ){
96022    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
96023  }else{
96024    pRet = 0;
96025  }
96026  assert( iCol>=0 );
96027  if( pRet==0 && iCol<p->pEList->nExpr ){
96028    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
96029  }
96030  return pRet;
96031}
96032#endif /* SQLITE_OMIT_COMPOUND_SELECT */
96033
96034/* Forward reference */
96035static int multiSelectOrderBy(
96036  Parse *pParse,        /* Parsing context */
96037  Select *p,            /* The right-most of SELECTs to be coded */
96038  SelectDest *pDest     /* What to do with query results */
96039);
96040
96041
96042#ifndef SQLITE_OMIT_COMPOUND_SELECT
96043/*
96044** This routine is called to process a compound query form from
96045** two or more separate queries using UNION, UNION ALL, EXCEPT, or
96046** INTERSECT
96047**
96048** "p" points to the right-most of the two queries.  the query on the
96049** left is p->pPrior.  The left query could also be a compound query
96050** in which case this routine will be called recursively.
96051**
96052** The results of the total query are to be written into a destination
96053** of type eDest with parameter iParm.
96054**
96055** Example 1:  Consider a three-way compound SQL statement.
96056**
96057**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
96058**
96059** This statement is parsed up as follows:
96060**
96061**     SELECT c FROM t3
96062**      |
96063**      `----->  SELECT b FROM t2
96064**                |
96065**                `------>  SELECT a FROM t1
96066**
96067** The arrows in the diagram above represent the Select.pPrior pointer.
96068** So if this routine is called with p equal to the t3 query, then
96069** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
96070**
96071** Notice that because of the way SQLite parses compound SELECTs, the
96072** individual selects always group from left to right.
96073*/
96074static int multiSelect(
96075  Parse *pParse,        /* Parsing context */
96076  Select *p,            /* The right-most of SELECTs to be coded */
96077  SelectDest *pDest     /* What to do with query results */
96078){
96079  int rc = SQLITE_OK;   /* Success code from a subroutine */
96080  Select *pPrior;       /* Another SELECT immediately to our left */
96081  Vdbe *v;              /* Generate code to this VDBE */
96082  SelectDest dest;      /* Alternative data destination */
96083  Select *pDelete = 0;  /* Chain of simple selects to delete */
96084  sqlite3 *db;          /* Database connection */
96085#ifndef SQLITE_OMIT_EXPLAIN
96086  int iSub1;            /* EQP id of left-hand query */
96087  int iSub2;            /* EQP id of right-hand query */
96088#endif
96089
96090  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
96091  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
96092  */
96093  assert( p && p->pPrior );  /* Calling function guarantees this much */
96094  db = pParse->db;
96095  pPrior = p->pPrior;
96096  assert( pPrior->pRightmost!=pPrior );
96097  assert( pPrior->pRightmost==p->pRightmost );
96098  dest = *pDest;
96099  if( pPrior->pOrderBy ){
96100    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
96101      selectOpName(p->op));
96102    rc = 1;
96103    goto multi_select_end;
96104  }
96105  if( pPrior->pLimit ){
96106    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
96107      selectOpName(p->op));
96108    rc = 1;
96109    goto multi_select_end;
96110  }
96111
96112  v = sqlite3GetVdbe(pParse);
96113  assert( v!=0 );  /* The VDBE already created by calling function */
96114
96115  /* Create the destination temporary table if necessary
96116  */
96117  if( dest.eDest==SRT_EphemTab ){
96118    assert( p->pEList );
96119    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
96120    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96121    dest.eDest = SRT_Table;
96122  }
96123
96124  /* Make sure all SELECTs in the statement have the same number of elements
96125  ** in their result sets.
96126  */
96127  assert( p->pEList && pPrior->pEList );
96128  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
96129    if( p->selFlags & SF_Values ){
96130      sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
96131    }else{
96132      sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
96133        " do not have the same number of result columns", selectOpName(p->op));
96134    }
96135    rc = 1;
96136    goto multi_select_end;
96137  }
96138
96139  /* Compound SELECTs that have an ORDER BY clause are handled separately.
96140  */
96141  if( p->pOrderBy ){
96142    return multiSelectOrderBy(pParse, p, pDest);
96143  }
96144
96145  /* Generate code for the left and right SELECT statements.
96146  */
96147  switch( p->op ){
96148    case TK_ALL: {
96149      int addr = 0;
96150      int nLimit;
96151      assert( !pPrior->pLimit );
96152      pPrior->pLimit = p->pLimit;
96153      pPrior->pOffset = p->pOffset;
96154      explainSetInteger(iSub1, pParse->iNextSelectId);
96155      rc = sqlite3Select(pParse, pPrior, &dest);
96156      p->pLimit = 0;
96157      p->pOffset = 0;
96158      if( rc ){
96159        goto multi_select_end;
96160      }
96161      p->pPrior = 0;
96162      p->iLimit = pPrior->iLimit;
96163      p->iOffset = pPrior->iOffset;
96164      if( p->iLimit ){
96165        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
96166        VdbeComment((v, "Jump ahead if LIMIT reached"));
96167      }
96168      explainSetInteger(iSub2, pParse->iNextSelectId);
96169      rc = sqlite3Select(pParse, p, &dest);
96170      testcase( rc!=SQLITE_OK );
96171      pDelete = p->pPrior;
96172      p->pPrior = pPrior;
96173      p->nSelectRow += pPrior->nSelectRow;
96174      if( pPrior->pLimit
96175       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
96176       && p->nSelectRow > (double)nLimit
96177      ){
96178        p->nSelectRow = (double)nLimit;
96179      }
96180      if( addr ){
96181        sqlite3VdbeJumpHere(v, addr);
96182      }
96183      break;
96184    }
96185    case TK_EXCEPT:
96186    case TK_UNION: {
96187      int unionTab;    /* Cursor number of the temporary table holding result */
96188      u8 op = 0;       /* One of the SRT_ operations to apply to self */
96189      int priorOp;     /* The SRT_ operation to apply to prior selects */
96190      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
96191      int addr;
96192      SelectDest uniondest;
96193
96194      testcase( p->op==TK_EXCEPT );
96195      testcase( p->op==TK_UNION );
96196      priorOp = SRT_Union;
96197      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
96198        /* We can reuse a temporary table generated by a SELECT to our
96199        ** right.
96200        */
96201        assert( p->pRightmost!=p );  /* Can only happen for leftward elements
96202                                     ** of a 3-way or more compound */
96203        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
96204        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
96205        unionTab = dest.iParm;
96206      }else{
96207        /* We will need to create our own temporary table to hold the
96208        ** intermediate results.
96209        */
96210        unionTab = pParse->nTab++;
96211        assert( p->pOrderBy==0 );
96212        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
96213        assert( p->addrOpenEphm[0] == -1 );
96214        p->addrOpenEphm[0] = addr;
96215        p->pRightmost->selFlags |= SF_UsesEphemeral;
96216        assert( p->pEList );
96217      }
96218
96219      /* Code the SELECT statements to our left
96220      */
96221      assert( !pPrior->pOrderBy );
96222      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
96223      explainSetInteger(iSub1, pParse->iNextSelectId);
96224      rc = sqlite3Select(pParse, pPrior, &uniondest);
96225      if( rc ){
96226        goto multi_select_end;
96227      }
96228
96229      /* Code the current SELECT statement
96230      */
96231      if( p->op==TK_EXCEPT ){
96232        op = SRT_Except;
96233      }else{
96234        assert( p->op==TK_UNION );
96235        op = SRT_Union;
96236      }
96237      p->pPrior = 0;
96238      pLimit = p->pLimit;
96239      p->pLimit = 0;
96240      pOffset = p->pOffset;
96241      p->pOffset = 0;
96242      uniondest.eDest = op;
96243      explainSetInteger(iSub2, pParse->iNextSelectId);
96244      rc = sqlite3Select(pParse, p, &uniondest);
96245      testcase( rc!=SQLITE_OK );
96246      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
96247      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
96248      sqlite3ExprListDelete(db, p->pOrderBy);
96249      pDelete = p->pPrior;
96250      p->pPrior = pPrior;
96251      p->pOrderBy = 0;
96252      if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
96253      sqlite3ExprDelete(db, p->pLimit);
96254      p->pLimit = pLimit;
96255      p->pOffset = pOffset;
96256      p->iLimit = 0;
96257      p->iOffset = 0;
96258
96259      /* Convert the data in the temporary table into whatever form
96260      ** it is that we currently need.
96261      */
96262      assert( unionTab==dest.iParm || dest.eDest!=priorOp );
96263      if( dest.eDest!=priorOp ){
96264        int iCont, iBreak, iStart;
96265        assert( p->pEList );
96266        if( dest.eDest==SRT_Output ){
96267          Select *pFirst = p;
96268          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96269          generateColumnNames(pParse, 0, pFirst->pEList);
96270        }
96271        iBreak = sqlite3VdbeMakeLabel(v);
96272        iCont = sqlite3VdbeMakeLabel(v);
96273        computeLimitRegisters(pParse, p, iBreak);
96274        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
96275        iStart = sqlite3VdbeCurrentAddr(v);
96276        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
96277                        0, -1, &dest, iCont, iBreak);
96278        sqlite3VdbeResolveLabel(v, iCont);
96279        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
96280        sqlite3VdbeResolveLabel(v, iBreak);
96281        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
96282      }
96283      break;
96284    }
96285    default: assert( p->op==TK_INTERSECT ); {
96286      int tab1, tab2;
96287      int iCont, iBreak, iStart;
96288      Expr *pLimit, *pOffset;
96289      int addr;
96290      SelectDest intersectdest;
96291      int r1;
96292
96293      /* INTERSECT is different from the others since it requires
96294      ** two temporary tables.  Hence it has its own case.  Begin
96295      ** by allocating the tables we will need.
96296      */
96297      tab1 = pParse->nTab++;
96298      tab2 = pParse->nTab++;
96299      assert( p->pOrderBy==0 );
96300
96301      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
96302      assert( p->addrOpenEphm[0] == -1 );
96303      p->addrOpenEphm[0] = addr;
96304      p->pRightmost->selFlags |= SF_UsesEphemeral;
96305      assert( p->pEList );
96306
96307      /* Code the SELECTs to our left into temporary table "tab1".
96308      */
96309      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
96310      explainSetInteger(iSub1, pParse->iNextSelectId);
96311      rc = sqlite3Select(pParse, pPrior, &intersectdest);
96312      if( rc ){
96313        goto multi_select_end;
96314      }
96315
96316      /* Code the current SELECT into temporary table "tab2"
96317      */
96318      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
96319      assert( p->addrOpenEphm[1] == -1 );
96320      p->addrOpenEphm[1] = addr;
96321      p->pPrior = 0;
96322      pLimit = p->pLimit;
96323      p->pLimit = 0;
96324      pOffset = p->pOffset;
96325      p->pOffset = 0;
96326      intersectdest.iParm = tab2;
96327      explainSetInteger(iSub2, pParse->iNextSelectId);
96328      rc = sqlite3Select(pParse, p, &intersectdest);
96329      testcase( rc!=SQLITE_OK );
96330      pDelete = p->pPrior;
96331      p->pPrior = pPrior;
96332      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
96333      sqlite3ExprDelete(db, p->pLimit);
96334      p->pLimit = pLimit;
96335      p->pOffset = pOffset;
96336
96337      /* Generate code to take the intersection of the two temporary
96338      ** tables.
96339      */
96340      assert( p->pEList );
96341      if( dest.eDest==SRT_Output ){
96342        Select *pFirst = p;
96343        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96344        generateColumnNames(pParse, 0, pFirst->pEList);
96345      }
96346      iBreak = sqlite3VdbeMakeLabel(v);
96347      iCont = sqlite3VdbeMakeLabel(v);
96348      computeLimitRegisters(pParse, p, iBreak);
96349      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
96350      r1 = sqlite3GetTempReg(pParse);
96351      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
96352      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
96353      sqlite3ReleaseTempReg(pParse, r1);
96354      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
96355                      0, -1, &dest, iCont, iBreak);
96356      sqlite3VdbeResolveLabel(v, iCont);
96357      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
96358      sqlite3VdbeResolveLabel(v, iBreak);
96359      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
96360      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
96361      break;
96362    }
96363  }
96364
96365  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
96366
96367  /* Compute collating sequences used by
96368  ** temporary tables needed to implement the compound select.
96369  ** Attach the KeyInfo structure to all temporary tables.
96370  **
96371  ** This section is run by the right-most SELECT statement only.
96372  ** SELECT statements to the left always skip this part.  The right-most
96373  ** SELECT might also skip this part if it has no ORDER BY clause and
96374  ** no temp tables are required.
96375  */
96376  if( p->selFlags & SF_UsesEphemeral ){
96377    int i;                        /* Loop counter */
96378    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
96379    Select *pLoop;                /* For looping through SELECT statements */
96380    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
96381    int nCol;                     /* Number of columns in result set */
96382
96383    assert( p->pRightmost==p );
96384    nCol = p->pEList->nExpr;
96385    pKeyInfo = sqlite3DbMallocZero(db,
96386                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
96387    if( !pKeyInfo ){
96388      rc = SQLITE_NOMEM;
96389      goto multi_select_end;
96390    }
96391
96392    pKeyInfo->enc = ENC(db);
96393    pKeyInfo->nField = (u16)nCol;
96394
96395    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
96396      *apColl = multiSelectCollSeq(pParse, p, i);
96397      if( 0==*apColl ){
96398        *apColl = db->pDfltColl;
96399      }
96400    }
96401
96402    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
96403      for(i=0; i<2; i++){
96404        int addr = pLoop->addrOpenEphm[i];
96405        if( addr<0 ){
96406          /* If [0] is unused then [1] is also unused.  So we can
96407          ** always safely abort as soon as the first unused slot is found */
96408          assert( pLoop->addrOpenEphm[1]<0 );
96409          break;
96410        }
96411        sqlite3VdbeChangeP2(v, addr, nCol);
96412        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
96413        pLoop->addrOpenEphm[i] = -1;
96414      }
96415    }
96416    sqlite3DbFree(db, pKeyInfo);
96417  }
96418
96419multi_select_end:
96420  pDest->iMem = dest.iMem;
96421  pDest->nMem = dest.nMem;
96422  sqlite3SelectDelete(db, pDelete);
96423  return rc;
96424}
96425#endif /* SQLITE_OMIT_COMPOUND_SELECT */
96426
96427/*
96428** Code an output subroutine for a coroutine implementation of a
96429** SELECT statment.
96430**
96431** The data to be output is contained in pIn->iMem.  There are
96432** pIn->nMem columns to be output.  pDest is where the output should
96433** be sent.
96434**
96435** regReturn is the number of the register holding the subroutine
96436** return address.
96437**
96438** If regPrev>0 then it is the first register in a vector that
96439** records the previous output.  mem[regPrev] is a flag that is false
96440** if there has been no previous output.  If regPrev>0 then code is
96441** generated to suppress duplicates.  pKeyInfo is used for comparing
96442** keys.
96443**
96444** If the LIMIT found in p->iLimit is reached, jump immediately to
96445** iBreak.
96446*/
96447static int generateOutputSubroutine(
96448  Parse *pParse,          /* Parsing context */
96449  Select *p,              /* The SELECT statement */
96450  SelectDest *pIn,        /* Coroutine supplying data */
96451  SelectDest *pDest,      /* Where to send the data */
96452  int regReturn,          /* The return address register */
96453  int regPrev,            /* Previous result register.  No uniqueness if 0 */
96454  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
96455  int p4type,             /* The p4 type for pKeyInfo */
96456  int iBreak              /* Jump here if we hit the LIMIT */
96457){
96458  Vdbe *v = pParse->pVdbe;
96459  int iContinue;
96460  int addr;
96461
96462  addr = sqlite3VdbeCurrentAddr(v);
96463  iContinue = sqlite3VdbeMakeLabel(v);
96464
96465  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
96466  */
96467  if( regPrev ){
96468    int j1, j2;
96469    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
96470    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
96471                              (char*)pKeyInfo, p4type);
96472    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
96473    sqlite3VdbeJumpHere(v, j1);
96474    sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
96475    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
96476  }
96477  if( pParse->db->mallocFailed ) return 0;
96478
96479  /* Suppress the the first OFFSET entries if there is an OFFSET clause
96480  */
96481  codeOffset(v, p, iContinue);
96482
96483  switch( pDest->eDest ){
96484    /* Store the result as data using a unique key.
96485    */
96486    case SRT_Table:
96487    case SRT_EphemTab: {
96488      int r1 = sqlite3GetTempReg(pParse);
96489      int r2 = sqlite3GetTempReg(pParse);
96490      testcase( pDest->eDest==SRT_Table );
96491      testcase( pDest->eDest==SRT_EphemTab );
96492      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
96493      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
96494      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
96495      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96496      sqlite3ReleaseTempReg(pParse, r2);
96497      sqlite3ReleaseTempReg(pParse, r1);
96498      break;
96499    }
96500
96501#ifndef SQLITE_OMIT_SUBQUERY
96502    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
96503    ** then there should be a single item on the stack.  Write this
96504    ** item into the set table with bogus data.
96505    */
96506    case SRT_Set: {
96507      int r1;
96508      assert( pIn->nMem==1 );
96509      p->affinity =
96510         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
96511      r1 = sqlite3GetTempReg(pParse);
96512      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
96513      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
96514      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
96515      sqlite3ReleaseTempReg(pParse, r1);
96516      break;
96517    }
96518
96519#if 0  /* Never occurs on an ORDER BY query */
96520    /* If any row exist in the result set, record that fact and abort.
96521    */
96522    case SRT_Exists: {
96523      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
96524      /* The LIMIT clause will terminate the loop for us */
96525      break;
96526    }
96527#endif
96528
96529    /* If this is a scalar select that is part of an expression, then
96530    ** store the results in the appropriate memory cell and break out
96531    ** of the scan loop.
96532    */
96533    case SRT_Mem: {
96534      assert( pIn->nMem==1 );
96535      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
96536      /* The LIMIT clause will jump out of the loop for us */
96537      break;
96538    }
96539#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
96540
96541    /* The results are stored in a sequence of registers
96542    ** starting at pDest->iMem.  Then the co-routine yields.
96543    */
96544    case SRT_Coroutine: {
96545      if( pDest->iMem==0 ){
96546        pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
96547        pDest->nMem = pIn->nMem;
96548      }
96549      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
96550      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
96551      break;
96552    }
96553
96554    /* If none of the above, then the result destination must be
96555    ** SRT_Output.  This routine is never called with any other
96556    ** destination other than the ones handled above or SRT_Output.
96557    **
96558    ** For SRT_Output, results are stored in a sequence of registers.
96559    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
96560    ** return the next row of result.
96561    */
96562    default: {
96563      assert( pDest->eDest==SRT_Output );
96564      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
96565      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
96566      break;
96567    }
96568  }
96569
96570  /* Jump to the end of the loop if the LIMIT is reached.
96571  */
96572  if( p->iLimit ){
96573    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
96574  }
96575
96576  /* Generate the subroutine return
96577  */
96578  sqlite3VdbeResolveLabel(v, iContinue);
96579  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
96580
96581  return addr;
96582}
96583
96584/*
96585** Alternative compound select code generator for cases when there
96586** is an ORDER BY clause.
96587**
96588** We assume a query of the following form:
96589**
96590**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
96591**
96592** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
96593** is to code both <selectA> and <selectB> with the ORDER BY clause as
96594** co-routines.  Then run the co-routines in parallel and merge the results
96595** into the output.  In addition to the two coroutines (called selectA and
96596** selectB) there are 7 subroutines:
96597**
96598**    outA:    Move the output of the selectA coroutine into the output
96599**             of the compound query.
96600**
96601**    outB:    Move the output of the selectB coroutine into the output
96602**             of the compound query.  (Only generated for UNION and
96603**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
96604**             appears only in B.)
96605**
96606**    AltB:    Called when there is data from both coroutines and A<B.
96607**
96608**    AeqB:    Called when there is data from both coroutines and A==B.
96609**
96610**    AgtB:    Called when there is data from both coroutines and A>B.
96611**
96612**    EofA:    Called when data is exhausted from selectA.
96613**
96614**    EofB:    Called when data is exhausted from selectB.
96615**
96616** The implementation of the latter five subroutines depend on which
96617** <operator> is used:
96618**
96619**
96620**             UNION ALL         UNION            EXCEPT          INTERSECT
96621**          -------------  -----------------  --------------  -----------------
96622**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
96623**
96624**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
96625**
96626**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
96627**
96628**   EofA:   outB, nextB      outB, nextB          halt             halt
96629**
96630**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
96631**
96632** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
96633** causes an immediate jump to EofA and an EOF on B following nextB causes
96634** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
96635** following nextX causes a jump to the end of the select processing.
96636**
96637** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
96638** within the output subroutine.  The regPrev register set holds the previously
96639** output value.  A comparison is made against this value and the output
96640** is skipped if the next results would be the same as the previous.
96641**
96642** The implementation plan is to implement the two coroutines and seven
96643** subroutines first, then put the control logic at the bottom.  Like this:
96644**
96645**          goto Init
96646**     coA: coroutine for left query (A)
96647**     coB: coroutine for right query (B)
96648**    outA: output one row of A
96649**    outB: output one row of B (UNION and UNION ALL only)
96650**    EofA: ...
96651**    EofB: ...
96652**    AltB: ...
96653**    AeqB: ...
96654**    AgtB: ...
96655**    Init: initialize coroutine registers
96656**          yield coA
96657**          if eof(A) goto EofA
96658**          yield coB
96659**          if eof(B) goto EofB
96660**    Cmpr: Compare A, B
96661**          Jump AltB, AeqB, AgtB
96662**     End: ...
96663**
96664** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
96665** actually called using Gosub and they do not Return.  EofA and EofB loop
96666** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
96667** and AgtB jump to either L2 or to one of EofA or EofB.
96668*/
96669#ifndef SQLITE_OMIT_COMPOUND_SELECT
96670static int multiSelectOrderBy(
96671  Parse *pParse,        /* Parsing context */
96672  Select *p,            /* The right-most of SELECTs to be coded */
96673  SelectDest *pDest     /* What to do with query results */
96674){
96675  int i, j;             /* Loop counters */
96676  Select *pPrior;       /* Another SELECT immediately to our left */
96677  Vdbe *v;              /* Generate code to this VDBE */
96678  SelectDest destA;     /* Destination for coroutine A */
96679  SelectDest destB;     /* Destination for coroutine B */
96680  int regAddrA;         /* Address register for select-A coroutine */
96681  int regEofA;          /* Flag to indicate when select-A is complete */
96682  int regAddrB;         /* Address register for select-B coroutine */
96683  int regEofB;          /* Flag to indicate when select-B is complete */
96684  int addrSelectA;      /* Address of the select-A coroutine */
96685  int addrSelectB;      /* Address of the select-B coroutine */
96686  int regOutA;          /* Address register for the output-A subroutine */
96687  int regOutB;          /* Address register for the output-B subroutine */
96688  int addrOutA;         /* Address of the output-A subroutine */
96689  int addrOutB = 0;     /* Address of the output-B subroutine */
96690  int addrEofA;         /* Address of the select-A-exhausted subroutine */
96691  int addrEofB;         /* Address of the select-B-exhausted subroutine */
96692  int addrAltB;         /* Address of the A<B subroutine */
96693  int addrAeqB;         /* Address of the A==B subroutine */
96694  int addrAgtB;         /* Address of the A>B subroutine */
96695  int regLimitA;        /* Limit register for select-A */
96696  int regLimitB;        /* Limit register for select-A */
96697  int regPrev;          /* A range of registers to hold previous output */
96698  int savedLimit;       /* Saved value of p->iLimit */
96699  int savedOffset;      /* Saved value of p->iOffset */
96700  int labelCmpr;        /* Label for the start of the merge algorithm */
96701  int labelEnd;         /* Label for the end of the overall SELECT stmt */
96702  int j1;               /* Jump instructions that get retargetted */
96703  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
96704  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
96705  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
96706  sqlite3 *db;          /* Database connection */
96707  ExprList *pOrderBy;   /* The ORDER BY clause */
96708  int nOrderBy;         /* Number of terms in the ORDER BY clause */
96709  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
96710#ifndef SQLITE_OMIT_EXPLAIN
96711  int iSub1;            /* EQP id of left-hand query */
96712  int iSub2;            /* EQP id of right-hand query */
96713#endif
96714
96715  assert( p->pOrderBy!=0 );
96716  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
96717  db = pParse->db;
96718  v = pParse->pVdbe;
96719  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
96720  labelEnd = sqlite3VdbeMakeLabel(v);
96721  labelCmpr = sqlite3VdbeMakeLabel(v);
96722
96723
96724  /* Patch up the ORDER BY clause
96725  */
96726  op = p->op;
96727  pPrior = p->pPrior;
96728  assert( pPrior->pOrderBy==0 );
96729  pOrderBy = p->pOrderBy;
96730  assert( pOrderBy );
96731  nOrderBy = pOrderBy->nExpr;
96732
96733  /* For operators other than UNION ALL we have to make sure that
96734  ** the ORDER BY clause covers every term of the result set.  Add
96735  ** terms to the ORDER BY clause as necessary.
96736  */
96737  if( op!=TK_ALL ){
96738    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
96739      struct ExprList_item *pItem;
96740      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
96741        assert( pItem->iOrderByCol>0 );
96742        if( pItem->iOrderByCol==i ) break;
96743      }
96744      if( j==nOrderBy ){
96745        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
96746        if( pNew==0 ) return SQLITE_NOMEM;
96747        pNew->flags |= EP_IntValue;
96748        pNew->u.iValue = i;
96749        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
96750        if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
96751      }
96752    }
96753  }
96754
96755  /* Compute the comparison permutation and keyinfo that is used with
96756  ** the permutation used to determine if the next
96757  ** row of results comes from selectA or selectB.  Also add explicit
96758  ** collations to the ORDER BY clause terms so that when the subqueries
96759  ** to the right and the left are evaluated, they use the correct
96760  ** collation.
96761  */
96762  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
96763  if( aPermute ){
96764    struct ExprList_item *pItem;
96765    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
96766      assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
96767      aPermute[i] = pItem->iOrderByCol - 1;
96768    }
96769    pKeyMerge =
96770      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
96771    if( pKeyMerge ){
96772      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
96773      pKeyMerge->nField = (u16)nOrderBy;
96774      pKeyMerge->enc = ENC(db);
96775      for(i=0; i<nOrderBy; i++){
96776        CollSeq *pColl;
96777        Expr *pTerm = pOrderBy->a[i].pExpr;
96778        if( pTerm->flags & EP_ExpCollate ){
96779          pColl = pTerm->pColl;
96780        }else{
96781          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
96782          pTerm->flags |= EP_ExpCollate;
96783          pTerm->pColl = pColl;
96784        }
96785        pKeyMerge->aColl[i] = pColl;
96786        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
96787      }
96788    }
96789  }else{
96790    pKeyMerge = 0;
96791  }
96792
96793  /* Reattach the ORDER BY clause to the query.
96794  */
96795  p->pOrderBy = pOrderBy;
96796  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
96797
96798  /* Allocate a range of temporary registers and the KeyInfo needed
96799  ** for the logic that removes duplicate result rows when the
96800  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
96801  */
96802  if( op==TK_ALL ){
96803    regPrev = 0;
96804  }else{
96805    int nExpr = p->pEList->nExpr;
96806    assert( nOrderBy>=nExpr || db->mallocFailed );
96807    regPrev = sqlite3GetTempRange(pParse, nExpr+1);
96808    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
96809    pKeyDup = sqlite3DbMallocZero(db,
96810                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
96811    if( pKeyDup ){
96812      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
96813      pKeyDup->nField = (u16)nExpr;
96814      pKeyDup->enc = ENC(db);
96815      for(i=0; i<nExpr; i++){
96816        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
96817        pKeyDup->aSortOrder[i] = 0;
96818      }
96819    }
96820  }
96821
96822  /* Separate the left and the right query from one another
96823  */
96824  p->pPrior = 0;
96825  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
96826  if( pPrior->pPrior==0 ){
96827    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
96828  }
96829
96830  /* Compute the limit registers */
96831  computeLimitRegisters(pParse, p, labelEnd);
96832  if( p->iLimit && op==TK_ALL ){
96833    regLimitA = ++pParse->nMem;
96834    regLimitB = ++pParse->nMem;
96835    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
96836                                  regLimitA);
96837    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
96838  }else{
96839    regLimitA = regLimitB = 0;
96840  }
96841  sqlite3ExprDelete(db, p->pLimit);
96842  p->pLimit = 0;
96843  sqlite3ExprDelete(db, p->pOffset);
96844  p->pOffset = 0;
96845
96846  regAddrA = ++pParse->nMem;
96847  regEofA = ++pParse->nMem;
96848  regAddrB = ++pParse->nMem;
96849  regEofB = ++pParse->nMem;
96850  regOutA = ++pParse->nMem;
96851  regOutB = ++pParse->nMem;
96852  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
96853  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
96854
96855  /* Jump past the various subroutines and coroutines to the main
96856  ** merge loop
96857  */
96858  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
96859  addrSelectA = sqlite3VdbeCurrentAddr(v);
96860
96861
96862  /* Generate a coroutine to evaluate the SELECT statement to the
96863  ** left of the compound operator - the "A" select.
96864  */
96865  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
96866  pPrior->iLimit = regLimitA;
96867  explainSetInteger(iSub1, pParse->iNextSelectId);
96868  sqlite3Select(pParse, pPrior, &destA);
96869  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
96870  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96871  VdbeNoopComment((v, "End coroutine for left SELECT"));
96872
96873  /* Generate a coroutine to evaluate the SELECT statement on
96874  ** the right - the "B" select
96875  */
96876  addrSelectB = sqlite3VdbeCurrentAddr(v);
96877  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
96878  savedLimit = p->iLimit;
96879  savedOffset = p->iOffset;
96880  p->iLimit = regLimitB;
96881  p->iOffset = 0;
96882  explainSetInteger(iSub2, pParse->iNextSelectId);
96883  sqlite3Select(pParse, p, &destB);
96884  p->iLimit = savedLimit;
96885  p->iOffset = savedOffset;
96886  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
96887  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
96888  VdbeNoopComment((v, "End coroutine for right SELECT"));
96889
96890  /* Generate a subroutine that outputs the current row of the A
96891  ** select as the next output row of the compound select.
96892  */
96893  VdbeNoopComment((v, "Output routine for A"));
96894  addrOutA = generateOutputSubroutine(pParse,
96895                 p, &destA, pDest, regOutA,
96896                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
96897
96898  /* Generate a subroutine that outputs the current row of the B
96899  ** select as the next output row of the compound select.
96900  */
96901  if( op==TK_ALL || op==TK_UNION ){
96902    VdbeNoopComment((v, "Output routine for B"));
96903    addrOutB = generateOutputSubroutine(pParse,
96904                 p, &destB, pDest, regOutB,
96905                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
96906  }
96907
96908  /* Generate a subroutine to run when the results from select A
96909  ** are exhausted and only data in select B remains.
96910  */
96911  VdbeNoopComment((v, "eof-A subroutine"));
96912  if( op==TK_EXCEPT || op==TK_INTERSECT ){
96913    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
96914  }else{
96915    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
96916    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
96917    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
96918    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
96919    p->nSelectRow += pPrior->nSelectRow;
96920  }
96921
96922  /* Generate a subroutine to run when the results from select B
96923  ** are exhausted and only data in select A remains.
96924  */
96925  if( op==TK_INTERSECT ){
96926    addrEofB = addrEofA;
96927    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
96928  }else{
96929    VdbeNoopComment((v, "eof-B subroutine"));
96930    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
96931    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
96932    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96933    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
96934  }
96935
96936  /* Generate code to handle the case of A<B
96937  */
96938  VdbeNoopComment((v, "A-lt-B subroutine"));
96939  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
96940  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96941  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96942  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96943
96944  /* Generate code to handle the case of A==B
96945  */
96946  if( op==TK_ALL ){
96947    addrAeqB = addrAltB;
96948  }else if( op==TK_INTERSECT ){
96949    addrAeqB = addrAltB;
96950    addrAltB++;
96951  }else{
96952    VdbeNoopComment((v, "A-eq-B subroutine"));
96953    addrAeqB =
96954    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96955    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96956    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96957  }
96958
96959  /* Generate code to handle the case of A>B
96960  */
96961  VdbeNoopComment((v, "A-gt-B subroutine"));
96962  addrAgtB = sqlite3VdbeCurrentAddr(v);
96963  if( op==TK_ALL || op==TK_UNION ){
96964    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
96965  }
96966  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
96967  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96968  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96969
96970  /* This code runs once to initialize everything.
96971  */
96972  sqlite3VdbeJumpHere(v, j1);
96973  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
96974  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
96975  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
96976  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
96977  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96978  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96979
96980  /* Implement the main merge loop
96981  */
96982  sqlite3VdbeResolveLabel(v, labelCmpr);
96983  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
96984  sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
96985                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
96986  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
96987
96988  /* Release temporary registers
96989  */
96990  if( regPrev ){
96991    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
96992  }
96993
96994  /* Jump to the this point in order to terminate the query.
96995  */
96996  sqlite3VdbeResolveLabel(v, labelEnd);
96997
96998  /* Set the number of output columns
96999  */
97000  if( pDest->eDest==SRT_Output ){
97001    Select *pFirst = pPrior;
97002    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
97003    generateColumnNames(pParse, 0, pFirst->pEList);
97004  }
97005
97006  /* Reassembly the compound query so that it will be freed correctly
97007  ** by the calling function */
97008  if( p->pPrior ){
97009    sqlite3SelectDelete(db, p->pPrior);
97010  }
97011  p->pPrior = pPrior;
97012
97013  /*** TBD:  Insert subroutine calls to close cursors on incomplete
97014  **** subqueries ****/
97015  explainComposite(pParse, p->op, iSub1, iSub2, 0);
97016  return SQLITE_OK;
97017}
97018#endif
97019
97020#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
97021/* Forward Declarations */
97022static void substExprList(sqlite3*, ExprList*, int, ExprList*);
97023static void substSelect(sqlite3*, Select *, int, ExprList *);
97024
97025/*
97026** Scan through the expression pExpr.  Replace every reference to
97027** a column in table number iTable with a copy of the iColumn-th
97028** entry in pEList.  (But leave references to the ROWID column
97029** unchanged.)
97030**
97031** This routine is part of the flattening procedure.  A subquery
97032** whose result set is defined by pEList appears as entry in the
97033** FROM clause of a SELECT such that the VDBE cursor assigned to that
97034** FORM clause entry is iTable.  This routine make the necessary
97035** changes to pExpr so that it refers directly to the source table
97036** of the subquery rather the result set of the subquery.
97037*/
97038static Expr *substExpr(
97039  sqlite3 *db,        /* Report malloc errors to this connection */
97040  Expr *pExpr,        /* Expr in which substitution occurs */
97041  int iTable,         /* Table to be substituted */
97042  ExprList *pEList    /* Substitute expressions */
97043){
97044  if( pExpr==0 ) return 0;
97045  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
97046    if( pExpr->iColumn<0 ){
97047      pExpr->op = TK_NULL;
97048    }else{
97049      Expr *pNew;
97050      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
97051      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
97052      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
97053      if( pNew && pExpr->pColl ){
97054        pNew->pColl = pExpr->pColl;
97055      }
97056      sqlite3ExprDelete(db, pExpr);
97057      pExpr = pNew;
97058    }
97059  }else{
97060    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
97061    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
97062    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
97063      substSelect(db, pExpr->x.pSelect, iTable, pEList);
97064    }else{
97065      substExprList(db, pExpr->x.pList, iTable, pEList);
97066    }
97067  }
97068  return pExpr;
97069}
97070static void substExprList(
97071  sqlite3 *db,         /* Report malloc errors here */
97072  ExprList *pList,     /* List to scan and in which to make substitutes */
97073  int iTable,          /* Table to be substituted */
97074  ExprList *pEList     /* Substitute values */
97075){
97076  int i;
97077  if( pList==0 ) return;
97078  for(i=0; i<pList->nExpr; i++){
97079    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
97080  }
97081}
97082static void substSelect(
97083  sqlite3 *db,         /* Report malloc errors here */
97084  Select *p,           /* SELECT statement in which to make substitutions */
97085  int iTable,          /* Table to be replaced */
97086  ExprList *pEList     /* Substitute values */
97087){
97088  SrcList *pSrc;
97089  struct SrcList_item *pItem;
97090  int i;
97091  if( !p ) return;
97092  substExprList(db, p->pEList, iTable, pEList);
97093  substExprList(db, p->pGroupBy, iTable, pEList);
97094  substExprList(db, p->pOrderBy, iTable, pEList);
97095  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
97096  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
97097  substSelect(db, p->pPrior, iTable, pEList);
97098  pSrc = p->pSrc;
97099  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
97100  if( ALWAYS(pSrc) ){
97101    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
97102      substSelect(db, pItem->pSelect, iTable, pEList);
97103    }
97104  }
97105}
97106#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
97107
97108#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
97109/*
97110** This routine attempts to flatten subqueries as a performance optimization.
97111** This routine returns 1 if it makes changes and 0 if no flattening occurs.
97112**
97113** To understand the concept of flattening, consider the following
97114** query:
97115**
97116**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
97117**
97118** The default way of implementing this query is to execute the
97119** subquery first and store the results in a temporary table, then
97120** run the outer query on that temporary table.  This requires two
97121** passes over the data.  Furthermore, because the temporary table
97122** has no indices, the WHERE clause on the outer query cannot be
97123** optimized.
97124**
97125** This routine attempts to rewrite queries such as the above into
97126** a single flat select, like this:
97127**
97128**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
97129**
97130** The code generated for this simpification gives the same result
97131** but only has to scan the data once.  And because indices might
97132** exist on the table t1, a complete scan of the data might be
97133** avoided.
97134**
97135** Flattening is only attempted if all of the following are true:
97136**
97137**   (1)  The subquery and the outer query do not both use aggregates.
97138**
97139**   (2)  The subquery is not an aggregate or the outer query is not a join.
97140**
97141**   (3)  The subquery is not the right operand of a left outer join
97142**        (Originally ticket #306.  Strengthened by ticket #3300)
97143**
97144**   (4)  The subquery is not DISTINCT.
97145**
97146**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
97147**        sub-queries that were excluded from this optimization. Restriction
97148**        (4) has since been expanded to exclude all DISTINCT subqueries.
97149**
97150**   (6)  The subquery does not use aggregates or the outer query is not
97151**        DISTINCT.
97152**
97153**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
97154**        A FROM clause, consider adding a FROM close with the special
97155**        table sqlite_once that consists of a single row containing a
97156**        single NULL.
97157**
97158**   (8)  The subquery does not use LIMIT or the outer query is not a join.
97159**
97160**   (9)  The subquery does not use LIMIT or the outer query does not use
97161**        aggregates.
97162**
97163**  (10)  The subquery does not use aggregates or the outer query does not
97164**        use LIMIT.
97165**
97166**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
97167**
97168**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
97169**        a separate restriction deriving from ticket #350.
97170**
97171**  (13)  The subquery and outer query do not both use LIMIT.
97172**
97173**  (14)  The subquery does not use OFFSET.
97174**
97175**  (15)  The outer query is not part of a compound select or the
97176**        subquery does not have a LIMIT clause.
97177**        (See ticket #2339 and ticket [02a8e81d44]).
97178**
97179**  (16)  The outer query is not an aggregate or the subquery does
97180**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
97181**        until we introduced the group_concat() function.
97182**
97183**  (17)  The sub-query is not a compound select, or it is a UNION ALL
97184**        compound clause made up entirely of non-aggregate queries, and
97185**        the parent query:
97186**
97187**          * is not itself part of a compound select,
97188**          * is not an aggregate or DISTINCT query, and
97189**          * is not a join
97190**
97191**        The parent and sub-query may contain WHERE clauses. Subject to
97192**        rules (11), (13) and (14), they may also contain ORDER BY,
97193**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
97194**        operator other than UNION ALL because all the other compound
97195**        operators have an implied DISTINCT which is disallowed by
97196**        restriction (4).
97197**
97198**  (18)  If the sub-query is a compound select, then all terms of the
97199**        ORDER by clause of the parent must be simple references to
97200**        columns of the sub-query.
97201**
97202**  (19)  The subquery does not use LIMIT or the outer query does not
97203**        have a WHERE clause.
97204**
97205**  (20)  If the sub-query is a compound select, then it must not use
97206**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
97207**        somewhat by saying that the terms of the ORDER BY clause must
97208**        appear as unmodified result columns in the outer query.  But we
97209**        have other optimizations in mind to deal with that case.
97210**
97211**  (21)  The subquery does not use LIMIT or the outer query is not
97212**        DISTINCT.  (See ticket [752e1646fc]).
97213**
97214** In this routine, the "p" parameter is a pointer to the outer query.
97215** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
97216** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
97217**
97218** If flattening is not attempted, this routine is a no-op and returns 0.
97219** If flattening is attempted this routine returns 1.
97220**
97221** All of the expression analysis must occur on both the outer query and
97222** the subquery before this routine runs.
97223*/
97224static int flattenSubquery(
97225  Parse *pParse,       /* Parsing context */
97226  Select *p,           /* The parent or outer SELECT statement */
97227  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
97228  int isAgg,           /* True if outer SELECT uses aggregate functions */
97229  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
97230){
97231  const char *zSavedAuthContext = pParse->zAuthContext;
97232  Select *pParent;
97233  Select *pSub;       /* The inner query or "subquery" */
97234  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
97235  SrcList *pSrc;      /* The FROM clause of the outer query */
97236  SrcList *pSubSrc;   /* The FROM clause of the subquery */
97237  ExprList *pList;    /* The result set of the outer query */
97238  int iParent;        /* VDBE cursor number of the pSub result set temp table */
97239  int i;              /* Loop counter */
97240  Expr *pWhere;                    /* The WHERE clause */
97241  struct SrcList_item *pSubitem;   /* The subquery */
97242  sqlite3 *db = pParse->db;
97243
97244  /* Check to see if flattening is permitted.  Return 0 if not.
97245  */
97246  assert( p!=0 );
97247  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
97248  if( db->flags & SQLITE_QueryFlattener ) return 0;
97249  pSrc = p->pSrc;
97250  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
97251  pSubitem = &pSrc->a[iFrom];
97252  iParent = pSubitem->iCursor;
97253  pSub = pSubitem->pSelect;
97254  assert( pSub!=0 );
97255  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
97256  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
97257  pSubSrc = pSub->pSrc;
97258  assert( pSubSrc );
97259  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
97260  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
97261  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
97262  ** became arbitrary expressions, we were forced to add restrictions (13)
97263  ** and (14). */
97264  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
97265  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
97266  if( p->pRightmost && pSub->pLimit ){
97267    return 0;                                            /* Restriction (15) */
97268  }
97269  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
97270  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
97271  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
97272     return 0;         /* Restrictions (8)(9) */
97273  }
97274  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
97275     return 0;         /* Restriction (6)  */
97276  }
97277  if( p->pOrderBy && pSub->pOrderBy ){
97278     return 0;                                           /* Restriction (11) */
97279  }
97280  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
97281  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
97282  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
97283     return 0;         /* Restriction (21) */
97284  }
97285
97286  /* OBSOLETE COMMENT 1:
97287  ** Restriction 3:  If the subquery is a join, make sure the subquery is
97288  ** not used as the right operand of an outer join.  Examples of why this
97289  ** is not allowed:
97290  **
97291  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
97292  **
97293  ** If we flatten the above, we would get
97294  **
97295  **         (t1 LEFT OUTER JOIN t2) JOIN t3
97296  **
97297  ** which is not at all the same thing.
97298  **
97299  ** OBSOLETE COMMENT 2:
97300  ** Restriction 12:  If the subquery is the right operand of a left outer
97301  ** join, make sure the subquery has no WHERE clause.
97302  ** An examples of why this is not allowed:
97303  **
97304  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
97305  **
97306  ** If we flatten the above, we would get
97307  **
97308  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
97309  **
97310  ** But the t2.x>0 test will always fail on a NULL row of t2, which
97311  ** effectively converts the OUTER JOIN into an INNER JOIN.
97312  **
97313  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
97314  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
97315  ** is fraught with danger.  Best to avoid the whole thing.  If the
97316  ** subquery is the right term of a LEFT JOIN, then do not flatten.
97317  */
97318  if( (pSubitem->jointype & JT_OUTER)!=0 ){
97319    return 0;
97320  }
97321
97322  /* Restriction 17: If the sub-query is a compound SELECT, then it must
97323  ** use only the UNION ALL operator. And none of the simple select queries
97324  ** that make up the compound SELECT are allowed to be aggregate or distinct
97325  ** queries.
97326  */
97327  if( pSub->pPrior ){
97328    if( pSub->pOrderBy ){
97329      return 0;  /* Restriction 20 */
97330    }
97331    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
97332      return 0;
97333    }
97334    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
97335      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
97336      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
97337      assert( pSub->pSrc!=0 );
97338      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
97339       || (pSub1->pPrior && pSub1->op!=TK_ALL)
97340       || pSub1->pSrc->nSrc<1
97341      ){
97342        return 0;
97343      }
97344      testcase( pSub1->pSrc->nSrc>1 );
97345    }
97346
97347    /* Restriction 18. */
97348    if( p->pOrderBy ){
97349      int ii;
97350      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
97351        if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
97352      }
97353    }
97354  }
97355
97356  /***** If we reach this point, flattening is permitted. *****/
97357
97358  /* Authorize the subquery */
97359  pParse->zAuthContext = pSubitem->zName;
97360  sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
97361  pParse->zAuthContext = zSavedAuthContext;
97362
97363  /* If the sub-query is a compound SELECT statement, then (by restrictions
97364  ** 17 and 18 above) it must be a UNION ALL and the parent query must
97365  ** be of the form:
97366  **
97367  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
97368  **
97369  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
97370  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
97371  ** OFFSET clauses and joins them to the left-hand-side of the original
97372  ** using UNION ALL operators. In this case N is the number of simple
97373  ** select statements in the compound sub-query.
97374  **
97375  ** Example:
97376  **
97377  **     SELECT a+1 FROM (
97378  **        SELECT x FROM tab
97379  **        UNION ALL
97380  **        SELECT y FROM tab
97381  **        UNION ALL
97382  **        SELECT abs(z*2) FROM tab2
97383  **     ) WHERE a!=5 ORDER BY 1
97384  **
97385  ** Transformed into:
97386  **
97387  **     SELECT x+1 FROM tab WHERE x+1!=5
97388  **     UNION ALL
97389  **     SELECT y+1 FROM tab WHERE y+1!=5
97390  **     UNION ALL
97391  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
97392  **     ORDER BY 1
97393  **
97394  ** We call this the "compound-subquery flattening".
97395  */
97396  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
97397    Select *pNew;
97398    ExprList *pOrderBy = p->pOrderBy;
97399    Expr *pLimit = p->pLimit;
97400    Select *pPrior = p->pPrior;
97401    p->pOrderBy = 0;
97402    p->pSrc = 0;
97403    p->pPrior = 0;
97404    p->pLimit = 0;
97405    pNew = sqlite3SelectDup(db, p, 0);
97406    p->pLimit = pLimit;
97407    p->pOrderBy = pOrderBy;
97408    p->pSrc = pSrc;
97409    p->op = TK_ALL;
97410    p->pRightmost = 0;
97411    if( pNew==0 ){
97412      pNew = pPrior;
97413    }else{
97414      pNew->pPrior = pPrior;
97415      pNew->pRightmost = 0;
97416    }
97417    p->pPrior = pNew;
97418    if( db->mallocFailed ) return 1;
97419  }
97420
97421  /* Begin flattening the iFrom-th entry of the FROM clause
97422  ** in the outer query.
97423  */
97424  pSub = pSub1 = pSubitem->pSelect;
97425
97426  /* Delete the transient table structure associated with the
97427  ** subquery
97428  */
97429  sqlite3DbFree(db, pSubitem->zDatabase);
97430  sqlite3DbFree(db, pSubitem->zName);
97431  sqlite3DbFree(db, pSubitem->zAlias);
97432  pSubitem->zDatabase = 0;
97433  pSubitem->zName = 0;
97434  pSubitem->zAlias = 0;
97435  pSubitem->pSelect = 0;
97436
97437  /* Defer deleting the Table object associated with the
97438  ** subquery until code generation is
97439  ** complete, since there may still exist Expr.pTab entries that
97440  ** refer to the subquery even after flattening.  Ticket #3346.
97441  **
97442  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
97443  */
97444  if( ALWAYS(pSubitem->pTab!=0) ){
97445    Table *pTabToDel = pSubitem->pTab;
97446    if( pTabToDel->nRef==1 ){
97447      Parse *pToplevel = sqlite3ParseToplevel(pParse);
97448      pTabToDel->pNextZombie = pToplevel->pZombieTab;
97449      pToplevel->pZombieTab = pTabToDel;
97450    }else{
97451      pTabToDel->nRef--;
97452    }
97453    pSubitem->pTab = 0;
97454  }
97455
97456  /* The following loop runs once for each term in a compound-subquery
97457  ** flattening (as described above).  If we are doing a different kind
97458  ** of flattening - a flattening other than a compound-subquery flattening -
97459  ** then this loop only runs once.
97460  **
97461  ** This loop moves all of the FROM elements of the subquery into the
97462  ** the FROM clause of the outer query.  Before doing this, remember
97463  ** the cursor number for the original outer query FROM element in
97464  ** iParent.  The iParent cursor will never be used.  Subsequent code
97465  ** will scan expressions looking for iParent references and replace
97466  ** those references with expressions that resolve to the subquery FROM
97467  ** elements we are now copying in.
97468  */
97469  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
97470    int nSubSrc;
97471    u8 jointype = 0;
97472    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
97473    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
97474    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
97475
97476    if( pSrc ){
97477      assert( pParent==p );  /* First time through the loop */
97478      jointype = pSubitem->jointype;
97479    }else{
97480      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
97481      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
97482      if( pSrc==0 ){
97483        assert( db->mallocFailed );
97484        break;
97485      }
97486    }
97487
97488    /* The subquery uses a single slot of the FROM clause of the outer
97489    ** query.  If the subquery has more than one element in its FROM clause,
97490    ** then expand the outer query to make space for it to hold all elements
97491    ** of the subquery.
97492    **
97493    ** Example:
97494    **
97495    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
97496    **
97497    ** The outer query has 3 slots in its FROM clause.  One slot of the
97498    ** outer query (the middle slot) is used by the subquery.  The next
97499    ** block of code will expand the out query to 4 slots.  The middle
97500    ** slot is expanded to two slots in order to make space for the
97501    ** two elements in the FROM clause of the subquery.
97502    */
97503    if( nSubSrc>1 ){
97504      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
97505      if( db->mallocFailed ){
97506        break;
97507      }
97508    }
97509
97510    /* Transfer the FROM clause terms from the subquery into the
97511    ** outer query.
97512    */
97513    for(i=0; i<nSubSrc; i++){
97514      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
97515      pSrc->a[i+iFrom] = pSubSrc->a[i];
97516      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
97517    }
97518    pSrc->a[iFrom].jointype = jointype;
97519
97520    /* Now begin substituting subquery result set expressions for
97521    ** references to the iParent in the outer query.
97522    **
97523    ** Example:
97524    **
97525    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
97526    **   \                     \_____________ subquery __________/          /
97527    **    \_____________________ outer query ______________________________/
97528    **
97529    ** We look at every expression in the outer query and every place we see
97530    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
97531    */
97532    pList = pParent->pEList;
97533    for(i=0; i<pList->nExpr; i++){
97534      if( pList->a[i].zName==0 ){
97535        const char *zSpan = pList->a[i].zSpan;
97536        if( ALWAYS(zSpan) ){
97537          pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
97538        }
97539      }
97540    }
97541    substExprList(db, pParent->pEList, iParent, pSub->pEList);
97542    if( isAgg ){
97543      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
97544      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97545    }
97546    if( pSub->pOrderBy ){
97547      assert( pParent->pOrderBy==0 );
97548      pParent->pOrderBy = pSub->pOrderBy;
97549      pSub->pOrderBy = 0;
97550    }else if( pParent->pOrderBy ){
97551      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
97552    }
97553    if( pSub->pWhere ){
97554      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
97555    }else{
97556      pWhere = 0;
97557    }
97558    if( subqueryIsAgg ){
97559      assert( pParent->pHaving==0 );
97560      pParent->pHaving = pParent->pWhere;
97561      pParent->pWhere = pWhere;
97562      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97563      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
97564                                  sqlite3ExprDup(db, pSub->pHaving, 0));
97565      assert( pParent->pGroupBy==0 );
97566      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
97567    }else{
97568      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
97569      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
97570    }
97571
97572    /* The flattened query is distinct if either the inner or the
97573    ** outer query is distinct.
97574    */
97575    pParent->selFlags |= pSub->selFlags & SF_Distinct;
97576
97577    /*
97578    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
97579    **
97580    ** One is tempted to try to add a and b to combine the limits.  But this
97581    ** does not work if either limit is negative.
97582    */
97583    if( pSub->pLimit ){
97584      pParent->pLimit = pSub->pLimit;
97585      pSub->pLimit = 0;
97586    }
97587  }
97588
97589  /* Finially, delete what is left of the subquery and return
97590  ** success.
97591  */
97592  sqlite3SelectDelete(db, pSub1);
97593
97594  return 1;
97595}
97596#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
97597
97598/*
97599** Analyze the SELECT statement passed as an argument to see if it
97600** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
97601** it is, or 0 otherwise. At present, a query is considered to be
97602** a min()/max() query if:
97603**
97604**   1. There is a single object in the FROM clause.
97605**
97606**   2. There is a single expression in the result set, and it is
97607**      either min(x) or max(x), where x is a column reference.
97608*/
97609static u8 minMaxQuery(Select *p){
97610  Expr *pExpr;
97611  ExprList *pEList = p->pEList;
97612
97613  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
97614  pExpr = pEList->a[0].pExpr;
97615  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97616  if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
97617  pEList = pExpr->x.pList;
97618  if( pEList==0 || pEList->nExpr!=1 ) return 0;
97619  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
97620  assert( !ExprHasProperty(pExpr, EP_IntValue) );
97621  if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
97622    return WHERE_ORDERBY_MIN;
97623  }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
97624    return WHERE_ORDERBY_MAX;
97625  }
97626  return WHERE_ORDERBY_NORMAL;
97627}
97628
97629/*
97630** The select statement passed as the first argument is an aggregate query.
97631** The second argment is the associated aggregate-info object. This
97632** function tests if the SELECT is of the form:
97633**
97634**   SELECT count(*) FROM <tbl>
97635**
97636** where table is a database table, not a sub-select or view. If the query
97637** does match this pattern, then a pointer to the Table object representing
97638** <tbl> is returned. Otherwise, 0 is returned.
97639*/
97640static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
97641  Table *pTab;
97642  Expr *pExpr;
97643
97644  assert( !p->pGroupBy );
97645
97646  if( p->pWhere || p->pEList->nExpr!=1
97647   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
97648  ){
97649    return 0;
97650  }
97651  pTab = p->pSrc->a[0].pTab;
97652  pExpr = p->pEList->a[0].pExpr;
97653  assert( pTab && !pTab->pSelect && pExpr );
97654
97655  if( IsVirtual(pTab) ) return 0;
97656  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97657  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
97658  if( pExpr->flags&EP_Distinct ) return 0;
97659
97660  return pTab;
97661}
97662
97663/*
97664** If the source-list item passed as an argument was augmented with an
97665** INDEXED BY clause, then try to locate the specified index. If there
97666** was such a clause and the named index cannot be found, return
97667** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
97668** pFrom->pIndex and return SQLITE_OK.
97669*/
97670SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
97671  if( pFrom->pTab && pFrom->zIndex ){
97672    Table *pTab = pFrom->pTab;
97673    char *zIndex = pFrom->zIndex;
97674    Index *pIdx;
97675    for(pIdx=pTab->pIndex;
97676        pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
97677        pIdx=pIdx->pNext
97678    );
97679    if( !pIdx ){
97680      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
97681      pParse->checkSchema = 1;
97682      return SQLITE_ERROR;
97683    }
97684    pFrom->pIndex = pIdx;
97685  }
97686  return SQLITE_OK;
97687}
97688
97689/*
97690** This routine is a Walker callback for "expanding" a SELECT statement.
97691** "Expanding" means to do the following:
97692**
97693**    (1)  Make sure VDBE cursor numbers have been assigned to every
97694**         element of the FROM clause.
97695**
97696**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
97697**         defines FROM clause.  When views appear in the FROM clause,
97698**         fill pTabList->a[].pSelect with a copy of the SELECT statement
97699**         that implements the view.  A copy is made of the view's SELECT
97700**         statement so that we can freely modify or delete that statement
97701**         without worrying about messing up the presistent representation
97702**         of the view.
97703**
97704**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
97705**         on joins and the ON and USING clause of joins.
97706**
97707**    (4)  Scan the list of columns in the result set (pEList) looking
97708**         for instances of the "*" operator or the TABLE.* operator.
97709**         If found, expand each "*" to be every column in every table
97710**         and TABLE.* to be every column in TABLE.
97711**
97712*/
97713static int selectExpander(Walker *pWalker, Select *p){
97714  Parse *pParse = pWalker->pParse;
97715  int i, j, k;
97716  SrcList *pTabList;
97717  ExprList *pEList;
97718  struct SrcList_item *pFrom;
97719  sqlite3 *db = pParse->db;
97720
97721  if( db->mallocFailed  ){
97722    return WRC_Abort;
97723  }
97724  if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
97725    return WRC_Prune;
97726  }
97727  p->selFlags |= SF_Expanded;
97728  pTabList = p->pSrc;
97729  pEList = p->pEList;
97730
97731  /* Make sure cursor numbers have been assigned to all entries in
97732  ** the FROM clause of the SELECT statement.
97733  */
97734  sqlite3SrcListAssignCursors(pParse, pTabList);
97735
97736  /* Look up every table named in the FROM clause of the select.  If
97737  ** an entry of the FROM clause is a subquery instead of a table or view,
97738  ** then create a transient table structure to describe the subquery.
97739  */
97740  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97741    Table *pTab;
97742    if( pFrom->pTab!=0 ){
97743      /* This statement has already been prepared.  There is no need
97744      ** to go further. */
97745      assert( i==0 );
97746      return WRC_Prune;
97747    }
97748    if( pFrom->zName==0 ){
97749#ifndef SQLITE_OMIT_SUBQUERY
97750      Select *pSel = pFrom->pSelect;
97751      /* A sub-query in the FROM clause of a SELECT */
97752      assert( pSel!=0 );
97753      assert( pFrom->pTab==0 );
97754      sqlite3WalkSelect(pWalker, pSel);
97755      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
97756      if( pTab==0 ) return WRC_Abort;
97757      pTab->nRef = 1;
97758      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
97759      while( pSel->pPrior ){ pSel = pSel->pPrior; }
97760      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
97761      pTab->iPKey = -1;
97762      pTab->nRowEst = 1000000;
97763      pTab->tabFlags |= TF_Ephemeral;
97764#endif
97765    }else{
97766      /* An ordinary table or view name in the FROM clause */
97767      assert( pFrom->pTab==0 );
97768      pFrom->pTab = pTab =
97769        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
97770      if( pTab==0 ) return WRC_Abort;
97771      pTab->nRef++;
97772#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
97773      if( pTab->pSelect || IsVirtual(pTab) ){
97774        /* We reach here if the named table is a really a view */
97775        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
97776        assert( pFrom->pSelect==0 );
97777        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
97778        sqlite3WalkSelect(pWalker, pFrom->pSelect);
97779      }
97780#endif
97781    }
97782
97783    /* Locate the index named by the INDEXED BY clause, if any. */
97784    if( sqlite3IndexedByLookup(pParse, pFrom) ){
97785      return WRC_Abort;
97786    }
97787  }
97788
97789  /* Process NATURAL keywords, and ON and USING clauses of joins.
97790  */
97791  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
97792    return WRC_Abort;
97793  }
97794
97795  /* For every "*" that occurs in the column list, insert the names of
97796  ** all columns in all tables.  And for every TABLE.* insert the names
97797  ** of all columns in TABLE.  The parser inserted a special expression
97798  ** with the TK_ALL operator for each "*" that it found in the column list.
97799  ** The following code just has to locate the TK_ALL expressions and expand
97800  ** each one to the list of all columns in all tables.
97801  **
97802  ** The first loop just checks to see if there are any "*" operators
97803  ** that need expanding.
97804  */
97805  for(k=0; k<pEList->nExpr; k++){
97806    Expr *pE = pEList->a[k].pExpr;
97807    if( pE->op==TK_ALL ) break;
97808    assert( pE->op!=TK_DOT || pE->pRight!=0 );
97809    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
97810    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
97811  }
97812  if( k<pEList->nExpr ){
97813    /*
97814    ** If we get here it means the result set contains one or more "*"
97815    ** operators that need to be expanded.  Loop through each expression
97816    ** in the result set and expand them one by one.
97817    */
97818    struct ExprList_item *a = pEList->a;
97819    ExprList *pNew = 0;
97820    int flags = pParse->db->flags;
97821    int longNames = (flags & SQLITE_FullColNames)!=0
97822                      && (flags & SQLITE_ShortColNames)==0;
97823
97824    for(k=0; k<pEList->nExpr; k++){
97825      Expr *pE = a[k].pExpr;
97826      assert( pE->op!=TK_DOT || pE->pRight!=0 );
97827      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
97828        /* This particular expression does not need to be expanded.
97829        */
97830        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
97831        if( pNew ){
97832          pNew->a[pNew->nExpr-1].zName = a[k].zName;
97833          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
97834          a[k].zName = 0;
97835          a[k].zSpan = 0;
97836        }
97837        a[k].pExpr = 0;
97838      }else{
97839        /* This expression is a "*" or a "TABLE.*" and needs to be
97840        ** expanded. */
97841        int tableSeen = 0;      /* Set to 1 when TABLE matches */
97842        char *zTName;            /* text of name of TABLE */
97843        if( pE->op==TK_DOT ){
97844          assert( pE->pLeft!=0 );
97845          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
97846          zTName = pE->pLeft->u.zToken;
97847        }else{
97848          zTName = 0;
97849        }
97850        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97851          Table *pTab = pFrom->pTab;
97852          char *zTabName = pFrom->zAlias;
97853          if( zTabName==0 ){
97854            zTabName = pTab->zName;
97855          }
97856          if( db->mallocFailed ) break;
97857          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
97858            continue;
97859          }
97860          tableSeen = 1;
97861          for(j=0; j<pTab->nCol; j++){
97862            Expr *pExpr, *pRight;
97863            char *zName = pTab->aCol[j].zName;
97864            char *zColname;  /* The computed column name */
97865            char *zToFree;   /* Malloced string that needs to be freed */
97866            Token sColname;  /* Computed column name as a token */
97867
97868            /* If a column is marked as 'hidden' (currently only possible
97869            ** for virtual tables), do not include it in the expanded
97870            ** result-set list.
97871            */
97872            if( IsHiddenColumn(&pTab->aCol[j]) ){
97873              assert(IsVirtual(pTab));
97874              continue;
97875            }
97876
97877            if( i>0 && zTName==0 ){
97878              if( (pFrom->jointype & JT_NATURAL)!=0
97879                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
97880              ){
97881                /* In a NATURAL join, omit the join columns from the
97882                ** table to the right of the join */
97883                continue;
97884              }
97885              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
97886                /* In a join with a USING clause, omit columns in the
97887                ** using clause from the table on the right. */
97888                continue;
97889              }
97890            }
97891            pRight = sqlite3Expr(db, TK_ID, zName);
97892            zColname = zName;
97893            zToFree = 0;
97894            if( longNames || pTabList->nSrc>1 ){
97895              Expr *pLeft;
97896              pLeft = sqlite3Expr(db, TK_ID, zTabName);
97897              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
97898              if( longNames ){
97899                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
97900                zToFree = zColname;
97901              }
97902            }else{
97903              pExpr = pRight;
97904            }
97905            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
97906            sColname.z = zColname;
97907            sColname.n = sqlite3Strlen30(zColname);
97908            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
97909            sqlite3DbFree(db, zToFree);
97910          }
97911        }
97912        if( !tableSeen ){
97913          if( zTName ){
97914            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
97915          }else{
97916            sqlite3ErrorMsg(pParse, "no tables specified");
97917          }
97918        }
97919      }
97920    }
97921    sqlite3ExprListDelete(db, pEList);
97922    p->pEList = pNew;
97923  }
97924#if SQLITE_MAX_COLUMN
97925  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
97926    sqlite3ErrorMsg(pParse, "too many columns in result set");
97927  }
97928#endif
97929  return WRC_Continue;
97930}
97931
97932/*
97933** No-op routine for the parse-tree walker.
97934**
97935** When this routine is the Walker.xExprCallback then expression trees
97936** are walked without any actions being taken at each node.  Presumably,
97937** when this routine is used for Walker.xExprCallback then
97938** Walker.xSelectCallback is set to do something useful for every
97939** subquery in the parser tree.
97940*/
97941static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
97942  UNUSED_PARAMETER2(NotUsed, NotUsed2);
97943  return WRC_Continue;
97944}
97945
97946/*
97947** This routine "expands" a SELECT statement and all of its subqueries.
97948** For additional information on what it means to "expand" a SELECT
97949** statement, see the comment on the selectExpand worker callback above.
97950**
97951** Expanding a SELECT statement is the first step in processing a
97952** SELECT statement.  The SELECT statement must be expanded before
97953** name resolution is performed.
97954**
97955** If anything goes wrong, an error message is written into pParse.
97956** The calling function can detect the problem by looking at pParse->nErr
97957** and/or pParse->db->mallocFailed.
97958*/
97959static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
97960  Walker w;
97961  w.xSelectCallback = selectExpander;
97962  w.xExprCallback = exprWalkNoop;
97963  w.pParse = pParse;
97964  sqlite3WalkSelect(&w, pSelect);
97965}
97966
97967
97968#ifndef SQLITE_OMIT_SUBQUERY
97969/*
97970** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
97971** interface.
97972**
97973** For each FROM-clause subquery, add Column.zType and Column.zColl
97974** information to the Table structure that represents the result set
97975** of that subquery.
97976**
97977** The Table structure that represents the result set was constructed
97978** by selectExpander() but the type and collation information was omitted
97979** at that point because identifiers had not yet been resolved.  This
97980** routine is called after identifier resolution.
97981*/
97982static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
97983  Parse *pParse;
97984  int i;
97985  SrcList *pTabList;
97986  struct SrcList_item *pFrom;
97987
97988  assert( p->selFlags & SF_Resolved );
97989  if( (p->selFlags & SF_HasTypeInfo)==0 ){
97990    p->selFlags |= SF_HasTypeInfo;
97991    pParse = pWalker->pParse;
97992    pTabList = p->pSrc;
97993    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97994      Table *pTab = pFrom->pTab;
97995      if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
97996        /* A sub-query in the FROM clause of a SELECT */
97997        Select *pSel = pFrom->pSelect;
97998        assert( pSel );
97999        while( pSel->pPrior ) pSel = pSel->pPrior;
98000        selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
98001      }
98002    }
98003  }
98004  return WRC_Continue;
98005}
98006#endif
98007
98008
98009/*
98010** This routine adds datatype and collating sequence information to
98011** the Table structures of all FROM-clause subqueries in a
98012** SELECT statement.
98013**
98014** Use this routine after name resolution.
98015*/
98016static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
98017#ifndef SQLITE_OMIT_SUBQUERY
98018  Walker w;
98019  w.xSelectCallback = selectAddSubqueryTypeInfo;
98020  w.xExprCallback = exprWalkNoop;
98021  w.pParse = pParse;
98022  sqlite3WalkSelect(&w, pSelect);
98023#endif
98024}
98025
98026
98027/*
98028** This routine sets of a SELECT statement for processing.  The
98029** following is accomplished:
98030**
98031**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
98032**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
98033**     *  ON and USING clauses are shifted into WHERE statements
98034**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
98035**     *  Identifiers in expression are matched to tables.
98036**
98037** This routine acts recursively on all subqueries within the SELECT.
98038*/
98039SQLITE_PRIVATE void sqlite3SelectPrep(
98040  Parse *pParse,         /* The parser context */
98041  Select *p,             /* The SELECT statement being coded. */
98042  NameContext *pOuterNC  /* Name context for container */
98043){
98044  sqlite3 *db;
98045  if( NEVER(p==0) ) return;
98046  db = pParse->db;
98047  if( p->selFlags & SF_HasTypeInfo ) return;
98048  sqlite3SelectExpand(pParse, p);
98049  if( pParse->nErr || db->mallocFailed ) return;
98050  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
98051  if( pParse->nErr || db->mallocFailed ) return;
98052  sqlite3SelectAddTypeInfo(pParse, p);
98053}
98054
98055/*
98056** Reset the aggregate accumulator.
98057**
98058** The aggregate accumulator is a set of memory cells that hold
98059** intermediate results while calculating an aggregate.  This
98060** routine simply stores NULLs in all of those memory cells.
98061*/
98062static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
98063  Vdbe *v = pParse->pVdbe;
98064  int i;
98065  struct AggInfo_func *pFunc;
98066  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
98067    return;
98068  }
98069  for(i=0; i<pAggInfo->nColumn; i++){
98070    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
98071  }
98072  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
98073    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
98074    if( pFunc->iDistinct>=0 ){
98075      Expr *pE = pFunc->pExpr;
98076      assert( !ExprHasProperty(pE, EP_xIsSelect) );
98077      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
98078        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
98079           "argument");
98080        pFunc->iDistinct = -1;
98081      }else{
98082        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
98083        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
98084                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98085      }
98086    }
98087  }
98088}
98089
98090/*
98091** Invoke the OP_AggFinalize opcode for every aggregate function
98092** in the AggInfo structure.
98093*/
98094static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
98095  Vdbe *v = pParse->pVdbe;
98096  int i;
98097  struct AggInfo_func *pF;
98098  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
98099    ExprList *pList = pF->pExpr->x.pList;
98100    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
98101    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
98102                      (void*)pF->pFunc, P4_FUNCDEF);
98103  }
98104}
98105
98106/*
98107** Update the accumulator memory cells for an aggregate based on
98108** the current cursor position.
98109*/
98110static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
98111  Vdbe *v = pParse->pVdbe;
98112  int i;
98113  int regHit = 0;
98114  int addrHitTest = 0;
98115  struct AggInfo_func *pF;
98116  struct AggInfo_col *pC;
98117
98118  pAggInfo->directMode = 1;
98119  sqlite3ExprCacheClear(pParse);
98120  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
98121    int nArg;
98122    int addrNext = 0;
98123    int regAgg;
98124    ExprList *pList = pF->pExpr->x.pList;
98125    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
98126    if( pList ){
98127      nArg = pList->nExpr;
98128      regAgg = sqlite3GetTempRange(pParse, nArg);
98129      sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
98130    }else{
98131      nArg = 0;
98132      regAgg = 0;
98133    }
98134    if( pF->iDistinct>=0 ){
98135      addrNext = sqlite3VdbeMakeLabel(v);
98136      assert( nArg==1 );
98137      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
98138    }
98139    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
98140      CollSeq *pColl = 0;
98141      struct ExprList_item *pItem;
98142      int j;
98143      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
98144      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
98145        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
98146      }
98147      if( !pColl ){
98148        pColl = pParse->db->pDfltColl;
98149      }
98150      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
98151      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
98152    }
98153    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
98154                      (void*)pF->pFunc, P4_FUNCDEF);
98155    sqlite3VdbeChangeP5(v, (u8)nArg);
98156    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
98157    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
98158    if( addrNext ){
98159      sqlite3VdbeResolveLabel(v, addrNext);
98160      sqlite3ExprCacheClear(pParse);
98161    }
98162  }
98163
98164  /* Before populating the accumulator registers, clear the column cache.
98165  ** Otherwise, if any of the required column values are already present
98166  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
98167  ** to pC->iMem. But by the time the value is used, the original register
98168  ** may have been used, invalidating the underlying buffer holding the
98169  ** text or blob value. See ticket [883034dcb5].
98170  **
98171  ** Another solution would be to change the OP_SCopy used to copy cached
98172  ** values to an OP_Copy.
98173  */
98174  if( regHit ){
98175    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
98176  }
98177  sqlite3ExprCacheClear(pParse);
98178  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
98179    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
98180  }
98181  pAggInfo->directMode = 0;
98182  sqlite3ExprCacheClear(pParse);
98183  if( addrHitTest ){
98184    sqlite3VdbeJumpHere(v, addrHitTest);
98185  }
98186}
98187
98188/*
98189** Add a single OP_Explain instruction to the VDBE to explain a simple
98190** count(*) query ("SELECT count(*) FROM pTab").
98191*/
98192#ifndef SQLITE_OMIT_EXPLAIN
98193static void explainSimpleCount(
98194  Parse *pParse,                  /* Parse context */
98195  Table *pTab,                    /* Table being queried */
98196  Index *pIdx                     /* Index used to optimize scan, or NULL */
98197){
98198  if( pParse->explain==2 ){
98199    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
98200        pTab->zName,
98201        pIdx ? "USING COVERING INDEX " : "",
98202        pIdx ? pIdx->zName : "",
98203        pTab->nRowEst
98204    );
98205    sqlite3VdbeAddOp4(
98206        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
98207    );
98208  }
98209}
98210#else
98211# define explainSimpleCount(a,b,c)
98212#endif
98213
98214/*
98215** Generate code for the SELECT statement given in the p argument.
98216**
98217** The results are distributed in various ways depending on the
98218** contents of the SelectDest structure pointed to by argument pDest
98219** as follows:
98220**
98221**     pDest->eDest    Result
98222**     ------------    -------------------------------------------
98223**     SRT_Output      Generate a row of output (using the OP_ResultRow
98224**                     opcode) for each row in the result set.
98225**
98226**     SRT_Mem         Only valid if the result is a single column.
98227**                     Store the first column of the first result row
98228**                     in register pDest->iParm then abandon the rest
98229**                     of the query.  This destination implies "LIMIT 1".
98230**
98231**     SRT_Set         The result must be a single column.  Store each
98232**                     row of result as the key in table pDest->iParm.
98233**                     Apply the affinity pDest->affinity before storing
98234**                     results.  Used to implement "IN (SELECT ...)".
98235**
98236**     SRT_Union       Store results as a key in a temporary table pDest->iParm.
98237**
98238**     SRT_Except      Remove results from the temporary table pDest->iParm.
98239**
98240**     SRT_Table       Store results in temporary table pDest->iParm.
98241**                     This is like SRT_EphemTab except that the table
98242**                     is assumed to already be open.
98243**
98244**     SRT_EphemTab    Create an temporary table pDest->iParm and store
98245**                     the result there. The cursor is left open after
98246**                     returning.  This is like SRT_Table except that
98247**                     this destination uses OP_OpenEphemeral to create
98248**                     the table first.
98249**
98250**     SRT_Coroutine   Generate a co-routine that returns a new row of
98251**                     results each time it is invoked.  The entry point
98252**                     of the co-routine is stored in register pDest->iParm.
98253**
98254**     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
98255**                     set is not empty.
98256**
98257**     SRT_Discard     Throw the results away.  This is used by SELECT
98258**                     statements within triggers whose only purpose is
98259**                     the side-effects of functions.
98260**
98261** This routine returns the number of errors.  If any errors are
98262** encountered, then an appropriate error message is left in
98263** pParse->zErrMsg.
98264**
98265** This routine does NOT free the Select structure passed in.  The
98266** calling function needs to do that.
98267*/
98268SQLITE_PRIVATE int sqlite3Select(
98269  Parse *pParse,         /* The parser context */
98270  Select *p,             /* The SELECT statement being coded. */
98271  SelectDest *pDest      /* What to do with the query results */
98272){
98273  int i, j;              /* Loop counters */
98274  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
98275  Vdbe *v;               /* The virtual machine under construction */
98276  int isAgg;             /* True for select lists like "count(*)" */
98277  ExprList *pEList;      /* List of columns to extract. */
98278  SrcList *pTabList;     /* List of tables to select from */
98279  Expr *pWhere;          /* The WHERE clause.  May be NULL */
98280  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
98281  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
98282  Expr *pHaving;         /* The HAVING clause.  May be NULL */
98283  int isDistinct;        /* True if the DISTINCT keyword is present */
98284  int distinct;          /* Table to use for the distinct set */
98285  int rc = 1;            /* Value to return from this function */
98286  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
98287  int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */
98288  AggInfo sAggInfo;      /* Information used by aggregate queries */
98289  int iEnd;              /* Address of the end of the query */
98290  sqlite3 *db;           /* The database connection */
98291
98292#ifndef SQLITE_OMIT_EXPLAIN
98293  int iRestoreSelectId = pParse->iSelectId;
98294  pParse->iSelectId = pParse->iNextSelectId++;
98295#endif
98296
98297  db = pParse->db;
98298  if( p==0 || db->mallocFailed || pParse->nErr ){
98299    return 1;
98300  }
98301  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
98302  memset(&sAggInfo, 0, sizeof(sAggInfo));
98303
98304  if( IgnorableOrderby(pDest) ){
98305    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
98306           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
98307    /* If ORDER BY makes no difference in the output then neither does
98308    ** DISTINCT so it can be removed too. */
98309    sqlite3ExprListDelete(db, p->pOrderBy);
98310    p->pOrderBy = 0;
98311    p->selFlags &= ~SF_Distinct;
98312  }
98313  sqlite3SelectPrep(pParse, p, 0);
98314  pOrderBy = p->pOrderBy;
98315  pTabList = p->pSrc;
98316  pEList = p->pEList;
98317  if( pParse->nErr || db->mallocFailed ){
98318    goto select_end;
98319  }
98320  isAgg = (p->selFlags & SF_Aggregate)!=0;
98321  assert( pEList!=0 );
98322
98323  /* Begin generating code.
98324  */
98325  v = sqlite3GetVdbe(pParse);
98326  if( v==0 ) goto select_end;
98327
98328  /* If writing to memory or generating a set
98329  ** only a single column may be output.
98330  */
98331#ifndef SQLITE_OMIT_SUBQUERY
98332  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
98333    goto select_end;
98334  }
98335#endif
98336
98337  /* Generate code for all sub-queries in the FROM clause
98338  */
98339#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98340  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
98341    struct SrcList_item *pItem = &pTabList->a[i];
98342    SelectDest dest;
98343    Select *pSub = pItem->pSelect;
98344    int isAggSub;
98345
98346    if( pSub==0 ) continue;
98347    if( pItem->addrFillSub ){
98348      sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
98349      continue;
98350    }
98351
98352    /* Increment Parse.nHeight by the height of the largest expression
98353    ** tree refered to by this, the parent select. The child select
98354    ** may contain expression trees of at most
98355    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
98356    ** more conservative than necessary, but much easier than enforcing
98357    ** an exact limit.
98358    */
98359    pParse->nHeight += sqlite3SelectExprHeight(p);
98360
98361    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
98362    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
98363      /* This subquery can be absorbed into its parent. */
98364      if( isAggSub ){
98365        isAgg = 1;
98366        p->selFlags |= SF_Aggregate;
98367      }
98368      i = -1;
98369    }else{
98370      /* Generate a subroutine that will fill an ephemeral table with
98371      ** the content of this subquery.  pItem->addrFillSub will point
98372      ** to the address of the generated subroutine.  pItem->regReturn
98373      ** is a register allocated to hold the subroutine return address
98374      */
98375      int topAddr;
98376      int onceAddr = 0;
98377      int retAddr;
98378      assert( pItem->addrFillSub==0 );
98379      pItem->regReturn = ++pParse->nMem;
98380      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
98381      pItem->addrFillSub = topAddr+1;
98382      VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
98383      if( pItem->isCorrelated==0 ){
98384        /* If the subquery is no correlated and if we are not inside of
98385        ** a trigger, then we only need to compute the value of the subquery
98386        ** once. */
98387        onceAddr = sqlite3CodeOnce(pParse);
98388      }
98389      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
98390      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
98391      sqlite3Select(pParse, pSub, &dest);
98392      pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
98393      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
98394      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
98395      VdbeComment((v, "end %s", pItem->pTab->zName));
98396      sqlite3VdbeChangeP1(v, topAddr, retAddr);
98397      sqlite3ClearTempRegCache(pParse);
98398    }
98399    if( /*pParse->nErr ||*/ db->mallocFailed ){
98400      goto select_end;
98401    }
98402    pParse->nHeight -= sqlite3SelectExprHeight(p);
98403    pTabList = p->pSrc;
98404    if( !IgnorableOrderby(pDest) ){
98405      pOrderBy = p->pOrderBy;
98406    }
98407  }
98408  pEList = p->pEList;
98409#endif
98410  pWhere = p->pWhere;
98411  pGroupBy = p->pGroupBy;
98412  pHaving = p->pHaving;
98413  isDistinct = (p->selFlags & SF_Distinct)!=0;
98414
98415#ifndef SQLITE_OMIT_COMPOUND_SELECT
98416  /* If there is are a sequence of queries, do the earlier ones first.
98417  */
98418  if( p->pPrior ){
98419    if( p->pRightmost==0 ){
98420      Select *pLoop, *pRight = 0;
98421      int cnt = 0;
98422      int mxSelect;
98423      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
98424        pLoop->pRightmost = p;
98425        pLoop->pNext = pRight;
98426        pRight = pLoop;
98427      }
98428      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
98429      if( mxSelect && cnt>mxSelect ){
98430        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
98431        goto select_end;
98432      }
98433    }
98434    rc = multiSelect(pParse, p, pDest);
98435    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
98436    return rc;
98437  }
98438#endif
98439
98440  /* If there is both a GROUP BY and an ORDER BY clause and they are
98441  ** identical, then disable the ORDER BY clause since the GROUP BY
98442  ** will cause elements to come out in the correct order.  This is
98443  ** an optimization - the correct answer should result regardless.
98444  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
98445  ** to disable this optimization for testing purposes.
98446  */
98447  if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
98448         && (db->flags & SQLITE_GroupByOrder)==0 ){
98449    pOrderBy = 0;
98450  }
98451
98452  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
98453  ** if the select-list is the same as the ORDER BY list, then this query
98454  ** can be rewritten as a GROUP BY. In other words, this:
98455  **
98456  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
98457  **
98458  ** is transformed to:
98459  **
98460  **     SELECT xyz FROM ... GROUP BY xyz
98461  **
98462  ** The second form is preferred as a single index (or temp-table) may be
98463  ** used for both the ORDER BY and DISTINCT processing. As originally
98464  ** written the query must use a temp-table for at least one of the ORDER
98465  ** BY and DISTINCT, and an index or separate temp-table for the other.
98466  */
98467  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
98468   && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
98469  ){
98470    p->selFlags &= ~SF_Distinct;
98471    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
98472    pGroupBy = p->pGroupBy;
98473    pOrderBy = 0;
98474  }
98475
98476  /* If there is an ORDER BY clause, then this sorting
98477  ** index might end up being unused if the data can be
98478  ** extracted in pre-sorted order.  If that is the case, then the
98479  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
98480  ** we figure out that the sorting index is not needed.  The addrSortIndex
98481  ** variable is used to facilitate that change.
98482  */
98483  if( pOrderBy ){
98484    KeyInfo *pKeyInfo;
98485    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
98486    pOrderBy->iECursor = pParse->nTab++;
98487    p->addrOpenEphm[2] = addrSortIndex =
98488      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
98489                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
98490                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98491  }else{
98492    addrSortIndex = -1;
98493  }
98494
98495  /* If the output is destined for a temporary table, open that table.
98496  */
98497  if( pDest->eDest==SRT_EphemTab ){
98498    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
98499  }
98500
98501  /* Set the limiter.
98502  */
98503  iEnd = sqlite3VdbeMakeLabel(v);
98504  p->nSelectRow = (double)LARGEST_INT64;
98505  computeLimitRegisters(pParse, p, iEnd);
98506  if( p->iLimit==0 && addrSortIndex>=0 ){
98507    sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
98508    p->selFlags |= SF_UseSorter;
98509  }
98510
98511  /* Open a virtual index to use for the distinct set.
98512  */
98513  if( p->selFlags & SF_Distinct ){
98514    KeyInfo *pKeyInfo;
98515    distinct = pParse->nTab++;
98516    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
98517    addrDistinctIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
98518        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98519    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
98520  }else{
98521    distinct = addrDistinctIndex = -1;
98522  }
98523
98524  /* Aggregate and non-aggregate queries are handled differently */
98525  if( !isAgg && pGroupBy==0 ){
98526    ExprList *pDist = (isDistinct ? p->pEList : 0);
98527
98528    /* Begin the database scan. */
98529    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0);
98530    if( pWInfo==0 ) goto select_end;
98531    if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
98532
98533    /* If sorting index that was created by a prior OP_OpenEphemeral
98534    ** instruction ended up not being needed, then change the OP_OpenEphemeral
98535    ** into an OP_Noop.
98536    */
98537    if( addrSortIndex>=0 && pOrderBy==0 ){
98538      sqlite3VdbeChangeToNoop(v, addrSortIndex);
98539      p->addrOpenEphm[2] = -1;
98540    }
98541
98542    if( pWInfo->eDistinct ){
98543      VdbeOp *pOp;                /* No longer required OpenEphemeral instr. */
98544
98545      assert( addrDistinctIndex>=0 );
98546      pOp = sqlite3VdbeGetOp(v, addrDistinctIndex);
98547
98548      assert( isDistinct );
98549      assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
98550           || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE
98551      );
98552      distinct = -1;
98553      if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){
98554        int iJump;
98555        int iExpr;
98556        int iFlag = ++pParse->nMem;
98557        int iBase = pParse->nMem+1;
98558        int iBase2 = iBase + pEList->nExpr;
98559        pParse->nMem += (pEList->nExpr*2);
98560
98561        /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The
98562        ** OP_Integer initializes the "first row" flag.  */
98563        pOp->opcode = OP_Integer;
98564        pOp->p1 = 1;
98565        pOp->p2 = iFlag;
98566
98567        sqlite3ExprCodeExprList(pParse, pEList, iBase, 1);
98568        iJump = sqlite3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1;
98569        sqlite3VdbeAddOp2(v, OP_If, iFlag, iJump-1);
98570        for(iExpr=0; iExpr<pEList->nExpr; iExpr++){
98571          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[iExpr].pExpr);
98572          sqlite3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr);
98573          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
98574          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
98575        }
98576        sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue);
98577
98578        sqlite3VdbeAddOp2(v, OP_Integer, 0, iFlag);
98579        assert( sqlite3VdbeCurrentAddr(v)==iJump );
98580        sqlite3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr);
98581      }else{
98582        pOp->opcode = OP_Noop;
98583      }
98584    }
98585
98586    /* Use the standard inner loop. */
98587    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest,
98588                    pWInfo->iContinue, pWInfo->iBreak);
98589
98590    /* End the database scan loop.
98591    */
98592    sqlite3WhereEnd(pWInfo);
98593  }else{
98594    /* This is the processing for aggregate queries */
98595    NameContext sNC;    /* Name context for processing aggregate information */
98596    int iAMem;          /* First Mem address for storing current GROUP BY */
98597    int iBMem;          /* First Mem address for previous GROUP BY */
98598    int iUseFlag;       /* Mem address holding flag indicating that at least
98599                        ** one row of the input to the aggregator has been
98600                        ** processed */
98601    int iAbortFlag;     /* Mem address which causes query abort if positive */
98602    int groupBySort;    /* Rows come from source in GROUP BY order */
98603    int addrEnd;        /* End of processing for this SELECT */
98604    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
98605    int sortOut = 0;    /* Output register from the sorter */
98606
98607    /* Remove any and all aliases between the result set and the
98608    ** GROUP BY clause.
98609    */
98610    if( pGroupBy ){
98611      int k;                        /* Loop counter */
98612      struct ExprList_item *pItem;  /* For looping over expression in a list */
98613
98614      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
98615        pItem->iAlias = 0;
98616      }
98617      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
98618        pItem->iAlias = 0;
98619      }
98620      if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
98621    }else{
98622      p->nSelectRow = (double)1;
98623    }
98624
98625
98626    /* Create a label to jump to when we want to abort the query */
98627    addrEnd = sqlite3VdbeMakeLabel(v);
98628
98629    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
98630    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
98631    ** SELECT statement.
98632    */
98633    memset(&sNC, 0, sizeof(sNC));
98634    sNC.pParse = pParse;
98635    sNC.pSrcList = pTabList;
98636    sNC.pAggInfo = &sAggInfo;
98637    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
98638    sAggInfo.pGroupBy = pGroupBy;
98639    sqlite3ExprAnalyzeAggList(&sNC, pEList);
98640    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
98641    if( pHaving ){
98642      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
98643    }
98644    sAggInfo.nAccumulator = sAggInfo.nColumn;
98645    for(i=0; i<sAggInfo.nFunc; i++){
98646      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
98647      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
98648    }
98649    if( db->mallocFailed ) goto select_end;
98650
98651    /* Processing for aggregates with GROUP BY is very different and
98652    ** much more complex than aggregates without a GROUP BY.
98653    */
98654    if( pGroupBy ){
98655      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
98656      int j1;             /* A-vs-B comparision jump */
98657      int addrOutputRow;  /* Start of subroutine that outputs a result row */
98658      int regOutputRow;   /* Return address register for output subroutine */
98659      int addrSetAbort;   /* Set the abort flag and return */
98660      int addrTopOfLoop;  /* Top of the input loop */
98661      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
98662      int addrReset;      /* Subroutine for resetting the accumulator */
98663      int regReset;       /* Return address register for reset subroutine */
98664
98665      /* If there is a GROUP BY clause we might need a sorting index to
98666      ** implement it.  Allocate that sorting index now.  If it turns out
98667      ** that we do not need it after all, the OP_SorterOpen instruction
98668      ** will be converted into a Noop.
98669      */
98670      sAggInfo.sortingIdx = pParse->nTab++;
98671      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
98672      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
98673          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
98674          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98675
98676      /* Initialize memory locations used by GROUP BY aggregate processing
98677      */
98678      iUseFlag = ++pParse->nMem;
98679      iAbortFlag = ++pParse->nMem;
98680      regOutputRow = ++pParse->nMem;
98681      addrOutputRow = sqlite3VdbeMakeLabel(v);
98682      regReset = ++pParse->nMem;
98683      addrReset = sqlite3VdbeMakeLabel(v);
98684      iAMem = pParse->nMem + 1;
98685      pParse->nMem += pGroupBy->nExpr;
98686      iBMem = pParse->nMem + 1;
98687      pParse->nMem += pGroupBy->nExpr;
98688      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
98689      VdbeComment((v, "clear abort flag"));
98690      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
98691      VdbeComment((v, "indicate accumulator empty"));
98692      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
98693
98694      /* Begin a loop that will extract all source rows in GROUP BY order.
98695      ** This might involve two separate loops with an OP_Sort in between, or
98696      ** it might be a single loop that uses an index to extract information
98697      ** in the right order to begin with.
98698      */
98699      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
98700      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
98701      if( pWInfo==0 ) goto select_end;
98702      if( pGroupBy==0 ){
98703        /* The optimizer is able to deliver rows in group by order so
98704        ** we do not have to sort.  The OP_OpenEphemeral table will be
98705        ** cancelled later because we still need to use the pKeyInfo
98706        */
98707        pGroupBy = p->pGroupBy;
98708        groupBySort = 0;
98709      }else{
98710        /* Rows are coming out in undetermined order.  We have to push
98711        ** each row into a sorting index, terminate the first loop,
98712        ** then loop over the sorting index in order to get the output
98713        ** in sorted order
98714        */
98715        int regBase;
98716        int regRecord;
98717        int nCol;
98718        int nGroupBy;
98719
98720        explainTempTable(pParse,
98721            isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
98722
98723        groupBySort = 1;
98724        nGroupBy = pGroupBy->nExpr;
98725        nCol = nGroupBy + 1;
98726        j = nGroupBy+1;
98727        for(i=0; i<sAggInfo.nColumn; i++){
98728          if( sAggInfo.aCol[i].iSorterColumn>=j ){
98729            nCol++;
98730            j++;
98731          }
98732        }
98733        regBase = sqlite3GetTempRange(pParse, nCol);
98734        sqlite3ExprCacheClear(pParse);
98735        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
98736        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
98737        j = nGroupBy+1;
98738        for(i=0; i<sAggInfo.nColumn; i++){
98739          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
98740          if( pCol->iSorterColumn>=j ){
98741            int r1 = j + regBase;
98742            int r2;
98743
98744            r2 = sqlite3ExprCodeGetColumn(pParse,
98745                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
98746            if( r1!=r2 ){
98747              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
98748            }
98749            j++;
98750          }
98751        }
98752        regRecord = sqlite3GetTempReg(pParse);
98753        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
98754        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
98755        sqlite3ReleaseTempReg(pParse, regRecord);
98756        sqlite3ReleaseTempRange(pParse, regBase, nCol);
98757        sqlite3WhereEnd(pWInfo);
98758        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
98759        sortOut = sqlite3GetTempReg(pParse);
98760        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
98761        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
98762        VdbeComment((v, "GROUP BY sort"));
98763        sAggInfo.useSortingIdx = 1;
98764        sqlite3ExprCacheClear(pParse);
98765      }
98766
98767      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
98768      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
98769      ** Then compare the current GROUP BY terms against the GROUP BY terms
98770      ** from the previous row currently stored in a0, a1, a2...
98771      */
98772      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
98773      sqlite3ExprCacheClear(pParse);
98774      if( groupBySort ){
98775        sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
98776      }
98777      for(j=0; j<pGroupBy->nExpr; j++){
98778        if( groupBySort ){
98779          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
98780          if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
98781        }else{
98782          sAggInfo.directMode = 1;
98783          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
98784        }
98785      }
98786      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
98787                          (char*)pKeyInfo, P4_KEYINFO);
98788      j1 = sqlite3VdbeCurrentAddr(v);
98789      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
98790
98791      /* Generate code that runs whenever the GROUP BY changes.
98792      ** Changes in the GROUP BY are detected by the previous code
98793      ** block.  If there were no changes, this block is skipped.
98794      **
98795      ** This code copies current group by terms in b0,b1,b2,...
98796      ** over to a0,a1,a2.  It then calls the output subroutine
98797      ** and resets the aggregate accumulator registers in preparation
98798      ** for the next GROUP BY batch.
98799      */
98800      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
98801      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
98802      VdbeComment((v, "output one row"));
98803      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
98804      VdbeComment((v, "check abort flag"));
98805      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
98806      VdbeComment((v, "reset accumulator"));
98807
98808      /* Update the aggregate accumulators based on the content of
98809      ** the current row
98810      */
98811      sqlite3VdbeJumpHere(v, j1);
98812      updateAccumulator(pParse, &sAggInfo);
98813      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
98814      VdbeComment((v, "indicate data in accumulator"));
98815
98816      /* End of the loop
98817      */
98818      if( groupBySort ){
98819        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
98820      }else{
98821        sqlite3WhereEnd(pWInfo);
98822        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
98823      }
98824
98825      /* Output the final row of result
98826      */
98827      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
98828      VdbeComment((v, "output final row"));
98829
98830      /* Jump over the subroutines
98831      */
98832      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
98833
98834      /* Generate a subroutine that outputs a single row of the result
98835      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
98836      ** is less than or equal to zero, the subroutine is a no-op.  If
98837      ** the processing calls for the query to abort, this subroutine
98838      ** increments the iAbortFlag memory location before returning in
98839      ** order to signal the caller to abort.
98840      */
98841      addrSetAbort = sqlite3VdbeCurrentAddr(v);
98842      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
98843      VdbeComment((v, "set abort flag"));
98844      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
98845      sqlite3VdbeResolveLabel(v, addrOutputRow);
98846      addrOutputRow = sqlite3VdbeCurrentAddr(v);
98847      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
98848      VdbeComment((v, "Groupby result generator entry point"));
98849      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
98850      finalizeAggFunctions(pParse, &sAggInfo);
98851      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
98852      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
98853                      distinct, pDest,
98854                      addrOutputRow+1, addrSetAbort);
98855      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
98856      VdbeComment((v, "end groupby result generator"));
98857
98858      /* Generate a subroutine that will reset the group-by accumulator
98859      */
98860      sqlite3VdbeResolveLabel(v, addrReset);
98861      resetAccumulator(pParse, &sAggInfo);
98862      sqlite3VdbeAddOp1(v, OP_Return, regReset);
98863
98864    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
98865    else {
98866      ExprList *pDel = 0;
98867#ifndef SQLITE_OMIT_BTREECOUNT
98868      Table *pTab;
98869      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
98870        /* If isSimpleCount() returns a pointer to a Table structure, then
98871        ** the SQL statement is of the form:
98872        **
98873        **   SELECT count(*) FROM <tbl>
98874        **
98875        ** where the Table structure returned represents table <tbl>.
98876        **
98877        ** This statement is so common that it is optimized specially. The
98878        ** OP_Count instruction is executed either on the intkey table that
98879        ** contains the data for table <tbl> or on one of its indexes. It
98880        ** is better to execute the op on an index, as indexes are almost
98881        ** always spread across less pages than their corresponding tables.
98882        */
98883        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
98884        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
98885        Index *pIdx;                         /* Iterator variable */
98886        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
98887        Index *pBest = 0;                    /* Best index found so far */
98888        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
98889
98890        sqlite3CodeVerifySchema(pParse, iDb);
98891        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
98892
98893        /* Search for the index that has the least amount of columns. If
98894        ** there is such an index, and it has less columns than the table
98895        ** does, then we can assume that it consumes less space on disk and
98896        ** will therefore be cheaper to scan to determine the query result.
98897        ** In this case set iRoot to the root page number of the index b-tree
98898        ** and pKeyInfo to the KeyInfo structure required to navigate the
98899        ** index.
98900        **
98901        ** (2011-04-15) Do not do a full scan of an unordered index.
98902        **
98903        ** In practice the KeyInfo structure will not be used. It is only
98904        ** passed to keep OP_OpenRead happy.
98905        */
98906        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98907          if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
98908            pBest = pIdx;
98909          }
98910        }
98911        if( pBest && pBest->nColumn<pTab->nCol ){
98912          iRoot = pBest->tnum;
98913          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
98914        }
98915
98916        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
98917        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
98918        if( pKeyInfo ){
98919          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
98920        }
98921        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
98922        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
98923        explainSimpleCount(pParse, pTab, pBest);
98924      }else
98925#endif /* SQLITE_OMIT_BTREECOUNT */
98926      {
98927        /* Check if the query is of one of the following forms:
98928        **
98929        **   SELECT min(x) FROM ...
98930        **   SELECT max(x) FROM ...
98931        **
98932        ** If it is, then ask the code in where.c to attempt to sort results
98933        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
98934        ** If where.c is able to produce results sorted in this order, then
98935        ** add vdbe code to break out of the processing loop after the
98936        ** first iteration (since the first iteration of the loop is
98937        ** guaranteed to operate on the row with the minimum or maximum
98938        ** value of x, the only row required).
98939        **
98940        ** A special flag must be passed to sqlite3WhereBegin() to slightly
98941        ** modify behaviour as follows:
98942        **
98943        **   + If the query is a "SELECT min(x)", then the loop coded by
98944        **     where.c should not iterate over any values with a NULL value
98945        **     for x.
98946        **
98947        **   + The optimizer code in where.c (the thing that decides which
98948        **     index or indices to use) should place a different priority on
98949        **     satisfying the 'ORDER BY' clause than it does in other cases.
98950        **     Refer to code and comments in where.c for details.
98951        */
98952        ExprList *pMinMax = 0;
98953        u8 flag = minMaxQuery(p);
98954        if( flag ){
98955          assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
98956          pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
98957          pDel = pMinMax;
98958          if( pMinMax && !db->mallocFailed ){
98959            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
98960            pMinMax->a[0].pExpr->op = TK_COLUMN;
98961          }
98962        }
98963
98964        /* This case runs if the aggregate has no GROUP BY clause.  The
98965        ** processing is much simpler since there is only a single row
98966        ** of output.
98967        */
98968        resetAccumulator(pParse, &sAggInfo);
98969        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, 0, flag);
98970        if( pWInfo==0 ){
98971          sqlite3ExprListDelete(db, pDel);
98972          goto select_end;
98973        }
98974        updateAccumulator(pParse, &sAggInfo);
98975        if( !pMinMax && flag ){
98976          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
98977          VdbeComment((v, "%s() by index",
98978                (flag==WHERE_ORDERBY_MIN?"min":"max")));
98979        }
98980        sqlite3WhereEnd(pWInfo);
98981        finalizeAggFunctions(pParse, &sAggInfo);
98982      }
98983
98984      pOrderBy = 0;
98985      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
98986      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
98987                      pDest, addrEnd, addrEnd);
98988      sqlite3ExprListDelete(db, pDel);
98989    }
98990    sqlite3VdbeResolveLabel(v, addrEnd);
98991
98992  } /* endif aggregate query */
98993
98994  if( distinct>=0 ){
98995    explainTempTable(pParse, "DISTINCT");
98996  }
98997
98998  /* If there is an ORDER BY clause, then we need to sort the results
98999  ** and send them to the callback one by one.
99000  */
99001  if( pOrderBy ){
99002    explainTempTable(pParse, "ORDER BY");
99003    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
99004  }
99005
99006  /* Jump here to skip this query
99007  */
99008  sqlite3VdbeResolveLabel(v, iEnd);
99009
99010  /* The SELECT was successfully coded.   Set the return code to 0
99011  ** to indicate no errors.
99012  */
99013  rc = 0;
99014
99015  /* Control jumps to here if an error is encountered above, or upon
99016  ** successful coding of the SELECT.
99017  */
99018select_end:
99019  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
99020
99021  /* Identify column names if results of the SELECT are to be output.
99022  */
99023  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
99024    generateColumnNames(pParse, pTabList, pEList);
99025  }
99026
99027  sqlite3DbFree(db, sAggInfo.aCol);
99028  sqlite3DbFree(db, sAggInfo.aFunc);
99029  return rc;
99030}
99031
99032#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
99033/*
99034** Generate a human-readable description of a the Select object.
99035*/
99036static void explainOneSelect(Vdbe *pVdbe, Select *p){
99037  sqlite3ExplainPrintf(pVdbe, "SELECT ");
99038  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
99039    if( p->selFlags & SF_Distinct ){
99040      sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
99041    }
99042    if( p->selFlags & SF_Aggregate ){
99043      sqlite3ExplainPrintf(pVdbe, "agg_flag ");
99044    }
99045    sqlite3ExplainNL(pVdbe);
99046    sqlite3ExplainPrintf(pVdbe, "   ");
99047  }
99048  sqlite3ExplainExprList(pVdbe, p->pEList);
99049  sqlite3ExplainNL(pVdbe);
99050  if( p->pSrc && p->pSrc->nSrc ){
99051    int i;
99052    sqlite3ExplainPrintf(pVdbe, "FROM ");
99053    sqlite3ExplainPush(pVdbe);
99054    for(i=0; i<p->pSrc->nSrc; i++){
99055      struct SrcList_item *pItem = &p->pSrc->a[i];
99056      sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
99057      if( pItem->pSelect ){
99058        sqlite3ExplainSelect(pVdbe, pItem->pSelect);
99059        if( pItem->pTab ){
99060          sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
99061        }
99062      }else if( pItem->zName ){
99063        sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
99064      }
99065      if( pItem->zAlias ){
99066        sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
99067      }
99068      if( pItem->jointype & JT_LEFT ){
99069        sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
99070      }
99071      sqlite3ExplainNL(pVdbe);
99072    }
99073    sqlite3ExplainPop(pVdbe);
99074  }
99075  if( p->pWhere ){
99076    sqlite3ExplainPrintf(pVdbe, "WHERE ");
99077    sqlite3ExplainExpr(pVdbe, p->pWhere);
99078    sqlite3ExplainNL(pVdbe);
99079  }
99080  if( p->pGroupBy ){
99081    sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
99082    sqlite3ExplainExprList(pVdbe, p->pGroupBy);
99083    sqlite3ExplainNL(pVdbe);
99084  }
99085  if( p->pHaving ){
99086    sqlite3ExplainPrintf(pVdbe, "HAVING ");
99087    sqlite3ExplainExpr(pVdbe, p->pHaving);
99088    sqlite3ExplainNL(pVdbe);
99089  }
99090  if( p->pOrderBy ){
99091    sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
99092    sqlite3ExplainExprList(pVdbe, p->pOrderBy);
99093    sqlite3ExplainNL(pVdbe);
99094  }
99095  if( p->pLimit ){
99096    sqlite3ExplainPrintf(pVdbe, "LIMIT ");
99097    sqlite3ExplainExpr(pVdbe, p->pLimit);
99098    sqlite3ExplainNL(pVdbe);
99099  }
99100  if( p->pOffset ){
99101    sqlite3ExplainPrintf(pVdbe, "OFFSET ");
99102    sqlite3ExplainExpr(pVdbe, p->pOffset);
99103    sqlite3ExplainNL(pVdbe);
99104  }
99105}
99106SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
99107  if( p==0 ){
99108    sqlite3ExplainPrintf(pVdbe, "(null-select)");
99109    return;
99110  }
99111  while( p->pPrior ) p = p->pPrior;
99112  sqlite3ExplainPush(pVdbe);
99113  while( p ){
99114    explainOneSelect(pVdbe, p);
99115    p = p->pNext;
99116    if( p==0 ) break;
99117    sqlite3ExplainNL(pVdbe);
99118    sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
99119  }
99120  sqlite3ExplainPrintf(pVdbe, "END");
99121  sqlite3ExplainPop(pVdbe);
99122}
99123
99124/* End of the structure debug printing code
99125*****************************************************************************/
99126#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
99127
99128/************** End of select.c **********************************************/
99129/************** Begin file table.c *******************************************/
99130/*
99131** 2001 September 15
99132**
99133** The author disclaims copyright to this source code.  In place of
99134** a legal notice, here is a blessing:
99135**
99136**    May you do good and not evil.
99137**    May you find forgiveness for yourself and forgive others.
99138**    May you share freely, never taking more than you give.
99139**
99140*************************************************************************
99141** This file contains the sqlite3_get_table() and sqlite3_free_table()
99142** interface routines.  These are just wrappers around the main
99143** interface routine of sqlite3_exec().
99144**
99145** These routines are in a separate files so that they will not be linked
99146** if they are not used.
99147*/
99148/* #include <stdlib.h> */
99149/* #include <string.h> */
99150
99151#ifndef SQLITE_OMIT_GET_TABLE
99152
99153/*
99154** This structure is used to pass data from sqlite3_get_table() through
99155** to the callback function is uses to build the result.
99156*/
99157typedef struct TabResult {
99158  char **azResult;   /* Accumulated output */
99159  char *zErrMsg;     /* Error message text, if an error occurs */
99160  int nAlloc;        /* Slots allocated for azResult[] */
99161  int nRow;          /* Number of rows in the result */
99162  int nColumn;       /* Number of columns in the result */
99163  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
99164  int rc;            /* Return code from sqlite3_exec() */
99165} TabResult;
99166
99167/*
99168** This routine is called once for each row in the result table.  Its job
99169** is to fill in the TabResult structure appropriately, allocating new
99170** memory as necessary.
99171*/
99172static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
99173  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
99174  int need;                         /* Slots needed in p->azResult[] */
99175  int i;                            /* Loop counter */
99176  char *z;                          /* A single column of result */
99177
99178  /* Make sure there is enough space in p->azResult to hold everything
99179  ** we need to remember from this invocation of the callback.
99180  */
99181  if( p->nRow==0 && argv!=0 ){
99182    need = nCol*2;
99183  }else{
99184    need = nCol;
99185  }
99186  if( p->nData + need > p->nAlloc ){
99187    char **azNew;
99188    p->nAlloc = p->nAlloc*2 + need;
99189    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
99190    if( azNew==0 ) goto malloc_failed;
99191    p->azResult = azNew;
99192  }
99193
99194  /* If this is the first row, then generate an extra row containing
99195  ** the names of all columns.
99196  */
99197  if( p->nRow==0 ){
99198    p->nColumn = nCol;
99199    for(i=0; i<nCol; i++){
99200      z = sqlite3_mprintf("%s", colv[i]);
99201      if( z==0 ) goto malloc_failed;
99202      p->azResult[p->nData++] = z;
99203    }
99204  }else if( p->nColumn!=nCol ){
99205    sqlite3_free(p->zErrMsg);
99206    p->zErrMsg = sqlite3_mprintf(
99207       "sqlite3_get_table() called with two or more incompatible queries"
99208    );
99209    p->rc = SQLITE_ERROR;
99210    return 1;
99211  }
99212
99213  /* Copy over the row data
99214  */
99215  if( argv!=0 ){
99216    for(i=0; i<nCol; i++){
99217      if( argv[i]==0 ){
99218        z = 0;
99219      }else{
99220        int n = sqlite3Strlen30(argv[i])+1;
99221        z = sqlite3_malloc( n );
99222        if( z==0 ) goto malloc_failed;
99223        memcpy(z, argv[i], n);
99224      }
99225      p->azResult[p->nData++] = z;
99226    }
99227    p->nRow++;
99228  }
99229  return 0;
99230
99231malloc_failed:
99232  p->rc = SQLITE_NOMEM;
99233  return 1;
99234}
99235
99236/*
99237** Query the database.  But instead of invoking a callback for each row,
99238** malloc() for space to hold the result and return the entire results
99239** at the conclusion of the call.
99240**
99241** The result that is written to ***pazResult is held in memory obtained
99242** from malloc().  But the caller cannot free this memory directly.
99243** Instead, the entire table should be passed to sqlite3_free_table() when
99244** the calling procedure is finished using it.
99245*/
99246SQLITE_API int sqlite3_get_table(
99247  sqlite3 *db,                /* The database on which the SQL executes */
99248  const char *zSql,           /* The SQL to be executed */
99249  char ***pazResult,          /* Write the result table here */
99250  int *pnRow,                 /* Write the number of rows in the result here */
99251  int *pnColumn,              /* Write the number of columns of result here */
99252  char **pzErrMsg             /* Write error messages here */
99253){
99254  int rc;
99255  TabResult res;
99256
99257  *pazResult = 0;
99258  if( pnColumn ) *pnColumn = 0;
99259  if( pnRow ) *pnRow = 0;
99260  if( pzErrMsg ) *pzErrMsg = 0;
99261  res.zErrMsg = 0;
99262  res.nRow = 0;
99263  res.nColumn = 0;
99264  res.nData = 1;
99265  res.nAlloc = 20;
99266  res.rc = SQLITE_OK;
99267  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
99268  if( res.azResult==0 ){
99269     db->errCode = SQLITE_NOMEM;
99270     return SQLITE_NOMEM;
99271  }
99272  res.azResult[0] = 0;
99273  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
99274  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
99275  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
99276  if( (rc&0xff)==SQLITE_ABORT ){
99277    sqlite3_free_table(&res.azResult[1]);
99278    if( res.zErrMsg ){
99279      if( pzErrMsg ){
99280        sqlite3_free(*pzErrMsg);
99281        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
99282      }
99283      sqlite3_free(res.zErrMsg);
99284    }
99285    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
99286    return res.rc;
99287  }
99288  sqlite3_free(res.zErrMsg);
99289  if( rc!=SQLITE_OK ){
99290    sqlite3_free_table(&res.azResult[1]);
99291    return rc;
99292  }
99293  if( res.nAlloc>res.nData ){
99294    char **azNew;
99295    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
99296    if( azNew==0 ){
99297      sqlite3_free_table(&res.azResult[1]);
99298      db->errCode = SQLITE_NOMEM;
99299      return SQLITE_NOMEM;
99300    }
99301    res.azResult = azNew;
99302  }
99303  *pazResult = &res.azResult[1];
99304  if( pnColumn ) *pnColumn = res.nColumn;
99305  if( pnRow ) *pnRow = res.nRow;
99306  return rc;
99307}
99308
99309/*
99310** This routine frees the space the sqlite3_get_table() malloced.
99311*/
99312SQLITE_API void sqlite3_free_table(
99313  char **azResult            /* Result returned from from sqlite3_get_table() */
99314){
99315  if( azResult ){
99316    int i, n;
99317    azResult--;
99318    assert( azResult!=0 );
99319    n = SQLITE_PTR_TO_INT(azResult[0]);
99320    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
99321    sqlite3_free(azResult);
99322  }
99323}
99324
99325#endif /* SQLITE_OMIT_GET_TABLE */
99326
99327/************** End of table.c ***********************************************/
99328/************** Begin file trigger.c *****************************************/
99329/*
99330**
99331** The author disclaims copyright to this source code.  In place of
99332** a legal notice, here is a blessing:
99333**
99334**    May you do good and not evil.
99335**    May you find forgiveness for yourself and forgive others.
99336**    May you share freely, never taking more than you give.
99337**
99338*************************************************************************
99339** This file contains the implementation for TRIGGERs
99340*/
99341
99342#ifndef SQLITE_OMIT_TRIGGER
99343/*
99344** Delete a linked list of TriggerStep structures.
99345*/
99346SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
99347  while( pTriggerStep ){
99348    TriggerStep * pTmp = pTriggerStep;
99349    pTriggerStep = pTriggerStep->pNext;
99350
99351    sqlite3ExprDelete(db, pTmp->pWhere);
99352    sqlite3ExprListDelete(db, pTmp->pExprList);
99353    sqlite3SelectDelete(db, pTmp->pSelect);
99354    sqlite3IdListDelete(db, pTmp->pIdList);
99355
99356    sqlite3DbFree(db, pTmp);
99357  }
99358}
99359
99360/*
99361** Given table pTab, return a list of all the triggers attached to
99362** the table. The list is connected by Trigger.pNext pointers.
99363**
99364** All of the triggers on pTab that are in the same database as pTab
99365** are already attached to pTab->pTrigger.  But there might be additional
99366** triggers on pTab in the TEMP schema.  This routine prepends all
99367** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
99368** and returns the combined list.
99369**
99370** To state it another way:  This routine returns a list of all triggers
99371** that fire off of pTab.  The list will include any TEMP triggers on
99372** pTab as well as the triggers lised in pTab->pTrigger.
99373*/
99374SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
99375  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
99376  Trigger *pList = 0;                  /* List of triggers to return */
99377
99378  if( pParse->disableTriggers ){
99379    return 0;
99380  }
99381
99382  if( pTmpSchema!=pTab->pSchema ){
99383    HashElem *p;
99384    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
99385    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
99386      Trigger *pTrig = (Trigger *)sqliteHashData(p);
99387      if( pTrig->pTabSchema==pTab->pSchema
99388       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
99389      ){
99390        pTrig->pNext = (pList ? pList : pTab->pTrigger);
99391        pList = pTrig;
99392      }
99393    }
99394  }
99395
99396  return (pList ? pList : pTab->pTrigger);
99397}
99398
99399/*
99400** This is called by the parser when it sees a CREATE TRIGGER statement
99401** up to the point of the BEGIN before the trigger actions.  A Trigger
99402** structure is generated based on the information available and stored
99403** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
99404** sqlite3FinishTrigger() function is called to complete the trigger
99405** construction process.
99406*/
99407SQLITE_PRIVATE void sqlite3BeginTrigger(
99408  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
99409  Token *pName1,      /* The name of the trigger */
99410  Token *pName2,      /* The name of the trigger */
99411  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
99412  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
99413  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
99414  SrcList *pTableName,/* The name of the table/view the trigger applies to */
99415  Expr *pWhen,        /* WHEN clause */
99416  int isTemp,         /* True if the TEMPORARY keyword is present */
99417  int noErr           /* Suppress errors if the trigger already exists */
99418){
99419  Trigger *pTrigger = 0;  /* The new trigger */
99420  Table *pTab;            /* Table that the trigger fires off of */
99421  char *zName = 0;        /* Name of the trigger */
99422  sqlite3 *db = pParse->db;  /* The database connection */
99423  int iDb;                /* The database to store the trigger in */
99424  Token *pName;           /* The unqualified db name */
99425  DbFixer sFix;           /* State vector for the DB fixer */
99426  int iTabDb;             /* Index of the database holding pTab */
99427
99428  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
99429  assert( pName2!=0 );
99430  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
99431  assert( op>0 && op<0xff );
99432  if( isTemp ){
99433    /* If TEMP was specified, then the trigger name may not be qualified. */
99434    if( pName2->n>0 ){
99435      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
99436      goto trigger_cleanup;
99437    }
99438    iDb = 1;
99439    pName = pName1;
99440  }else{
99441    /* Figure out the db that the the trigger will be created in */
99442    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
99443    if( iDb<0 ){
99444      goto trigger_cleanup;
99445    }
99446  }
99447  if( !pTableName || db->mallocFailed ){
99448    goto trigger_cleanup;
99449  }
99450
99451  /* A long-standing parser bug is that this syntax was allowed:
99452  **
99453  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
99454  **                                                 ^^^^^^^^
99455  **
99456  ** To maintain backwards compatibility, ignore the database
99457  ** name on pTableName if we are reparsing our of SQLITE_MASTER.
99458  */
99459  if( db->init.busy && iDb!=1 ){
99460    sqlite3DbFree(db, pTableName->a[0].zDatabase);
99461    pTableName->a[0].zDatabase = 0;
99462  }
99463
99464  /* If the trigger name was unqualified, and the table is a temp table,
99465  ** then set iDb to 1 to create the trigger in the temporary database.
99466  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
99467  ** exist, the error is caught by the block below.
99468  */
99469  pTab = sqlite3SrcListLookup(pParse, pTableName);
99470  if( db->init.busy==0 && pName2->n==0 && pTab
99471        && pTab->pSchema==db->aDb[1].pSchema ){
99472    iDb = 1;
99473  }
99474
99475  /* Ensure the table name matches database name and that the table exists */
99476  if( db->mallocFailed ) goto trigger_cleanup;
99477  assert( pTableName->nSrc==1 );
99478  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
99479      sqlite3FixSrcList(&sFix, pTableName) ){
99480    goto trigger_cleanup;
99481  }
99482  pTab = sqlite3SrcListLookup(pParse, pTableName);
99483  if( !pTab ){
99484    /* The table does not exist. */
99485    if( db->init.iDb==1 ){
99486      /* Ticket #3810.
99487      ** Normally, whenever a table is dropped, all associated triggers are
99488      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
99489      ** and the table is dropped by a different database connection, the
99490      ** trigger is not visible to the database connection that does the
99491      ** drop so the trigger cannot be dropped.  This results in an
99492      ** "orphaned trigger" - a trigger whose associated table is missing.
99493      */
99494      db->init.orphanTrigger = 1;
99495    }
99496    goto trigger_cleanup;
99497  }
99498  if( IsVirtual(pTab) ){
99499    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
99500    goto trigger_cleanup;
99501  }
99502
99503  /* Check that the trigger name is not reserved and that no trigger of the
99504  ** specified name exists */
99505  zName = sqlite3NameFromToken(db, pName);
99506  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
99507    goto trigger_cleanup;
99508  }
99509  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99510  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
99511                      zName, sqlite3Strlen30(zName)) ){
99512    if( !noErr ){
99513      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
99514    }else{
99515      assert( !db->init.busy );
99516      sqlite3CodeVerifySchema(pParse, iDb);
99517    }
99518    goto trigger_cleanup;
99519  }
99520
99521  /* Do not create a trigger on a system table */
99522  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
99523    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
99524    pParse->nErr++;
99525    goto trigger_cleanup;
99526  }
99527
99528  /* INSTEAD of triggers are only for views and views only support INSTEAD
99529  ** of triggers.
99530  */
99531  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
99532    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
99533        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
99534    goto trigger_cleanup;
99535  }
99536  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
99537    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
99538        " trigger on table: %S", pTableName, 0);
99539    goto trigger_cleanup;
99540  }
99541  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99542
99543#ifndef SQLITE_OMIT_AUTHORIZATION
99544  {
99545    int code = SQLITE_CREATE_TRIGGER;
99546    const char *zDb = db->aDb[iTabDb].zName;
99547    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
99548    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
99549    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
99550      goto trigger_cleanup;
99551    }
99552    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
99553      goto trigger_cleanup;
99554    }
99555  }
99556#endif
99557
99558  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
99559  ** cannot appear on views.  So we might as well translate every
99560  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
99561  ** elsewhere.
99562  */
99563  if (tr_tm == TK_INSTEAD){
99564    tr_tm = TK_BEFORE;
99565  }
99566
99567  /* Build the Trigger object */
99568  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
99569  if( pTrigger==0 ) goto trigger_cleanup;
99570  pTrigger->zName = zName;
99571  zName = 0;
99572  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
99573  pTrigger->pSchema = db->aDb[iDb].pSchema;
99574  pTrigger->pTabSchema = pTab->pSchema;
99575  pTrigger->op = (u8)op;
99576  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
99577  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
99578  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
99579  assert( pParse->pNewTrigger==0 );
99580  pParse->pNewTrigger = pTrigger;
99581
99582trigger_cleanup:
99583  sqlite3DbFree(db, zName);
99584  sqlite3SrcListDelete(db, pTableName);
99585  sqlite3IdListDelete(db, pColumns);
99586  sqlite3ExprDelete(db, pWhen);
99587  if( !pParse->pNewTrigger ){
99588    sqlite3DeleteTrigger(db, pTrigger);
99589  }else{
99590    assert( pParse->pNewTrigger==pTrigger );
99591  }
99592}
99593
99594/*
99595** This routine is called after all of the trigger actions have been parsed
99596** in order to complete the process of building the trigger.
99597*/
99598SQLITE_PRIVATE void sqlite3FinishTrigger(
99599  Parse *pParse,          /* Parser context */
99600  TriggerStep *pStepList, /* The triggered program */
99601  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
99602){
99603  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
99604  char *zName;                            /* Name of trigger */
99605  sqlite3 *db = pParse->db;               /* The database */
99606  DbFixer sFix;                           /* Fixer object */
99607  int iDb;                                /* Database containing the trigger */
99608  Token nameToken;                        /* Trigger name for error reporting */
99609
99610  pParse->pNewTrigger = 0;
99611  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
99612  zName = pTrig->zName;
99613  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
99614  pTrig->step_list = pStepList;
99615  while( pStepList ){
99616    pStepList->pTrig = pTrig;
99617    pStepList = pStepList->pNext;
99618  }
99619  nameToken.z = pTrig->zName;
99620  nameToken.n = sqlite3Strlen30(nameToken.z);
99621  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
99622          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
99623    goto triggerfinish_cleanup;
99624  }
99625
99626  /* if we are not initializing,
99627  ** build the sqlite_master entry
99628  */
99629  if( !db->init.busy ){
99630    Vdbe *v;
99631    char *z;
99632
99633    /* Make an entry in the sqlite_master table */
99634    v = sqlite3GetVdbe(pParse);
99635    if( v==0 ) goto triggerfinish_cleanup;
99636    sqlite3BeginWriteOperation(pParse, 0, iDb);
99637    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
99638    sqlite3NestedParse(pParse,
99639       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
99640       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
99641       pTrig->table, z);
99642    sqlite3DbFree(db, z);
99643    sqlite3ChangeCookie(pParse, iDb);
99644    sqlite3VdbeAddParseSchemaOp(v, iDb,
99645        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
99646  }
99647
99648  if( db->init.busy ){
99649    Trigger *pLink = pTrig;
99650    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
99651    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99652    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
99653    if( pTrig ){
99654      db->mallocFailed = 1;
99655    }else if( pLink->pSchema==pLink->pTabSchema ){
99656      Table *pTab;
99657      int n = sqlite3Strlen30(pLink->table);
99658      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
99659      assert( pTab!=0 );
99660      pLink->pNext = pTab->pTrigger;
99661      pTab->pTrigger = pLink;
99662    }
99663  }
99664
99665triggerfinish_cleanup:
99666  sqlite3DeleteTrigger(db, pTrig);
99667  assert( !pParse->pNewTrigger );
99668  sqlite3DeleteTriggerStep(db, pStepList);
99669}
99670
99671/*
99672** Turn a SELECT statement (that the pSelect parameter points to) into
99673** a trigger step.  Return a pointer to a TriggerStep structure.
99674**
99675** The parser calls this routine when it finds a SELECT statement in
99676** body of a TRIGGER.
99677*/
99678SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
99679  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
99680  if( pTriggerStep==0 ) {
99681    sqlite3SelectDelete(db, pSelect);
99682    return 0;
99683  }
99684  pTriggerStep->op = TK_SELECT;
99685  pTriggerStep->pSelect = pSelect;
99686  pTriggerStep->orconf = OE_Default;
99687  return pTriggerStep;
99688}
99689
99690/*
99691** Allocate space to hold a new trigger step.  The allocated space
99692** holds both the TriggerStep object and the TriggerStep.target.z string.
99693**
99694** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
99695*/
99696static TriggerStep *triggerStepAllocate(
99697  sqlite3 *db,                /* Database connection */
99698  u8 op,                      /* Trigger opcode */
99699  Token *pName                /* The target name */
99700){
99701  TriggerStep *pTriggerStep;
99702
99703  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
99704  if( pTriggerStep ){
99705    char *z = (char*)&pTriggerStep[1];
99706    memcpy(z, pName->z, pName->n);
99707    pTriggerStep->target.z = z;
99708    pTriggerStep->target.n = pName->n;
99709    pTriggerStep->op = op;
99710  }
99711  return pTriggerStep;
99712}
99713
99714/*
99715** Build a trigger step out of an INSERT statement.  Return a pointer
99716** to the new trigger step.
99717**
99718** The parser calls this routine when it sees an INSERT inside the
99719** body of a trigger.
99720*/
99721SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
99722  sqlite3 *db,        /* The database connection */
99723  Token *pTableName,  /* Name of the table into which we insert */
99724  IdList *pColumn,    /* List of columns in pTableName to insert into */
99725  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
99726  Select *pSelect,    /* A SELECT statement that supplies values */
99727  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
99728){
99729  TriggerStep *pTriggerStep;
99730
99731  assert(pEList == 0 || pSelect == 0);
99732  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
99733
99734  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
99735  if( pTriggerStep ){
99736    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
99737    pTriggerStep->pIdList = pColumn;
99738    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
99739    pTriggerStep->orconf = orconf;
99740  }else{
99741    sqlite3IdListDelete(db, pColumn);
99742  }
99743  sqlite3ExprListDelete(db, pEList);
99744  sqlite3SelectDelete(db, pSelect);
99745
99746  return pTriggerStep;
99747}
99748
99749/*
99750** Construct a trigger step that implements an UPDATE statement and return
99751** a pointer to that trigger step.  The parser calls this routine when it
99752** sees an UPDATE statement inside the body of a CREATE TRIGGER.
99753*/
99754SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
99755  sqlite3 *db,         /* The database connection */
99756  Token *pTableName,   /* Name of the table to be updated */
99757  ExprList *pEList,    /* The SET clause: list of column and new values */
99758  Expr *pWhere,        /* The WHERE clause */
99759  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
99760){
99761  TriggerStep *pTriggerStep;
99762
99763  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
99764  if( pTriggerStep ){
99765    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
99766    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99767    pTriggerStep->orconf = orconf;
99768  }
99769  sqlite3ExprListDelete(db, pEList);
99770  sqlite3ExprDelete(db, pWhere);
99771  return pTriggerStep;
99772}
99773
99774/*
99775** Construct a trigger step that implements a DELETE statement and return
99776** a pointer to that trigger step.  The parser calls this routine when it
99777** sees a DELETE statement inside the body of a CREATE TRIGGER.
99778*/
99779SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
99780  sqlite3 *db,            /* Database connection */
99781  Token *pTableName,      /* The table from which rows are deleted */
99782  Expr *pWhere            /* The WHERE clause */
99783){
99784  TriggerStep *pTriggerStep;
99785
99786  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
99787  if( pTriggerStep ){
99788    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99789    pTriggerStep->orconf = OE_Default;
99790  }
99791  sqlite3ExprDelete(db, pWhere);
99792  return pTriggerStep;
99793}
99794
99795/*
99796** Recursively delete a Trigger structure
99797*/
99798SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
99799  if( pTrigger==0 ) return;
99800  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
99801  sqlite3DbFree(db, pTrigger->zName);
99802  sqlite3DbFree(db, pTrigger->table);
99803  sqlite3ExprDelete(db, pTrigger->pWhen);
99804  sqlite3IdListDelete(db, pTrigger->pColumns);
99805  sqlite3DbFree(db, pTrigger);
99806}
99807
99808/*
99809** This function is called to drop a trigger from the database schema.
99810**
99811** This may be called directly from the parser and therefore identifies
99812** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
99813** same job as this routine except it takes a pointer to the trigger
99814** instead of the trigger name.
99815**/
99816SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
99817  Trigger *pTrigger = 0;
99818  int i;
99819  const char *zDb;
99820  const char *zName;
99821  int nName;
99822  sqlite3 *db = pParse->db;
99823
99824  if( db->mallocFailed ) goto drop_trigger_cleanup;
99825  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
99826    goto drop_trigger_cleanup;
99827  }
99828
99829  assert( pName->nSrc==1 );
99830  zDb = pName->a[0].zDatabase;
99831  zName = pName->a[0].zName;
99832  nName = sqlite3Strlen30(zName);
99833  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
99834  for(i=OMIT_TEMPDB; i<db->nDb; i++){
99835    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
99836    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
99837    assert( sqlite3SchemaMutexHeld(db, j, 0) );
99838    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
99839    if( pTrigger ) break;
99840  }
99841  if( !pTrigger ){
99842    if( !noErr ){
99843      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
99844    }else{
99845      sqlite3CodeVerifyNamedSchema(pParse, zDb);
99846    }
99847    pParse->checkSchema = 1;
99848    goto drop_trigger_cleanup;
99849  }
99850  sqlite3DropTriggerPtr(pParse, pTrigger);
99851
99852drop_trigger_cleanup:
99853  sqlite3SrcListDelete(db, pName);
99854}
99855
99856/*
99857** Return a pointer to the Table structure for the table that a trigger
99858** is set on.
99859*/
99860static Table *tableOfTrigger(Trigger *pTrigger){
99861  int n = sqlite3Strlen30(pTrigger->table);
99862  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
99863}
99864
99865
99866/*
99867** Drop a trigger given a pointer to that trigger.
99868*/
99869SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
99870  Table   *pTable;
99871  Vdbe *v;
99872  sqlite3 *db = pParse->db;
99873  int iDb;
99874
99875  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
99876  assert( iDb>=0 && iDb<db->nDb );
99877  pTable = tableOfTrigger(pTrigger);
99878  assert( pTable );
99879  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
99880#ifndef SQLITE_OMIT_AUTHORIZATION
99881  {
99882    int code = SQLITE_DROP_TRIGGER;
99883    const char *zDb = db->aDb[iDb].zName;
99884    const char *zTab = SCHEMA_TABLE(iDb);
99885    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
99886    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
99887      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
99888      return;
99889    }
99890  }
99891#endif
99892
99893  /* Generate code to destroy the database record of the trigger.
99894  */
99895  assert( pTable!=0 );
99896  if( (v = sqlite3GetVdbe(pParse))!=0 ){
99897    int base;
99898    static const VdbeOpList dropTrigger[] = {
99899      { OP_Rewind,     0, ADDR(9),  0},
99900      { OP_String8,    0, 1,        0}, /* 1 */
99901      { OP_Column,     0, 1,        2},
99902      { OP_Ne,         2, ADDR(8),  1},
99903      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
99904      { OP_Column,     0, 0,        2},
99905      { OP_Ne,         2, ADDR(8),  1},
99906      { OP_Delete,     0, 0,        0},
99907      { OP_Next,       0, ADDR(1),  0}, /* 8 */
99908    };
99909
99910    sqlite3BeginWriteOperation(pParse, 0, iDb);
99911    sqlite3OpenMasterTable(pParse, iDb);
99912    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
99913    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
99914    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
99915    sqlite3ChangeCookie(pParse, iDb);
99916    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
99917    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
99918    if( pParse->nMem<3 ){
99919      pParse->nMem = 3;
99920    }
99921  }
99922}
99923
99924/*
99925** Remove a trigger from the hash tables of the sqlite* pointer.
99926*/
99927SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
99928  Trigger *pTrigger;
99929  Hash *pHash;
99930
99931  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99932  pHash = &(db->aDb[iDb].pSchema->trigHash);
99933  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
99934  if( ALWAYS(pTrigger) ){
99935    if( pTrigger->pSchema==pTrigger->pTabSchema ){
99936      Table *pTab = tableOfTrigger(pTrigger);
99937      Trigger **pp;
99938      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
99939      *pp = (*pp)->pNext;
99940    }
99941    sqlite3DeleteTrigger(db, pTrigger);
99942    db->flags |= SQLITE_InternChanges;
99943  }
99944}
99945
99946/*
99947** pEList is the SET clause of an UPDATE statement.  Each entry
99948** in pEList is of the format <id>=<expr>.  If any of the entries
99949** in pEList have an <id> which matches an identifier in pIdList,
99950** then return TRUE.  If pIdList==NULL, then it is considered a
99951** wildcard that matches anything.  Likewise if pEList==NULL then
99952** it matches anything so always return true.  Return false only
99953** if there is no match.
99954*/
99955static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
99956  int e;
99957  if( pIdList==0 || NEVER(pEList==0) ) return 1;
99958  for(e=0; e<pEList->nExpr; e++){
99959    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
99960  }
99961  return 0;
99962}
99963
99964/*
99965** Return a list of all triggers on table pTab if there exists at least
99966** one trigger that must be fired when an operation of type 'op' is
99967** performed on the table, and, if that operation is an UPDATE, if at
99968** least one of the columns in pChanges is being modified.
99969*/
99970SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
99971  Parse *pParse,          /* Parse context */
99972  Table *pTab,            /* The table the contains the triggers */
99973  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
99974  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
99975  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
99976){
99977  int mask = 0;
99978  Trigger *pList = 0;
99979  Trigger *p;
99980
99981  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
99982    pList = sqlite3TriggerList(pParse, pTab);
99983  }
99984  assert( pList==0 || IsVirtual(pTab)==0 );
99985  for(p=pList; p; p=p->pNext){
99986    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
99987      mask |= p->tr_tm;
99988    }
99989  }
99990  if( pMask ){
99991    *pMask = mask;
99992  }
99993  return (mask ? pList : 0);
99994}
99995
99996/*
99997** Convert the pStep->target token into a SrcList and return a pointer
99998** to that SrcList.
99999**
100000** This routine adds a specific database name, if needed, to the target when
100001** forming the SrcList.  This prevents a trigger in one database from
100002** referring to a target in another database.  An exception is when the
100003** trigger is in TEMP in which case it can refer to any other database it
100004** wants.
100005*/
100006static SrcList *targetSrcList(
100007  Parse *pParse,       /* The parsing context */
100008  TriggerStep *pStep   /* The trigger containing the target token */
100009){
100010  int iDb;             /* Index of the database to use */
100011  SrcList *pSrc;       /* SrcList to be returned */
100012
100013  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
100014  if( pSrc ){
100015    assert( pSrc->nSrc>0 );
100016    assert( pSrc->a!=0 );
100017    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
100018    if( iDb==0 || iDb>=2 ){
100019      sqlite3 *db = pParse->db;
100020      assert( iDb<pParse->db->nDb );
100021      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
100022    }
100023  }
100024  return pSrc;
100025}
100026
100027/*
100028** Generate VDBE code for the statements inside the body of a single
100029** trigger.
100030*/
100031static int codeTriggerProgram(
100032  Parse *pParse,            /* The parser context */
100033  TriggerStep *pStepList,   /* List of statements inside the trigger body */
100034  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
100035){
100036  TriggerStep *pStep;
100037  Vdbe *v = pParse->pVdbe;
100038  sqlite3 *db = pParse->db;
100039
100040  assert( pParse->pTriggerTab && pParse->pToplevel );
100041  assert( pStepList );
100042  assert( v!=0 );
100043  for(pStep=pStepList; pStep; pStep=pStep->pNext){
100044    /* Figure out the ON CONFLICT policy that will be used for this step
100045    ** of the trigger program. If the statement that caused this trigger
100046    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
100047    ** the ON CONFLICT policy that was specified as part of the trigger
100048    ** step statement. Example:
100049    **
100050    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
100051    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
100052    **   END;
100053    **
100054    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
100055    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
100056    */
100057    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
100058
100059    switch( pStep->op ){
100060      case TK_UPDATE: {
100061        sqlite3Update(pParse,
100062          targetSrcList(pParse, pStep),
100063          sqlite3ExprListDup(db, pStep->pExprList, 0),
100064          sqlite3ExprDup(db, pStep->pWhere, 0),
100065          pParse->eOrconf
100066        );
100067        break;
100068      }
100069      case TK_INSERT: {
100070        sqlite3Insert(pParse,
100071          targetSrcList(pParse, pStep),
100072          sqlite3ExprListDup(db, pStep->pExprList, 0),
100073          sqlite3SelectDup(db, pStep->pSelect, 0),
100074          sqlite3IdListDup(db, pStep->pIdList),
100075          pParse->eOrconf
100076        );
100077        break;
100078      }
100079      case TK_DELETE: {
100080        sqlite3DeleteFrom(pParse,
100081          targetSrcList(pParse, pStep),
100082          sqlite3ExprDup(db, pStep->pWhere, 0)
100083        );
100084        break;
100085      }
100086      default: assert( pStep->op==TK_SELECT ); {
100087        SelectDest sDest;
100088        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
100089        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
100090        sqlite3Select(pParse, pSelect, &sDest);
100091        sqlite3SelectDelete(db, pSelect);
100092        break;
100093      }
100094    }
100095    if( pStep->op!=TK_SELECT ){
100096      sqlite3VdbeAddOp0(v, OP_ResetCount);
100097    }
100098  }
100099
100100  return 0;
100101}
100102
100103#ifdef SQLITE_DEBUG
100104/*
100105** This function is used to add VdbeComment() annotations to a VDBE
100106** program. It is not used in production code, only for debugging.
100107*/
100108static const char *onErrorText(int onError){
100109  switch( onError ){
100110    case OE_Abort:    return "abort";
100111    case OE_Rollback: return "rollback";
100112    case OE_Fail:     return "fail";
100113    case OE_Replace:  return "replace";
100114    case OE_Ignore:   return "ignore";
100115    case OE_Default:  return "default";
100116  }
100117  return "n/a";
100118}
100119#endif
100120
100121/*
100122** Parse context structure pFrom has just been used to create a sub-vdbe
100123** (trigger program). If an error has occurred, transfer error information
100124** from pFrom to pTo.
100125*/
100126static void transferParseError(Parse *pTo, Parse *pFrom){
100127  assert( pFrom->zErrMsg==0 || pFrom->nErr );
100128  assert( pTo->zErrMsg==0 || pTo->nErr );
100129  if( pTo->nErr==0 ){
100130    pTo->zErrMsg = pFrom->zErrMsg;
100131    pTo->nErr = pFrom->nErr;
100132  }else{
100133    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
100134  }
100135}
100136
100137/*
100138** Create and populate a new TriggerPrg object with a sub-program
100139** implementing trigger pTrigger with ON CONFLICT policy orconf.
100140*/
100141static TriggerPrg *codeRowTrigger(
100142  Parse *pParse,       /* Current parse context */
100143  Trigger *pTrigger,   /* Trigger to code */
100144  Table *pTab,         /* The table pTrigger is attached to */
100145  int orconf           /* ON CONFLICT policy to code trigger program with */
100146){
100147  Parse *pTop = sqlite3ParseToplevel(pParse);
100148  sqlite3 *db = pParse->db;   /* Database handle */
100149  TriggerPrg *pPrg;           /* Value to return */
100150  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
100151  Vdbe *v;                    /* Temporary VM */
100152  NameContext sNC;            /* Name context for sub-vdbe */
100153  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
100154  Parse *pSubParse;           /* Parse context for sub-vdbe */
100155  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
100156
100157  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
100158  assert( pTop->pVdbe );
100159
100160  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
100161  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
100162  ** list of the top-level Parse object sooner rather than later.  */
100163  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
100164  if( !pPrg ) return 0;
100165  pPrg->pNext = pTop->pTriggerPrg;
100166  pTop->pTriggerPrg = pPrg;
100167  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
100168  if( !pProgram ) return 0;
100169  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
100170  pPrg->pTrigger = pTrigger;
100171  pPrg->orconf = orconf;
100172  pPrg->aColmask[0] = 0xffffffff;
100173  pPrg->aColmask[1] = 0xffffffff;
100174
100175  /* Allocate and populate a new Parse context to use for coding the
100176  ** trigger sub-program.  */
100177  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
100178  if( !pSubParse ) return 0;
100179  memset(&sNC, 0, sizeof(sNC));
100180  sNC.pParse = pSubParse;
100181  pSubParse->db = db;
100182  pSubParse->pTriggerTab = pTab;
100183  pSubParse->pToplevel = pTop;
100184  pSubParse->zAuthContext = pTrigger->zName;
100185  pSubParse->eTriggerOp = pTrigger->op;
100186  pSubParse->nQueryLoop = pParse->nQueryLoop;
100187
100188  v = sqlite3GetVdbe(pSubParse);
100189  if( v ){
100190    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
100191      pTrigger->zName, onErrorText(orconf),
100192      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
100193        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
100194        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
100195        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
100196      pTab->zName
100197    ));
100198#ifndef SQLITE_OMIT_TRACE
100199    sqlite3VdbeChangeP4(v, -1,
100200      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
100201    );
100202#endif
100203
100204    /* If one was specified, code the WHEN clause. If it evaluates to false
100205    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
100206    ** OP_Halt inserted at the end of the program.  */
100207    if( pTrigger->pWhen ){
100208      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
100209      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
100210       && db->mallocFailed==0
100211      ){
100212        iEndTrigger = sqlite3VdbeMakeLabel(v);
100213        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
100214      }
100215      sqlite3ExprDelete(db, pWhen);
100216    }
100217
100218    /* Code the trigger program into the sub-vdbe. */
100219    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
100220
100221    /* Insert an OP_Halt at the end of the sub-program. */
100222    if( iEndTrigger ){
100223      sqlite3VdbeResolveLabel(v, iEndTrigger);
100224    }
100225    sqlite3VdbeAddOp0(v, OP_Halt);
100226    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
100227
100228    transferParseError(pParse, pSubParse);
100229    if( db->mallocFailed==0 ){
100230      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
100231    }
100232    pProgram->nMem = pSubParse->nMem;
100233    pProgram->nCsr = pSubParse->nTab;
100234    pProgram->nOnce = pSubParse->nOnce;
100235    pProgram->token = (void *)pTrigger;
100236    pPrg->aColmask[0] = pSubParse->oldmask;
100237    pPrg->aColmask[1] = pSubParse->newmask;
100238    sqlite3VdbeDelete(v);
100239  }
100240
100241  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
100242  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
100243  sqlite3StackFree(db, pSubParse);
100244
100245  return pPrg;
100246}
100247
100248/*
100249** Return a pointer to a TriggerPrg object containing the sub-program for
100250** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
100251** TriggerPrg object exists, a new object is allocated and populated before
100252** being returned.
100253*/
100254static TriggerPrg *getRowTrigger(
100255  Parse *pParse,       /* Current parse context */
100256  Trigger *pTrigger,   /* Trigger to code */
100257  Table *pTab,         /* The table trigger pTrigger is attached to */
100258  int orconf           /* ON CONFLICT algorithm. */
100259){
100260  Parse *pRoot = sqlite3ParseToplevel(pParse);
100261  TriggerPrg *pPrg;
100262
100263  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
100264
100265  /* It may be that this trigger has already been coded (or is in the
100266  ** process of being coded). If this is the case, then an entry with
100267  ** a matching TriggerPrg.pTrigger field will be present somewhere
100268  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
100269  for(pPrg=pRoot->pTriggerPrg;
100270      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
100271      pPrg=pPrg->pNext
100272  );
100273
100274  /* If an existing TriggerPrg could not be located, create a new one. */
100275  if( !pPrg ){
100276    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
100277  }
100278
100279  return pPrg;
100280}
100281
100282/*
100283** Generate code for the trigger program associated with trigger p on
100284** table pTab. The reg, orconf and ignoreJump parameters passed to this
100285** function are the same as those described in the header function for
100286** sqlite3CodeRowTrigger()
100287*/
100288SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
100289  Parse *pParse,       /* Parse context */
100290  Trigger *p,          /* Trigger to code */
100291  Table *pTab,         /* The table to code triggers from */
100292  int reg,             /* Reg array containing OLD.* and NEW.* values */
100293  int orconf,          /* ON CONFLICT policy */
100294  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
100295){
100296  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
100297  TriggerPrg *pPrg;
100298  pPrg = getRowTrigger(pParse, p, pTab, orconf);
100299  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
100300
100301  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
100302  ** is a pointer to the sub-vdbe containing the trigger program.  */
100303  if( pPrg ){
100304    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
100305
100306    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
100307    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
100308    VdbeComment(
100309        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
100310
100311    /* Set the P5 operand of the OP_Program instruction to non-zero if
100312    ** recursive invocation of this trigger program is disallowed. Recursive
100313    ** invocation is disallowed if (a) the sub-program is really a trigger,
100314    ** not a foreign key action, and (b) the flag to enable recursive triggers
100315    ** is clear.  */
100316    sqlite3VdbeChangeP5(v, (u8)bRecursive);
100317  }
100318}
100319
100320/*
100321** This is called to code the required FOR EACH ROW triggers for an operation
100322** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
100323** is given by the op paramater. The tr_tm parameter determines whether the
100324** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
100325** parameter pChanges is passed the list of columns being modified.
100326**
100327** If there are no triggers that fire at the specified time for the specified
100328** operation on pTab, this function is a no-op.
100329**
100330** The reg argument is the address of the first in an array of registers
100331** that contain the values substituted for the new.* and old.* references
100332** in the trigger program. If N is the number of columns in table pTab
100333** (a copy of pTab->nCol), then registers are populated as follows:
100334**
100335**   Register       Contains
100336**   ------------------------------------------------------
100337**   reg+0          OLD.rowid
100338**   reg+1          OLD.* value of left-most column of pTab
100339**   ...            ...
100340**   reg+N          OLD.* value of right-most column of pTab
100341**   reg+N+1        NEW.rowid
100342**   reg+N+2        OLD.* value of left-most column of pTab
100343**   ...            ...
100344**   reg+N+N+1      NEW.* value of right-most column of pTab
100345**
100346** For ON DELETE triggers, the registers containing the NEW.* values will
100347** never be accessed by the trigger program, so they are not allocated or
100348** populated by the caller (there is no data to populate them with anyway).
100349** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
100350** are never accessed, and so are not allocated by the caller. So, for an
100351** ON INSERT trigger, the value passed to this function as parameter reg
100352** is not a readable register, although registers (reg+N) through
100353** (reg+N+N+1) are.
100354**
100355** Parameter orconf is the default conflict resolution algorithm for the
100356** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
100357** is the instruction that control should jump to if a trigger program
100358** raises an IGNORE exception.
100359*/
100360SQLITE_PRIVATE void sqlite3CodeRowTrigger(
100361  Parse *pParse,       /* Parse context */
100362  Trigger *pTrigger,   /* List of triggers on table pTab */
100363  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
100364  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100365  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
100366  Table *pTab,         /* The table to code triggers from */
100367  int reg,             /* The first in an array of registers (see above) */
100368  int orconf,          /* ON CONFLICT policy */
100369  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
100370){
100371  Trigger *p;          /* Used to iterate through pTrigger list */
100372
100373  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
100374  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
100375  assert( (op==TK_UPDATE)==(pChanges!=0) );
100376
100377  for(p=pTrigger; p; p=p->pNext){
100378
100379    /* Sanity checking:  The schema for the trigger and for the table are
100380    ** always defined.  The trigger must be in the same schema as the table
100381    ** or else it must be a TEMP trigger. */
100382    assert( p->pSchema!=0 );
100383    assert( p->pTabSchema!=0 );
100384    assert( p->pSchema==p->pTabSchema
100385         || p->pSchema==pParse->db->aDb[1].pSchema );
100386
100387    /* Determine whether we should code this trigger */
100388    if( p->op==op
100389     && p->tr_tm==tr_tm
100390     && checkColumnOverlap(p->pColumns, pChanges)
100391    ){
100392      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
100393    }
100394  }
100395}
100396
100397/*
100398** Triggers may access values stored in the old.* or new.* pseudo-table.
100399** This function returns a 32-bit bitmask indicating which columns of the
100400** old.* or new.* tables actually are used by triggers. This information
100401** may be used by the caller, for example, to avoid having to load the entire
100402** old.* record into memory when executing an UPDATE or DELETE command.
100403**
100404** Bit 0 of the returned mask is set if the left-most column of the
100405** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
100406** the second leftmost column value is required, and so on. If there
100407** are more than 32 columns in the table, and at least one of the columns
100408** with an index greater than 32 may be accessed, 0xffffffff is returned.
100409**
100410** It is not possible to determine if the old.rowid or new.rowid column is
100411** accessed by triggers. The caller must always assume that it is.
100412**
100413** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
100414** applies to the old.* table. If 1, the new.* table.
100415**
100416** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
100417** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
100418** included in the returned mask if the TRIGGER_BEFORE bit is set in the
100419** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
100420** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
100421*/
100422SQLITE_PRIVATE u32 sqlite3TriggerColmask(
100423  Parse *pParse,       /* Parse context */
100424  Trigger *pTrigger,   /* List of triggers on table pTab */
100425  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100426  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
100427  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100428  Table *pTab,         /* The table to code triggers from */
100429  int orconf           /* Default ON CONFLICT policy for trigger steps */
100430){
100431  const int op = pChanges ? TK_UPDATE : TK_DELETE;
100432  u32 mask = 0;
100433  Trigger *p;
100434
100435  assert( isNew==1 || isNew==0 );
100436  for(p=pTrigger; p; p=p->pNext){
100437    if( p->op==op && (tr_tm&p->tr_tm)
100438     && checkColumnOverlap(p->pColumns,pChanges)
100439    ){
100440      TriggerPrg *pPrg;
100441      pPrg = getRowTrigger(pParse, p, pTab, orconf);
100442      if( pPrg ){
100443        mask |= pPrg->aColmask[isNew];
100444      }
100445    }
100446  }
100447
100448  return mask;
100449}
100450
100451#endif /* !defined(SQLITE_OMIT_TRIGGER) */
100452
100453/************** End of trigger.c *********************************************/
100454/************** Begin file update.c ******************************************/
100455/*
100456** 2001 September 15
100457**
100458** The author disclaims copyright to this source code.  In place of
100459** a legal notice, here is a blessing:
100460**
100461**    May you do good and not evil.
100462**    May you find forgiveness for yourself and forgive others.
100463**    May you share freely, never taking more than you give.
100464**
100465*************************************************************************
100466** This file contains C code routines that are called by the parser
100467** to handle UPDATE statements.
100468*/
100469
100470#ifndef SQLITE_OMIT_VIRTUALTABLE
100471/* Forward declaration */
100472static void updateVirtualTable(
100473  Parse *pParse,       /* The parsing context */
100474  SrcList *pSrc,       /* The virtual table to be modified */
100475  Table *pTab,         /* The virtual table */
100476  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
100477  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
100478  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
100479  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
100480  int onError          /* ON CONFLICT strategy */
100481);
100482#endif /* SQLITE_OMIT_VIRTUALTABLE */
100483
100484/*
100485** The most recently coded instruction was an OP_Column to retrieve the
100486** i-th column of table pTab. This routine sets the P4 parameter of the
100487** OP_Column to the default value, if any.
100488**
100489** The default value of a column is specified by a DEFAULT clause in the
100490** column definition. This was either supplied by the user when the table
100491** was created, or added later to the table definition by an ALTER TABLE
100492** command. If the latter, then the row-records in the table btree on disk
100493** may not contain a value for the column and the default value, taken
100494** from the P4 parameter of the OP_Column instruction, is returned instead.
100495** If the former, then all row-records are guaranteed to include a value
100496** for the column and the P4 value is not required.
100497**
100498** Column definitions created by an ALTER TABLE command may only have
100499** literal default values specified: a number, null or a string. (If a more
100500** complicated default expression value was provided, it is evaluated
100501** when the ALTER TABLE is executed and one of the literal values written
100502** into the sqlite_master table.)
100503**
100504** Therefore, the P4 parameter is only required if the default value for
100505** the column is a literal number, string or null. The sqlite3ValueFromExpr()
100506** function is capable of transforming these types of expressions into
100507** sqlite3_value objects.
100508**
100509** If parameter iReg is not negative, code an OP_RealAffinity instruction
100510** on register iReg. This is used when an equivalent integer value is
100511** stored in place of an 8-byte floating point value in order to save
100512** space.
100513*/
100514SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
100515  assert( pTab!=0 );
100516  if( !pTab->pSelect ){
100517    sqlite3_value *pValue;
100518    u8 enc = ENC(sqlite3VdbeDb(v));
100519    Column *pCol = &pTab->aCol[i];
100520    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
100521    assert( i<pTab->nCol );
100522    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
100523                         pCol->affinity, &pValue);
100524    if( pValue ){
100525      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
100526    }
100527#ifndef SQLITE_OMIT_FLOATING_POINT
100528    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
100529      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
100530    }
100531#endif
100532  }
100533}
100534
100535/*
100536** Process an UPDATE statement.
100537**
100538**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
100539**          \_______/ \________/     \______/       \________________/
100540*            onError   pTabList      pChanges             pWhere
100541*/
100542SQLITE_PRIVATE void sqlite3Update(
100543  Parse *pParse,         /* The parser context */
100544  SrcList *pTabList,     /* The table in which we should change things */
100545  ExprList *pChanges,    /* Things to be changed */
100546  Expr *pWhere,          /* The WHERE clause.  May be null */
100547  int onError            /* How to handle constraint errors */
100548){
100549  int i, j;              /* Loop counters */
100550  Table *pTab;           /* The table to be updated */
100551  int addr = 0;          /* VDBE instruction address of the start of the loop */
100552  WhereInfo *pWInfo;     /* Information about the WHERE clause */
100553  Vdbe *v;               /* The virtual database engine */
100554  Index *pIdx;           /* For looping over indices */
100555  int nIdx;              /* Number of indices that need updating */
100556  int iCur;              /* VDBE Cursor number of pTab */
100557  sqlite3 *db;           /* The database structure */
100558  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
100559  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
100560                         ** an expression for the i-th column of the table.
100561                         ** aXRef[i]==-1 if the i-th column is not changed. */
100562  int chngRowid;         /* True if the record number is being changed */
100563  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
100564  int openAll = 0;       /* True if all indices need to be opened */
100565  AuthContext sContext;  /* The authorization context */
100566  NameContext sNC;       /* The name-context to resolve expressions in */
100567  int iDb;               /* Database containing the table being updated */
100568  int okOnePass;         /* True for one-pass algorithm without the FIFO */
100569  int hasFK;             /* True if foreign key processing is required */
100570
100571#ifndef SQLITE_OMIT_TRIGGER
100572  int isView;            /* True when updating a view (INSTEAD OF trigger) */
100573  Trigger *pTrigger;     /* List of triggers on pTab, if required */
100574  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100575#endif
100576  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
100577
100578  /* Register Allocations */
100579  int regRowCount = 0;   /* A count of rows changed */
100580  int regOldRowid;       /* The old rowid */
100581  int regNewRowid;       /* The new rowid */
100582  int regNew;            /* Content of the NEW.* table in triggers */
100583  int regOld = 0;        /* Content of OLD.* table in triggers */
100584  int regRowSet = 0;     /* Rowset of rows to be updated */
100585
100586  memset(&sContext, 0, sizeof(sContext));
100587  db = pParse->db;
100588  if( pParse->nErr || db->mallocFailed ){
100589    goto update_cleanup;
100590  }
100591  assert( pTabList->nSrc==1 );
100592
100593  /* Locate the table which we want to update.
100594  */
100595  pTab = sqlite3SrcListLookup(pParse, pTabList);
100596  if( pTab==0 ) goto update_cleanup;
100597  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100598
100599  /* Figure out if we have any triggers and if the table being
100600  ** updated is a view.
100601  */
100602#ifndef SQLITE_OMIT_TRIGGER
100603  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
100604  isView = pTab->pSelect!=0;
100605  assert( pTrigger || tmask==0 );
100606#else
100607# define pTrigger 0
100608# define isView 0
100609# define tmask 0
100610#endif
100611#ifdef SQLITE_OMIT_VIEW
100612# undef isView
100613# define isView 0
100614#endif
100615
100616  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
100617    goto update_cleanup;
100618  }
100619  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
100620    goto update_cleanup;
100621  }
100622  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
100623  if( aXRef==0 ) goto update_cleanup;
100624  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
100625
100626  /* Allocate a cursors for the main database table and for all indices.
100627  ** The index cursors might not be used, but if they are used they
100628  ** need to occur right after the database cursor.  So go ahead and
100629  ** allocate enough space, just in case.
100630  */
100631  pTabList->a[0].iCursor = iCur = pParse->nTab++;
100632  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100633    pParse->nTab++;
100634  }
100635
100636  /* Initialize the name-context */
100637  memset(&sNC, 0, sizeof(sNC));
100638  sNC.pParse = pParse;
100639  sNC.pSrcList = pTabList;
100640
100641  /* Resolve the column names in all the expressions of the
100642  ** of the UPDATE statement.  Also find the column index
100643  ** for each column to be updated in the pChanges array.  For each
100644  ** column to be updated, make sure we have authorization to change
100645  ** that column.
100646  */
100647  chngRowid = 0;
100648  for(i=0; i<pChanges->nExpr; i++){
100649    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
100650      goto update_cleanup;
100651    }
100652    for(j=0; j<pTab->nCol; j++){
100653      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
100654        if( j==pTab->iPKey ){
100655          chngRowid = 1;
100656          pRowidExpr = pChanges->a[i].pExpr;
100657        }
100658        aXRef[j] = i;
100659        break;
100660      }
100661    }
100662    if( j>=pTab->nCol ){
100663      if( sqlite3IsRowid(pChanges->a[i].zName) ){
100664        chngRowid = 1;
100665        pRowidExpr = pChanges->a[i].pExpr;
100666      }else{
100667        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
100668        pParse->checkSchema = 1;
100669        goto update_cleanup;
100670      }
100671    }
100672#ifndef SQLITE_OMIT_AUTHORIZATION
100673    {
100674      int rc;
100675      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
100676                           pTab->aCol[j].zName, db->aDb[iDb].zName);
100677      if( rc==SQLITE_DENY ){
100678        goto update_cleanup;
100679      }else if( rc==SQLITE_IGNORE ){
100680        aXRef[j] = -1;
100681      }
100682    }
100683#endif
100684  }
100685
100686  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
100687
100688  /* Allocate memory for the array aRegIdx[].  There is one entry in the
100689  ** array for each index associated with table being updated.  Fill in
100690  ** the value with a register number for indices that are to be used
100691  ** and with zero for unused indices.
100692  */
100693  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
100694  if( nIdx>0 ){
100695    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
100696    if( aRegIdx==0 ) goto update_cleanup;
100697  }
100698  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
100699    int reg;
100700    if( hasFK || chngRowid ){
100701      reg = ++pParse->nMem;
100702    }else{
100703      reg = 0;
100704      for(i=0; i<pIdx->nColumn; i++){
100705        if( aXRef[pIdx->aiColumn[i]]>=0 ){
100706          reg = ++pParse->nMem;
100707          break;
100708        }
100709      }
100710    }
100711    aRegIdx[j] = reg;
100712  }
100713
100714  /* Begin generating code. */
100715  v = sqlite3GetVdbe(pParse);
100716  if( v==0 ) goto update_cleanup;
100717  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
100718  sqlite3BeginWriteOperation(pParse, 1, iDb);
100719
100720#ifndef SQLITE_OMIT_VIRTUALTABLE
100721  /* Virtual tables must be handled separately */
100722  if( IsVirtual(pTab) ){
100723    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
100724                       pWhere, onError);
100725    pWhere = 0;
100726    pTabList = 0;
100727    goto update_cleanup;
100728  }
100729#endif
100730
100731  /* Allocate required registers. */
100732  regRowSet = ++pParse->nMem;
100733  regOldRowid = regNewRowid = ++pParse->nMem;
100734  if( pTrigger || hasFK ){
100735    regOld = pParse->nMem + 1;
100736    pParse->nMem += pTab->nCol;
100737  }
100738  if( chngRowid || pTrigger || hasFK ){
100739    regNewRowid = ++pParse->nMem;
100740  }
100741  regNew = pParse->nMem + 1;
100742  pParse->nMem += pTab->nCol;
100743
100744  /* Start the view context. */
100745  if( isView ){
100746    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
100747  }
100748
100749  /* If we are trying to update a view, realize that view into
100750  ** a ephemeral table.
100751  */
100752#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
100753  if( isView ){
100754    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
100755  }
100756#endif
100757
100758  /* Resolve the column names in all the expressions in the
100759  ** WHERE clause.
100760  */
100761  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
100762    goto update_cleanup;
100763  }
100764
100765  /* Begin the database scan
100766  */
100767  sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
100768  pWInfo = sqlite3WhereBegin(
100769      pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED
100770  );
100771  if( pWInfo==0 ) goto update_cleanup;
100772  okOnePass = pWInfo->okOnePass;
100773
100774  /* Remember the rowid of every item to be updated.
100775  */
100776  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
100777  if( !okOnePass ){
100778    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
100779  }
100780
100781  /* End the database scan loop.
100782  */
100783  sqlite3WhereEnd(pWInfo);
100784
100785  /* Initialize the count of updated rows
100786  */
100787  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
100788    regRowCount = ++pParse->nMem;
100789    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
100790  }
100791
100792  if( !isView ){
100793    /*
100794    ** Open every index that needs updating.  Note that if any
100795    ** index could potentially invoke a REPLACE conflict resolution
100796    ** action, then we need to open all indices because we might need
100797    ** to be deleting some records.
100798    */
100799    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
100800    if( onError==OE_Replace ){
100801      openAll = 1;
100802    }else{
100803      openAll = 0;
100804      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100805        if( pIdx->onError==OE_Replace ){
100806          openAll = 1;
100807          break;
100808        }
100809      }
100810    }
100811    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100812      assert( aRegIdx );
100813      if( openAll || aRegIdx[i]>0 ){
100814        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
100815        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
100816                       (char*)pKey, P4_KEYINFO_HANDOFF);
100817        assert( pParse->nTab>iCur+i+1 );
100818      }
100819    }
100820  }
100821
100822  /* Top of the update loop */
100823  if( okOnePass ){
100824    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
100825    addr = sqlite3VdbeAddOp0(v, OP_Goto);
100826    sqlite3VdbeJumpHere(v, a1);
100827  }else{
100828    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
100829  }
100830
100831  /* Make cursor iCur point to the record that is being updated. If
100832  ** this record does not exist for some reason (deleted by a trigger,
100833  ** for example, then jump to the next iteration of the RowSet loop.  */
100834  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
100835
100836  /* If the record number will change, set register regNewRowid to
100837  ** contain the new value. If the record number is not being modified,
100838  ** then regNewRowid is the same register as regOldRowid, which is
100839  ** already populated.  */
100840  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
100841  if( chngRowid ){
100842    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
100843    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
100844  }
100845
100846  /* If there are triggers on this table, populate an array of registers
100847  ** with the required old.* column data.  */
100848  if( hasFK || pTrigger ){
100849    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
100850    oldmask |= sqlite3TriggerColmask(pParse,
100851        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
100852    );
100853    for(i=0; i<pTab->nCol; i++){
100854      if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
100855        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
100856      }else{
100857        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
100858      }
100859    }
100860    if( chngRowid==0 ){
100861      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
100862    }
100863  }
100864
100865  /* Populate the array of registers beginning at regNew with the new
100866  ** row data. This array is used to check constaints, create the new
100867  ** table and index records, and as the values for any new.* references
100868  ** made by triggers.
100869  **
100870  ** If there are one or more BEFORE triggers, then do not populate the
100871  ** registers associated with columns that are (a) not modified by
100872  ** this UPDATE statement and (b) not accessed by new.* references. The
100873  ** values for registers not modified by the UPDATE must be reloaded from
100874  ** the database after the BEFORE triggers are fired anyway (as the trigger
100875  ** may have modified them). So not loading those that are not going to
100876  ** be used eliminates some redundant opcodes.
100877  */
100878  newmask = sqlite3TriggerColmask(
100879      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
100880  );
100881  sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
100882  for(i=0; i<pTab->nCol; i++){
100883    if( i==pTab->iPKey ){
100884      /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
100885    }else{
100886      j = aXRef[i];
100887      if( j>=0 ){
100888        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
100889      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
100890        /* This branch loads the value of a column that will not be changed
100891        ** into a register. This is done if there are no BEFORE triggers, or
100892        ** if there are one or more BEFORE triggers that use this value via
100893        ** a new.* reference in a trigger program.
100894        */
100895        testcase( i==31 );
100896        testcase( i==32 );
100897        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
100898        sqlite3ColumnDefault(v, pTab, i, regNew+i);
100899      }
100900    }
100901  }
100902
100903  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
100904  ** verified. One could argue that this is wrong.
100905  */
100906  if( tmask&TRIGGER_BEFORE ){
100907    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
100908    sqlite3TableAffinityStr(v, pTab);
100909    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
100910        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
100911
100912    /* The row-trigger may have deleted the row being updated. In this
100913    ** case, jump to the next row. No updates or AFTER triggers are
100914    ** required. This behaviour - what happens when the row being updated
100915    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
100916    ** documentation.
100917    */
100918    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
100919
100920    /* If it did not delete it, the row-trigger may still have modified
100921    ** some of the columns of the row being updated. Load the values for
100922    ** all columns not modified by the update statement into their
100923    ** registers in case this has happened.
100924    */
100925    for(i=0; i<pTab->nCol; i++){
100926      if( aXRef[i]<0 && i!=pTab->iPKey ){
100927        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
100928        sqlite3ColumnDefault(v, pTab, i, regNew+i);
100929      }
100930    }
100931  }
100932
100933  if( !isView ){
100934    int j1;                       /* Address of jump instruction */
100935
100936    /* Do constraint checks. */
100937    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
100938        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
100939
100940    /* Do FK constraint checks. */
100941    if( hasFK ){
100942      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
100943    }
100944
100945    /* Delete the index entries associated with the current record.  */
100946    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
100947    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
100948
100949    /* If changing the record number, delete the old record.  */
100950    if( hasFK || chngRowid ){
100951      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
100952    }
100953    sqlite3VdbeJumpHere(v, j1);
100954
100955    if( hasFK ){
100956      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
100957    }
100958
100959    /* Insert the new index entries and the new record. */
100960    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
100961
100962    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
100963    ** handle rows (possibly in other tables) that refer via a foreign key
100964    ** to the row just updated. */
100965    if( hasFK ){
100966      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
100967    }
100968  }
100969
100970  /* Increment the row counter
100971  */
100972  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
100973    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
100974  }
100975
100976  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
100977      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
100978
100979  /* Repeat the above with the next record to be updated, until
100980  ** all record selected by the WHERE clause have been updated.
100981  */
100982  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
100983  sqlite3VdbeJumpHere(v, addr);
100984
100985  /* Close all tables */
100986  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100987    assert( aRegIdx );
100988    if( openAll || aRegIdx[i]>0 ){
100989      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
100990    }
100991  }
100992  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
100993
100994  /* Update the sqlite_sequence table by storing the content of the
100995  ** maximum rowid counter values recorded while inserting into
100996  ** autoincrement tables.
100997  */
100998  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
100999    sqlite3AutoincrementEnd(pParse);
101000  }
101001
101002  /*
101003  ** Return the number of rows that were changed. If this routine is
101004  ** generating code because of a call to sqlite3NestedParse(), do not
101005  ** invoke the callback function.
101006  */
101007  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
101008    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
101009    sqlite3VdbeSetNumCols(v, 1);
101010    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
101011  }
101012
101013update_cleanup:
101014  sqlite3AuthContextPop(&sContext);
101015  sqlite3DbFree(db, aRegIdx);
101016  sqlite3DbFree(db, aXRef);
101017  sqlite3SrcListDelete(db, pTabList);
101018  sqlite3ExprListDelete(db, pChanges);
101019  sqlite3ExprDelete(db, pWhere);
101020  return;
101021}
101022/* Make sure "isView" and other macros defined above are undefined. Otherwise
101023** thely may interfere with compilation of other functions in this file
101024** (or in another file, if this file becomes part of the amalgamation).  */
101025#ifdef isView
101026 #undef isView
101027#endif
101028#ifdef pTrigger
101029 #undef pTrigger
101030#endif
101031
101032#ifndef SQLITE_OMIT_VIRTUALTABLE
101033/*
101034** Generate code for an UPDATE of a virtual table.
101035**
101036** The strategy is that we create an ephemerial table that contains
101037** for each row to be changed:
101038**
101039**   (A)  The original rowid of that row.
101040**   (B)  The revised rowid for the row. (note1)
101041**   (C)  The content of every column in the row.
101042**
101043** Then we loop over this ephemeral table and for each row in
101044** the ephermeral table call VUpdate.
101045**
101046** When finished, drop the ephemeral table.
101047**
101048** (note1) Actually, if we know in advance that (A) is always the same
101049** as (B) we only store (A), then duplicate (A) when pulling
101050** it out of the ephemeral table before calling VUpdate.
101051*/
101052static void updateVirtualTable(
101053  Parse *pParse,       /* The parsing context */
101054  SrcList *pSrc,       /* The virtual table to be modified */
101055  Table *pTab,         /* The virtual table */
101056  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
101057  Expr *pRowid,        /* Expression used to recompute the rowid */
101058  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
101059  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
101060  int onError          /* ON CONFLICT strategy */
101061){
101062  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
101063  ExprList *pEList = 0;     /* The result set of the SELECT statement */
101064  Select *pSelect = 0;      /* The SELECT statement */
101065  Expr *pExpr;              /* Temporary expression */
101066  int ephemTab;             /* Table holding the result of the SELECT */
101067  int i;                    /* Loop counter */
101068  int addr;                 /* Address of top of loop */
101069  int iReg;                 /* First register in set passed to OP_VUpdate */
101070  sqlite3 *db = pParse->db; /* Database connection */
101071  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
101072  SelectDest dest;
101073
101074  /* Construct the SELECT statement that will find the new values for
101075  ** all updated rows.
101076  */
101077  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
101078  if( pRowid ){
101079    pEList = sqlite3ExprListAppend(pParse, pEList,
101080                                   sqlite3ExprDup(db, pRowid, 0));
101081  }
101082  assert( pTab->iPKey<0 );
101083  for(i=0; i<pTab->nCol; i++){
101084    if( aXRef[i]>=0 ){
101085      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
101086    }else{
101087      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
101088    }
101089    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
101090  }
101091  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
101092
101093  /* Create the ephemeral table into which the update results will
101094  ** be stored.
101095  */
101096  assert( v );
101097  ephemTab = pParse->nTab++;
101098  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
101099  sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
101100
101101  /* fill the ephemeral table
101102  */
101103  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
101104  sqlite3Select(pParse, pSelect, &dest);
101105
101106  /* Generate code to scan the ephemeral table and call VUpdate. */
101107  iReg = ++pParse->nMem;
101108  pParse->nMem += pTab->nCol+1;
101109  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
101110  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
101111  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
101112  for(i=0; i<pTab->nCol; i++){
101113    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
101114  }
101115  sqlite3VtabMakeWritable(pParse, pTab);
101116  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
101117  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
101118  sqlite3MayAbort(pParse);
101119  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
101120  sqlite3VdbeJumpHere(v, addr);
101121  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
101122
101123  /* Cleanup */
101124  sqlite3SelectDelete(db, pSelect);
101125}
101126#endif /* SQLITE_OMIT_VIRTUALTABLE */
101127
101128/************** End of update.c **********************************************/
101129/************** Begin file vacuum.c ******************************************/
101130/*
101131** 2003 April 6
101132**
101133** The author disclaims copyright to this source code.  In place of
101134** a legal notice, here is a blessing:
101135**
101136**    May you do good and not evil.
101137**    May you find forgiveness for yourself and forgive others.
101138**    May you share freely, never taking more than you give.
101139**
101140*************************************************************************
101141** This file contains code used to implement the VACUUM command.
101142**
101143** Most of the code in this file may be omitted by defining the
101144** SQLITE_OMIT_VACUUM macro.
101145*/
101146
101147#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
101148/*
101149** Finalize a prepared statement.  If there was an error, store the
101150** text of the error message in *pzErrMsg.  Return the result code.
101151*/
101152static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
101153  int rc;
101154  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
101155  if( rc ){
101156    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
101157  }
101158  return rc;
101159}
101160
101161/*
101162** Execute zSql on database db. Return an error code.
101163*/
101164static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
101165  sqlite3_stmt *pStmt;
101166  VVA_ONLY( int rc; )
101167  if( !zSql ){
101168    return SQLITE_NOMEM;
101169  }
101170  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
101171    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
101172    return sqlite3_errcode(db);
101173  }
101174  VVA_ONLY( rc = ) sqlite3_step(pStmt);
101175  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
101176  return vacuumFinalize(db, pStmt, pzErrMsg);
101177}
101178
101179/*
101180** Execute zSql on database db. The statement returns exactly
101181** one column. Execute this as SQL on the same database.
101182*/
101183static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
101184  sqlite3_stmt *pStmt;
101185  int rc;
101186
101187  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
101188  if( rc!=SQLITE_OK ) return rc;
101189
101190  while( SQLITE_ROW==sqlite3_step(pStmt) ){
101191    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
101192    if( rc!=SQLITE_OK ){
101193      vacuumFinalize(db, pStmt, pzErrMsg);
101194      return rc;
101195    }
101196  }
101197
101198  return vacuumFinalize(db, pStmt, pzErrMsg);
101199}
101200
101201/*
101202** The non-standard VACUUM command is used to clean up the database,
101203** collapse free space, etc.  It is modelled after the VACUUM command
101204** in PostgreSQL.
101205**
101206** In version 1.0.x of SQLite, the VACUUM command would call
101207** gdbm_reorganize() on all the database tables.  But beginning
101208** with 2.0.0, SQLite no longer uses GDBM so this command has
101209** become a no-op.
101210*/
101211SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
101212  Vdbe *v = sqlite3GetVdbe(pParse);
101213  if( v ){
101214    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
101215  }
101216  return;
101217}
101218
101219/*
101220** This routine implements the OP_Vacuum opcode of the VDBE.
101221*/
101222SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
101223  int rc = SQLITE_OK;     /* Return code from service routines */
101224  Btree *pMain;           /* The database being vacuumed */
101225  Btree *pTemp;           /* The temporary database we vacuum into */
101226  char *zSql = 0;         /* SQL statements */
101227  int saved_flags;        /* Saved value of the db->flags */
101228  int saved_nChange;      /* Saved value of db->nChange */
101229  int saved_nTotalChange; /* Saved value of db->nTotalChange */
101230  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
101231  Db *pDb = 0;            /* Database to detach at end of vacuum */
101232  int isMemDb;            /* True if vacuuming a :memory: database */
101233  int nRes;               /* Bytes of reserved space at the end of each page */
101234  int nDb;                /* Number of attached databases */
101235
101236  if( !db->autoCommit ){
101237    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
101238    return SQLITE_ERROR;
101239  }
101240  if( db->activeVdbeCnt>1 ){
101241    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
101242    return SQLITE_ERROR;
101243  }
101244
101245  /* Save the current value of the database flags so that it can be
101246  ** restored before returning. Then set the writable-schema flag, and
101247  ** disable CHECK and foreign key constraints.  */
101248  saved_flags = db->flags;
101249  saved_nChange = db->nChange;
101250  saved_nTotalChange = db->nTotalChange;
101251  saved_xTrace = db->xTrace;
101252  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
101253  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
101254  db->xTrace = 0;
101255
101256  pMain = db->aDb[0].pBt;
101257  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
101258
101259  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
101260  ** can be set to 'off' for this file, as it is not recovered if a crash
101261  ** occurs anyway. The integrity of the database is maintained by a
101262  ** (possibly synchronous) transaction opened on the main database before
101263  ** sqlite3BtreeCopyFile() is called.
101264  **
101265  ** An optimisation would be to use a non-journaled pager.
101266  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
101267  ** that actually made the VACUUM run slower.  Very little journalling
101268  ** actually occurs when doing a vacuum since the vacuum_db is initially
101269  ** empty.  Only the journal header is written.  Apparently it takes more
101270  ** time to parse and run the PRAGMA to turn journalling off than it does
101271  ** to write the journal header file.
101272  */
101273  nDb = db->nDb;
101274  if( sqlite3TempInMemory(db) ){
101275    zSql = "ATTACH ':memory:' AS vacuum_db;";
101276  }else{
101277    zSql = "ATTACH '' AS vacuum_db;";
101278  }
101279  rc = execSql(db, pzErrMsg, zSql);
101280  if( db->nDb>nDb ){
101281    pDb = &db->aDb[db->nDb-1];
101282    assert( strcmp(pDb->zName,"vacuum_db")==0 );
101283  }
101284  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101285  pTemp = db->aDb[db->nDb-1].pBt;
101286
101287  /* The call to execSql() to attach the temp database has left the file
101288  ** locked (as there was more than one active statement when the transaction
101289  ** to read the schema was concluded. Unlock it here so that this doesn't
101290  ** cause problems for the call to BtreeSetPageSize() below.  */
101291  sqlite3BtreeCommit(pTemp);
101292
101293  nRes = sqlite3BtreeGetReserve(pMain);
101294
101295  /* A VACUUM cannot change the pagesize of an encrypted database. */
101296#ifdef SQLITE_HAS_CODEC
101297  if( db->nextPagesize ){
101298    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
101299    int nKey;
101300    char *zKey;
101301    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
101302    if( nKey ) db->nextPagesize = 0;
101303  }
101304#endif
101305
101306  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
101307  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101308
101309  /* Begin a transaction and take an exclusive lock on the main database
101310  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
101311  ** to ensure that we do not try to change the page-size on a WAL database.
101312  */
101313  rc = execSql(db, pzErrMsg, "BEGIN;");
101314  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101315  rc = sqlite3BtreeBeginTrans(pMain, 2);
101316  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101317
101318  /* Do not attempt to change the page size for a WAL database */
101319  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
101320                                               ==PAGER_JOURNALMODE_WAL ){
101321    db->nextPagesize = 0;
101322  }
101323
101324  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
101325   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
101326   || NEVER(db->mallocFailed)
101327  ){
101328    rc = SQLITE_NOMEM;
101329    goto end_of_vacuum;
101330  }
101331
101332#ifndef SQLITE_OMIT_AUTOVACUUM
101333  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
101334                                           sqlite3BtreeGetAutoVacuum(pMain));
101335#endif
101336
101337  /* Query the schema of the main database. Create a mirror schema
101338  ** in the temporary database.
101339  */
101340  rc = execExecSql(db, pzErrMsg,
101341      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
101342      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
101343      "   AND rootpage>0"
101344  );
101345  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101346  rc = execExecSql(db, pzErrMsg,
101347      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
101348      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
101349  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101350  rc = execExecSql(db, pzErrMsg,
101351      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
101352      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
101353  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101354
101355  /* Loop through the tables in the main database. For each, do
101356  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
101357  ** the contents to the temporary database.
101358  */
101359  rc = execExecSql(db, pzErrMsg,
101360      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
101361      "|| ' SELECT * FROM main.' || quote(name) || ';'"
101362      "FROM main.sqlite_master "
101363      "WHERE type = 'table' AND name!='sqlite_sequence' "
101364      "  AND rootpage>0"
101365  );
101366  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101367
101368  /* Copy over the sequence table
101369  */
101370  rc = execExecSql(db, pzErrMsg,
101371      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
101372      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
101373  );
101374  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101375  rc = execExecSql(db, pzErrMsg,
101376      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
101377      "|| ' SELECT * FROM main.' || quote(name) || ';' "
101378      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
101379  );
101380  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101381
101382
101383  /* Copy the triggers, views, and virtual tables from the main database
101384  ** over to the temporary database.  None of these objects has any
101385  ** associated storage, so all we have to do is copy their entries
101386  ** from the SQLITE_MASTER table.
101387  */
101388  rc = execSql(db, pzErrMsg,
101389      "INSERT INTO vacuum_db.sqlite_master "
101390      "  SELECT type, name, tbl_name, rootpage, sql"
101391      "    FROM main.sqlite_master"
101392      "   WHERE type='view' OR type='trigger'"
101393      "      OR (type='table' AND rootpage=0)"
101394  );
101395  if( rc ) goto end_of_vacuum;
101396
101397  /* At this point, there is a write transaction open on both the
101398  ** vacuum database and the main database. Assuming no error occurs,
101399  ** both transactions are closed by this block - the main database
101400  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
101401  ** call to sqlite3BtreeCommit().
101402  */
101403  {
101404    u32 meta;
101405    int i;
101406
101407    /* This array determines which meta meta values are preserved in the
101408    ** vacuum.  Even entries are the meta value number and odd entries
101409    ** are an increment to apply to the meta value after the vacuum.
101410    ** The increment is used to increase the schema cookie so that other
101411    ** connections to the same database will know to reread the schema.
101412    */
101413    static const unsigned char aCopy[] = {
101414       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
101415       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
101416       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
101417       BTREE_USER_VERSION,       0,  /* Preserve the user version */
101418    };
101419
101420    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
101421    assert( 1==sqlite3BtreeIsInTrans(pMain) );
101422
101423    /* Copy Btree meta values */
101424    for(i=0; i<ArraySize(aCopy); i+=2){
101425      /* GetMeta() and UpdateMeta() cannot fail in this context because
101426      ** we already have page 1 loaded into cache and marked dirty. */
101427      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
101428      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
101429      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
101430    }
101431
101432    rc = sqlite3BtreeCopyFile(pMain, pTemp);
101433    if( rc!=SQLITE_OK ) goto end_of_vacuum;
101434    rc = sqlite3BtreeCommit(pTemp);
101435    if( rc!=SQLITE_OK ) goto end_of_vacuum;
101436#ifndef SQLITE_OMIT_AUTOVACUUM
101437    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
101438#endif
101439  }
101440
101441  assert( rc==SQLITE_OK );
101442  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
101443
101444end_of_vacuum:
101445  /* Restore the original value of db->flags */
101446  db->flags = saved_flags;
101447  db->nChange = saved_nChange;
101448  db->nTotalChange = saved_nTotalChange;
101449  db->xTrace = saved_xTrace;
101450  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
101451
101452  /* Currently there is an SQL level transaction open on the vacuum
101453  ** database. No locks are held on any other files (since the main file
101454  ** was committed at the btree level). So it safe to end the transaction
101455  ** by manually setting the autoCommit flag to true and detaching the
101456  ** vacuum database. The vacuum_db journal file is deleted when the pager
101457  ** is closed by the DETACH.
101458  */
101459  db->autoCommit = 1;
101460
101461  if( pDb ){
101462    sqlite3BtreeClose(pDb->pBt);
101463    pDb->pBt = 0;
101464    pDb->pSchema = 0;
101465  }
101466
101467  /* This both clears the schemas and reduces the size of the db->aDb[]
101468  ** array. */
101469  sqlite3ResetInternalSchema(db, -1);
101470
101471  return rc;
101472}
101473
101474#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
101475
101476/************** End of vacuum.c **********************************************/
101477/************** Begin file vtab.c ********************************************/
101478/*
101479** 2006 June 10
101480**
101481** The author disclaims copyright to this source code.  In place of
101482** a legal notice, here is a blessing:
101483**
101484**    May you do good and not evil.
101485**    May you find forgiveness for yourself and forgive others.
101486**    May you share freely, never taking more than you give.
101487**
101488*************************************************************************
101489** This file contains code used to help implement virtual tables.
101490*/
101491#ifndef SQLITE_OMIT_VIRTUALTABLE
101492
101493/*
101494** Before a virtual table xCreate() or xConnect() method is invoked, the
101495** sqlite3.pVtabCtx member variable is set to point to an instance of
101496** this struct allocated on the stack. It is used by the implementation of
101497** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
101498** are invoked only from within xCreate and xConnect methods.
101499*/
101500struct VtabCtx {
101501  Table *pTab;
101502  VTable *pVTable;
101503};
101504
101505/*
101506** The actual function that does the work of creating a new module.
101507** This function implements the sqlite3_create_module() and
101508** sqlite3_create_module_v2() interfaces.
101509*/
101510static int createModule(
101511  sqlite3 *db,                    /* Database in which module is registered */
101512  const char *zName,              /* Name assigned to this module */
101513  const sqlite3_module *pModule,  /* The definition of the module */
101514  void *pAux,                     /* Context pointer for xCreate/xConnect */
101515  void (*xDestroy)(void *)        /* Module destructor function */
101516){
101517  int rc, nName;
101518  Module *pMod;
101519
101520  sqlite3_mutex_enter(db->mutex);
101521  nName = sqlite3Strlen30(zName);
101522  pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
101523  if( pMod ){
101524    Module *pDel;
101525    char *zCopy = (char *)(&pMod[1]);
101526    memcpy(zCopy, zName, nName+1);
101527    pMod->zName = zCopy;
101528    pMod->pModule = pModule;
101529    pMod->pAux = pAux;
101530    pMod->xDestroy = xDestroy;
101531    pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
101532    if( pDel && pDel->xDestroy ){
101533      sqlite3ResetInternalSchema(db, -1);
101534      pDel->xDestroy(pDel->pAux);
101535    }
101536    sqlite3DbFree(db, pDel);
101537    if( pDel==pMod ){
101538      db->mallocFailed = 1;
101539    }
101540  }else if( xDestroy ){
101541    xDestroy(pAux);
101542  }
101543  rc = sqlite3ApiExit(db, SQLITE_OK);
101544  sqlite3_mutex_leave(db->mutex);
101545  return rc;
101546}
101547
101548
101549/*
101550** External API function used to create a new virtual-table module.
101551*/
101552SQLITE_API int sqlite3_create_module(
101553  sqlite3 *db,                    /* Database in which module is registered */
101554  const char *zName,              /* Name assigned to this module */
101555  const sqlite3_module *pModule,  /* The definition of the module */
101556  void *pAux                      /* Context pointer for xCreate/xConnect */
101557){
101558  return createModule(db, zName, pModule, pAux, 0);
101559}
101560
101561/*
101562** External API function used to create a new virtual-table module.
101563*/
101564SQLITE_API int sqlite3_create_module_v2(
101565  sqlite3 *db,                    /* Database in which module is registered */
101566  const char *zName,              /* Name assigned to this module */
101567  const sqlite3_module *pModule,  /* The definition of the module */
101568  void *pAux,                     /* Context pointer for xCreate/xConnect */
101569  void (*xDestroy)(void *)        /* Module destructor function */
101570){
101571  return createModule(db, zName, pModule, pAux, xDestroy);
101572}
101573
101574/*
101575** Lock the virtual table so that it cannot be disconnected.
101576** Locks nest.  Every lock should have a corresponding unlock.
101577** If an unlock is omitted, resources leaks will occur.
101578**
101579** If a disconnect is attempted while a virtual table is locked,
101580** the disconnect is deferred until all locks have been removed.
101581*/
101582SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
101583  pVTab->nRef++;
101584}
101585
101586
101587/*
101588** pTab is a pointer to a Table structure representing a virtual-table.
101589** Return a pointer to the VTable object used by connection db to access
101590** this virtual-table, if one has been created, or NULL otherwise.
101591*/
101592SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
101593  VTable *pVtab;
101594  assert( IsVirtual(pTab) );
101595  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
101596  return pVtab;
101597}
101598
101599/*
101600** Decrement the ref-count on a virtual table object. When the ref-count
101601** reaches zero, call the xDisconnect() method to delete the object.
101602*/
101603SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
101604  sqlite3 *db = pVTab->db;
101605
101606  assert( db );
101607  assert( pVTab->nRef>0 );
101608  assert( sqlite3SafetyCheckOk(db) );
101609
101610  pVTab->nRef--;
101611  if( pVTab->nRef==0 ){
101612    sqlite3_vtab *p = pVTab->pVtab;
101613    if( p ){
101614      p->pModule->xDisconnect(p);
101615    }
101616    sqlite3DbFree(db, pVTab);
101617  }
101618}
101619
101620/*
101621** Table p is a virtual table. This function moves all elements in the
101622** p->pVTable list to the sqlite3.pDisconnect lists of their associated
101623** database connections to be disconnected at the next opportunity.
101624** Except, if argument db is not NULL, then the entry associated with
101625** connection db is left in the p->pVTable list.
101626*/
101627static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
101628  VTable *pRet = 0;
101629  VTable *pVTable = p->pVTable;
101630  p->pVTable = 0;
101631
101632  /* Assert that the mutex (if any) associated with the BtShared database
101633  ** that contains table p is held by the caller. See header comments
101634  ** above function sqlite3VtabUnlockList() for an explanation of why
101635  ** this makes it safe to access the sqlite3.pDisconnect list of any
101636  ** database connection that may have an entry in the p->pVTable list.
101637  */
101638  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
101639
101640  while( pVTable ){
101641    sqlite3 *db2 = pVTable->db;
101642    VTable *pNext = pVTable->pNext;
101643    assert( db2 );
101644    if( db2==db ){
101645      pRet = pVTable;
101646      p->pVTable = pRet;
101647      pRet->pNext = 0;
101648    }else{
101649      pVTable->pNext = db2->pDisconnect;
101650      db2->pDisconnect = pVTable;
101651    }
101652    pVTable = pNext;
101653  }
101654
101655  assert( !db || pRet );
101656  return pRet;
101657}
101658
101659
101660/*
101661** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
101662**
101663** This function may only be called when the mutexes associated with all
101664** shared b-tree databases opened using connection db are held by the
101665** caller. This is done to protect the sqlite3.pDisconnect list. The
101666** sqlite3.pDisconnect list is accessed only as follows:
101667**
101668**   1) By this function. In this case, all BtShared mutexes and the mutex
101669**      associated with the database handle itself must be held.
101670**
101671**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
101672**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
101673**      associated with the database the virtual table is stored in is held
101674**      or, if the virtual table is stored in a non-sharable database, then
101675**      the database handle mutex is held.
101676**
101677** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
101678** by multiple threads. It is thread-safe.
101679*/
101680SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
101681  VTable *p = db->pDisconnect;
101682  db->pDisconnect = 0;
101683
101684  assert( sqlite3BtreeHoldsAllMutexes(db) );
101685  assert( sqlite3_mutex_held(db->mutex) );
101686
101687  if( p ){
101688    sqlite3ExpirePreparedStatements(db);
101689    do {
101690      VTable *pNext = p->pNext;
101691      sqlite3VtabUnlock(p);
101692      p = pNext;
101693    }while( p );
101694  }
101695}
101696
101697/*
101698** Clear any and all virtual-table information from the Table record.
101699** This routine is called, for example, just before deleting the Table
101700** record.
101701**
101702** Since it is a virtual-table, the Table structure contains a pointer
101703** to the head of a linked list of VTable structures. Each VTable
101704** structure is associated with a single sqlite3* user of the schema.
101705** The reference count of the VTable structure associated with database
101706** connection db is decremented immediately (which may lead to the
101707** structure being xDisconnected and free). Any other VTable structures
101708** in the list are moved to the sqlite3.pDisconnect list of the associated
101709** database connection.
101710*/
101711SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
101712  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
101713  if( p->azModuleArg ){
101714    int i;
101715    for(i=0; i<p->nModuleArg; i++){
101716      sqlite3DbFree(db, p->azModuleArg[i]);
101717    }
101718    sqlite3DbFree(db, p->azModuleArg);
101719  }
101720}
101721
101722/*
101723** Add a new module argument to pTable->azModuleArg[].
101724** The string is not copied - the pointer is stored.  The
101725** string will be freed automatically when the table is
101726** deleted.
101727*/
101728static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
101729  int i = pTable->nModuleArg++;
101730  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
101731  char **azModuleArg;
101732  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
101733  if( azModuleArg==0 ){
101734    int j;
101735    for(j=0; j<i; j++){
101736      sqlite3DbFree(db, pTable->azModuleArg[j]);
101737    }
101738    sqlite3DbFree(db, zArg);
101739    sqlite3DbFree(db, pTable->azModuleArg);
101740    pTable->nModuleArg = 0;
101741  }else{
101742    azModuleArg[i] = zArg;
101743    azModuleArg[i+1] = 0;
101744  }
101745  pTable->azModuleArg = azModuleArg;
101746}
101747
101748/*
101749** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
101750** statement.  The module name has been parsed, but the optional list
101751** of parameters that follow the module name are still pending.
101752*/
101753SQLITE_PRIVATE void sqlite3VtabBeginParse(
101754  Parse *pParse,        /* Parsing context */
101755  Token *pName1,        /* Name of new table, or database name */
101756  Token *pName2,        /* Name of new table or NULL */
101757  Token *pModuleName,   /* Name of the module for the virtual table */
101758  int ifNotExists       /* No error if the table already exists */
101759){
101760  int iDb;              /* The database the table is being created in */
101761  Table *pTable;        /* The new virtual table */
101762  sqlite3 *db;          /* Database connection */
101763
101764  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
101765  pTable = pParse->pNewTable;
101766  if( pTable==0 ) return;
101767  assert( 0==pTable->pIndex );
101768
101769  db = pParse->db;
101770  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
101771  assert( iDb>=0 );
101772
101773  pTable->tabFlags |= TF_Virtual;
101774  pTable->nModuleArg = 0;
101775  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
101776  addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
101777  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
101778  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
101779
101780#ifndef SQLITE_OMIT_AUTHORIZATION
101781  /* Creating a virtual table invokes the authorization callback twice.
101782  ** The first invocation, to obtain permission to INSERT a row into the
101783  ** sqlite_master table, has already been made by sqlite3StartTable().
101784  ** The second call, to obtain permission to create the table, is made now.
101785  */
101786  if( pTable->azModuleArg ){
101787    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
101788            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
101789  }
101790#endif
101791}
101792
101793/*
101794** This routine takes the module argument that has been accumulating
101795** in pParse->zArg[] and appends it to the list of arguments on the
101796** virtual table currently under construction in pParse->pTable.
101797*/
101798static void addArgumentToVtab(Parse *pParse){
101799  if( pParse->sArg.z && pParse->pNewTable ){
101800    const char *z = (const char*)pParse->sArg.z;
101801    int n = pParse->sArg.n;
101802    sqlite3 *db = pParse->db;
101803    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
101804  }
101805}
101806
101807/*
101808** The parser calls this routine after the CREATE VIRTUAL TABLE statement
101809** has been completely parsed.
101810*/
101811SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
101812  Table *pTab = pParse->pNewTable;  /* The table being constructed */
101813  sqlite3 *db = pParse->db;         /* The database connection */
101814
101815  if( pTab==0 ) return;
101816  addArgumentToVtab(pParse);
101817  pParse->sArg.z = 0;
101818  if( pTab->nModuleArg<1 ) return;
101819
101820  /* If the CREATE VIRTUAL TABLE statement is being entered for the
101821  ** first time (in other words if the virtual table is actually being
101822  ** created now instead of just being read out of sqlite_master) then
101823  ** do additional initialization work and store the statement text
101824  ** in the sqlite_master table.
101825  */
101826  if( !db->init.busy ){
101827    char *zStmt;
101828    char *zWhere;
101829    int iDb;
101830    Vdbe *v;
101831
101832    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
101833    if( pEnd ){
101834      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
101835    }
101836    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
101837
101838    /* A slot for the record has already been allocated in the
101839    ** SQLITE_MASTER table.  We just need to update that slot with all
101840    ** the information we've collected.
101841    **
101842    ** The VM register number pParse->regRowid holds the rowid of an
101843    ** entry in the sqlite_master table tht was created for this vtab
101844    ** by sqlite3StartTable().
101845    */
101846    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101847    sqlite3NestedParse(pParse,
101848      "UPDATE %Q.%s "
101849         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
101850       "WHERE rowid=#%d",
101851      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
101852      pTab->zName,
101853      pTab->zName,
101854      zStmt,
101855      pParse->regRowid
101856    );
101857    sqlite3DbFree(db, zStmt);
101858    v = sqlite3GetVdbe(pParse);
101859    sqlite3ChangeCookie(pParse, iDb);
101860
101861    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
101862    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
101863    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
101864    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
101865                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
101866  }
101867
101868  /* If we are rereading the sqlite_master table create the in-memory
101869  ** record of the table. The xConnect() method is not called until
101870  ** the first time the virtual table is used in an SQL statement. This
101871  ** allows a schema that contains virtual tables to be loaded before
101872  ** the required virtual table implementations are registered.  */
101873  else {
101874    Table *pOld;
101875    Schema *pSchema = pTab->pSchema;
101876    const char *zName = pTab->zName;
101877    int nName = sqlite3Strlen30(zName);
101878    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
101879    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
101880    if( pOld ){
101881      db->mallocFailed = 1;
101882      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
101883      return;
101884    }
101885    pParse->pNewTable = 0;
101886  }
101887}
101888
101889/*
101890** The parser calls this routine when it sees the first token
101891** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
101892*/
101893SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
101894  addArgumentToVtab(pParse);
101895  pParse->sArg.z = 0;
101896  pParse->sArg.n = 0;
101897}
101898
101899/*
101900** The parser calls this routine for each token after the first token
101901** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
101902*/
101903SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
101904  Token *pArg = &pParse->sArg;
101905  if( pArg->z==0 ){
101906    pArg->z = p->z;
101907    pArg->n = p->n;
101908  }else{
101909    assert(pArg->z < p->z);
101910    pArg->n = (int)(&p->z[p->n] - pArg->z);
101911  }
101912}
101913
101914/*
101915** Invoke a virtual table constructor (either xCreate or xConnect). The
101916** pointer to the function to invoke is passed as the fourth parameter
101917** to this procedure.
101918*/
101919static int vtabCallConstructor(
101920  sqlite3 *db,
101921  Table *pTab,
101922  Module *pMod,
101923  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
101924  char **pzErr
101925){
101926  VtabCtx sCtx;
101927  VTable *pVTable;
101928  int rc;
101929  const char *const*azArg = (const char *const*)pTab->azModuleArg;
101930  int nArg = pTab->nModuleArg;
101931  char *zErr = 0;
101932  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
101933
101934  if( !zModuleName ){
101935    return SQLITE_NOMEM;
101936  }
101937
101938  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
101939  if( !pVTable ){
101940    sqlite3DbFree(db, zModuleName);
101941    return SQLITE_NOMEM;
101942  }
101943  pVTable->db = db;
101944  pVTable->pMod = pMod;
101945
101946  /* Invoke the virtual table constructor */
101947  assert( &db->pVtabCtx );
101948  assert( xConstruct );
101949  sCtx.pTab = pTab;
101950  sCtx.pVTable = pVTable;
101951  db->pVtabCtx = &sCtx;
101952  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
101953  db->pVtabCtx = 0;
101954  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
101955
101956  if( SQLITE_OK!=rc ){
101957    if( zErr==0 ){
101958      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
101959    }else {
101960      *pzErr = sqlite3MPrintf(db, "%s", zErr);
101961      sqlite3_free(zErr);
101962    }
101963    sqlite3DbFree(db, pVTable);
101964  }else if( ALWAYS(pVTable->pVtab) ){
101965    /* Justification of ALWAYS():  A correct vtab constructor must allocate
101966    ** the sqlite3_vtab object if successful.  */
101967    pVTable->pVtab->pModule = pMod->pModule;
101968    pVTable->nRef = 1;
101969    if( sCtx.pTab ){
101970      const char *zFormat = "vtable constructor did not declare schema: %s";
101971      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
101972      sqlite3VtabUnlock(pVTable);
101973      rc = SQLITE_ERROR;
101974    }else{
101975      int iCol;
101976      /* If everything went according to plan, link the new VTable structure
101977      ** into the linked list headed by pTab->pVTable. Then loop through the
101978      ** columns of the table to see if any of them contain the token "hidden".
101979      ** If so, set the Column.isHidden flag and remove the token from
101980      ** the type string.  */
101981      pVTable->pNext = pTab->pVTable;
101982      pTab->pVTable = pVTable;
101983
101984      for(iCol=0; iCol<pTab->nCol; iCol++){
101985        char *zType = pTab->aCol[iCol].zType;
101986        int nType;
101987        int i = 0;
101988        if( !zType ) continue;
101989        nType = sqlite3Strlen30(zType);
101990        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
101991          for(i=0; i<nType; i++){
101992            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
101993             && (zType[i+7]=='\0' || zType[i+7]==' ')
101994            ){
101995              i++;
101996              break;
101997            }
101998          }
101999        }
102000        if( i<nType ){
102001          int j;
102002          int nDel = 6 + (zType[i+6] ? 1 : 0);
102003          for(j=i; (j+nDel)<=nType; j++){
102004            zType[j] = zType[j+nDel];
102005          }
102006          if( zType[i]=='\0' && i>0 ){
102007            assert(zType[i-1]==' ');
102008            zType[i-1] = '\0';
102009          }
102010          pTab->aCol[iCol].isHidden = 1;
102011        }
102012      }
102013    }
102014  }
102015
102016  sqlite3DbFree(db, zModuleName);
102017  return rc;
102018}
102019
102020/*
102021** This function is invoked by the parser to call the xConnect() method
102022** of the virtual table pTab. If an error occurs, an error code is returned
102023** and an error left in pParse.
102024**
102025** This call is a no-op if table pTab is not a virtual table.
102026*/
102027SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
102028  sqlite3 *db = pParse->db;
102029  const char *zMod;
102030  Module *pMod;
102031  int rc;
102032
102033  assert( pTab );
102034  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
102035    return SQLITE_OK;
102036  }
102037
102038  /* Locate the required virtual table module */
102039  zMod = pTab->azModuleArg[0];
102040  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
102041
102042  if( !pMod ){
102043    const char *zModule = pTab->azModuleArg[0];
102044    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
102045    rc = SQLITE_ERROR;
102046  }else{
102047    char *zErr = 0;
102048    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
102049    if( rc!=SQLITE_OK ){
102050      sqlite3ErrorMsg(pParse, "%s", zErr);
102051    }
102052    sqlite3DbFree(db, zErr);
102053  }
102054
102055  return rc;
102056}
102057/*
102058** Grow the db->aVTrans[] array so that there is room for at least one
102059** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
102060*/
102061static int growVTrans(sqlite3 *db){
102062  const int ARRAY_INCR = 5;
102063
102064  /* Grow the sqlite3.aVTrans array if required */
102065  if( (db->nVTrans%ARRAY_INCR)==0 ){
102066    VTable **aVTrans;
102067    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
102068    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
102069    if( !aVTrans ){
102070      return SQLITE_NOMEM;
102071    }
102072    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
102073    db->aVTrans = aVTrans;
102074  }
102075
102076  return SQLITE_OK;
102077}
102078
102079/*
102080** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
102081** have already been reserved using growVTrans().
102082*/
102083static void addToVTrans(sqlite3 *db, VTable *pVTab){
102084  /* Add pVtab to the end of sqlite3.aVTrans */
102085  db->aVTrans[db->nVTrans++] = pVTab;
102086  sqlite3VtabLock(pVTab);
102087}
102088
102089/*
102090** This function is invoked by the vdbe to call the xCreate method
102091** of the virtual table named zTab in database iDb.
102092**
102093** If an error occurs, *pzErr is set to point an an English language
102094** description of the error and an SQLITE_XXX error code is returned.
102095** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
102096*/
102097SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
102098  int rc = SQLITE_OK;
102099  Table *pTab;
102100  Module *pMod;
102101  const char *zMod;
102102
102103  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
102104  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
102105
102106  /* Locate the required virtual table module */
102107  zMod = pTab->azModuleArg[0];
102108  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
102109
102110  /* If the module has been registered and includes a Create method,
102111  ** invoke it now. If the module has not been registered, return an
102112  ** error. Otherwise, do nothing.
102113  */
102114  if( !pMod ){
102115    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
102116    rc = SQLITE_ERROR;
102117  }else{
102118    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
102119  }
102120
102121  /* Justification of ALWAYS():  The xConstructor method is required to
102122  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
102123  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
102124    rc = growVTrans(db);
102125    if( rc==SQLITE_OK ){
102126      addToVTrans(db, sqlite3GetVTable(db, pTab));
102127    }
102128  }
102129
102130  return rc;
102131}
102132
102133/*
102134** This function is used to set the schema of a virtual table.  It is only
102135** valid to call this function from within the xCreate() or xConnect() of a
102136** virtual table module.
102137*/
102138SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
102139  Parse *pParse;
102140
102141  int rc = SQLITE_OK;
102142  Table *pTab;
102143  char *zErr = 0;
102144
102145  sqlite3_mutex_enter(db->mutex);
102146  if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
102147    sqlite3Error(db, SQLITE_MISUSE, 0);
102148    sqlite3_mutex_leave(db->mutex);
102149    return SQLITE_MISUSE_BKPT;
102150  }
102151  assert( (pTab->tabFlags & TF_Virtual)!=0 );
102152
102153  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
102154  if( pParse==0 ){
102155    rc = SQLITE_NOMEM;
102156  }else{
102157    pParse->declareVtab = 1;
102158    pParse->db = db;
102159    pParse->nQueryLoop = 1;
102160
102161    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
102162     && pParse->pNewTable
102163     && !db->mallocFailed
102164     && !pParse->pNewTable->pSelect
102165     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
102166    ){
102167      if( !pTab->aCol ){
102168        pTab->aCol = pParse->pNewTable->aCol;
102169        pTab->nCol = pParse->pNewTable->nCol;
102170        pParse->pNewTable->nCol = 0;
102171        pParse->pNewTable->aCol = 0;
102172      }
102173      db->pVtabCtx->pTab = 0;
102174    }else{
102175      sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
102176      sqlite3DbFree(db, zErr);
102177      rc = SQLITE_ERROR;
102178    }
102179    pParse->declareVtab = 0;
102180
102181    if( pParse->pVdbe ){
102182      sqlite3VdbeFinalize(pParse->pVdbe);
102183    }
102184    sqlite3DeleteTable(db, pParse->pNewTable);
102185    sqlite3StackFree(db, pParse);
102186  }
102187
102188  assert( (rc&0xff)==rc );
102189  rc = sqlite3ApiExit(db, rc);
102190  sqlite3_mutex_leave(db->mutex);
102191  return rc;
102192}
102193
102194/*
102195** This function is invoked by the vdbe to call the xDestroy method
102196** of the virtual table named zTab in database iDb. This occurs
102197** when a DROP TABLE is mentioned.
102198**
102199** This call is a no-op if zTab is not a virtual table.
102200*/
102201SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
102202  int rc = SQLITE_OK;
102203  Table *pTab;
102204
102205  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
102206  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
102207    VTable *p = vtabDisconnectAll(db, pTab);
102208
102209    assert( rc==SQLITE_OK );
102210    rc = p->pMod->pModule->xDestroy(p->pVtab);
102211
102212    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
102213    if( rc==SQLITE_OK ){
102214      assert( pTab->pVTable==p && p->pNext==0 );
102215      p->pVtab = 0;
102216      pTab->pVTable = 0;
102217      sqlite3VtabUnlock(p);
102218    }
102219  }
102220
102221  return rc;
102222}
102223
102224/*
102225** This function invokes either the xRollback or xCommit method
102226** of each of the virtual tables in the sqlite3.aVTrans array. The method
102227** called is identified by the second argument, "offset", which is
102228** the offset of the method to call in the sqlite3_module structure.
102229**
102230** The array is cleared after invoking the callbacks.
102231*/
102232static void callFinaliser(sqlite3 *db, int offset){
102233  int i;
102234  if( db->aVTrans ){
102235    for(i=0; i<db->nVTrans; i++){
102236      VTable *pVTab = db->aVTrans[i];
102237      sqlite3_vtab *p = pVTab->pVtab;
102238      if( p ){
102239        int (*x)(sqlite3_vtab *);
102240        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
102241        if( x ) x(p);
102242      }
102243      pVTab->iSavepoint = 0;
102244      sqlite3VtabUnlock(pVTab);
102245    }
102246    sqlite3DbFree(db, db->aVTrans);
102247    db->nVTrans = 0;
102248    db->aVTrans = 0;
102249  }
102250}
102251
102252/*
102253** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
102254** array. Return the error code for the first error that occurs, or
102255** SQLITE_OK if all xSync operations are successful.
102256**
102257** Set *pzErrmsg to point to a buffer that should be released using
102258** sqlite3DbFree() containing an error message, if one is available.
102259*/
102260SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
102261  int i;
102262  int rc = SQLITE_OK;
102263  VTable **aVTrans = db->aVTrans;
102264
102265  db->aVTrans = 0;
102266  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
102267    int (*x)(sqlite3_vtab *);
102268    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
102269    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
102270      rc = x(pVtab);
102271      sqlite3DbFree(db, *pzErrmsg);
102272      *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
102273      sqlite3_free(pVtab->zErrMsg);
102274    }
102275  }
102276  db->aVTrans = aVTrans;
102277  return rc;
102278}
102279
102280/*
102281** Invoke the xRollback method of all virtual tables in the
102282** sqlite3.aVTrans array. Then clear the array itself.
102283*/
102284SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
102285  callFinaliser(db, offsetof(sqlite3_module,xRollback));
102286  return SQLITE_OK;
102287}
102288
102289/*
102290** Invoke the xCommit method of all virtual tables in the
102291** sqlite3.aVTrans array. Then clear the array itself.
102292*/
102293SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
102294  callFinaliser(db, offsetof(sqlite3_module,xCommit));
102295  return SQLITE_OK;
102296}
102297
102298/*
102299** If the virtual table pVtab supports the transaction interface
102300** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
102301** not currently open, invoke the xBegin method now.
102302**
102303** If the xBegin call is successful, place the sqlite3_vtab pointer
102304** in the sqlite3.aVTrans array.
102305*/
102306SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
102307  int rc = SQLITE_OK;
102308  const sqlite3_module *pModule;
102309
102310  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
102311  ** than zero, then this function is being called from within a
102312  ** virtual module xSync() callback. It is illegal to write to
102313  ** virtual module tables in this case, so return SQLITE_LOCKED.
102314  */
102315  if( sqlite3VtabInSync(db) ){
102316    return SQLITE_LOCKED;
102317  }
102318  if( !pVTab ){
102319    return SQLITE_OK;
102320  }
102321  pModule = pVTab->pVtab->pModule;
102322
102323  if( pModule->xBegin ){
102324    int i;
102325
102326    /* If pVtab is already in the aVTrans array, return early */
102327    for(i=0; i<db->nVTrans; i++){
102328      if( db->aVTrans[i]==pVTab ){
102329        return SQLITE_OK;
102330      }
102331    }
102332
102333    /* Invoke the xBegin method. If successful, add the vtab to the
102334    ** sqlite3.aVTrans[] array. */
102335    rc = growVTrans(db);
102336    if( rc==SQLITE_OK ){
102337      rc = pModule->xBegin(pVTab->pVtab);
102338      if( rc==SQLITE_OK ){
102339        addToVTrans(db, pVTab);
102340      }
102341    }
102342  }
102343  return rc;
102344}
102345
102346/*
102347** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
102348** virtual tables that currently have an open transaction. Pass iSavepoint
102349** as the second argument to the virtual table method invoked.
102350**
102351** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
102352** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
102353** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
102354** an open transaction is invoked.
102355**
102356** If any virtual table method returns an error code other than SQLITE_OK,
102357** processing is abandoned and the error returned to the caller of this
102358** function immediately. If all calls to virtual table methods are successful,
102359** SQLITE_OK is returned.
102360*/
102361SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
102362  int rc = SQLITE_OK;
102363
102364  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
102365  assert( iSavepoint>=0 );
102366  if( db->aVTrans ){
102367    int i;
102368    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
102369      VTable *pVTab = db->aVTrans[i];
102370      const sqlite3_module *pMod = pVTab->pMod->pModule;
102371      if( pVTab->pVtab && pMod->iVersion>=2 ){
102372        int (*xMethod)(sqlite3_vtab *, int);
102373        switch( op ){
102374          case SAVEPOINT_BEGIN:
102375            xMethod = pMod->xSavepoint;
102376            pVTab->iSavepoint = iSavepoint+1;
102377            break;
102378          case SAVEPOINT_ROLLBACK:
102379            xMethod = pMod->xRollbackTo;
102380            break;
102381          default:
102382            xMethod = pMod->xRelease;
102383            break;
102384        }
102385        if( xMethod && pVTab->iSavepoint>iSavepoint ){
102386          rc = xMethod(pVTab->pVtab, iSavepoint);
102387        }
102388      }
102389    }
102390  }
102391  return rc;
102392}
102393
102394/*
102395** The first parameter (pDef) is a function implementation.  The
102396** second parameter (pExpr) is the first argument to this function.
102397** If pExpr is a column in a virtual table, then let the virtual
102398** table implementation have an opportunity to overload the function.
102399**
102400** This routine is used to allow virtual table implementations to
102401** overload MATCH, LIKE, GLOB, and REGEXP operators.
102402**
102403** Return either the pDef argument (indicating no change) or a
102404** new FuncDef structure that is marked as ephemeral using the
102405** SQLITE_FUNC_EPHEM flag.
102406*/
102407SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
102408  sqlite3 *db,    /* Database connection for reporting malloc problems */
102409  FuncDef *pDef,  /* Function to possibly overload */
102410  int nArg,       /* Number of arguments to the function */
102411  Expr *pExpr     /* First argument to the function */
102412){
102413  Table *pTab;
102414  sqlite3_vtab *pVtab;
102415  sqlite3_module *pMod;
102416  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
102417  void *pArg = 0;
102418  FuncDef *pNew;
102419  int rc = 0;
102420  char *zLowerName;
102421  unsigned char *z;
102422
102423
102424  /* Check to see the left operand is a column in a virtual table */
102425  if( NEVER(pExpr==0) ) return pDef;
102426  if( pExpr->op!=TK_COLUMN ) return pDef;
102427  pTab = pExpr->pTab;
102428  if( NEVER(pTab==0) ) return pDef;
102429  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
102430  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
102431  assert( pVtab!=0 );
102432  assert( pVtab->pModule!=0 );
102433  pMod = (sqlite3_module *)pVtab->pModule;
102434  if( pMod->xFindFunction==0 ) return pDef;
102435
102436  /* Call the xFindFunction method on the virtual table implementation
102437  ** to see if the implementation wants to overload this function
102438  */
102439  zLowerName = sqlite3DbStrDup(db, pDef->zName);
102440  if( zLowerName ){
102441    for(z=(unsigned char*)zLowerName; *z; z++){
102442      *z = sqlite3UpperToLower[*z];
102443    }
102444    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
102445    sqlite3DbFree(db, zLowerName);
102446  }
102447  if( rc==0 ){
102448    return pDef;
102449  }
102450
102451  /* Create a new ephemeral function definition for the overloaded
102452  ** function */
102453  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
102454                             + sqlite3Strlen30(pDef->zName) + 1);
102455  if( pNew==0 ){
102456    return pDef;
102457  }
102458  *pNew = *pDef;
102459  pNew->zName = (char *)&pNew[1];
102460  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
102461  pNew->xFunc = xFunc;
102462  pNew->pUserData = pArg;
102463  pNew->flags |= SQLITE_FUNC_EPHEM;
102464  return pNew;
102465}
102466
102467/*
102468** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
102469** array so that an OP_VBegin will get generated for it.  Add pTab to the
102470** array if it is missing.  If pTab is already in the array, this routine
102471** is a no-op.
102472*/
102473SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
102474  Parse *pToplevel = sqlite3ParseToplevel(pParse);
102475  int i, n;
102476  Table **apVtabLock;
102477
102478  assert( IsVirtual(pTab) );
102479  for(i=0; i<pToplevel->nVtabLock; i++){
102480    if( pTab==pToplevel->apVtabLock[i] ) return;
102481  }
102482  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
102483  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
102484  if( apVtabLock ){
102485    pToplevel->apVtabLock = apVtabLock;
102486    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
102487  }else{
102488    pToplevel->db->mallocFailed = 1;
102489  }
102490}
102491
102492/*
102493** Return the ON CONFLICT resolution mode in effect for the virtual
102494** table update operation currently in progress.
102495**
102496** The results of this routine are undefined unless it is called from
102497** within an xUpdate method.
102498*/
102499SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
102500  static const unsigned char aMap[] = {
102501    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
102502  };
102503  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
102504  assert( OE_Ignore==4 && OE_Replace==5 );
102505  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
102506  return (int)aMap[db->vtabOnConflict-1];
102507}
102508
102509/*
102510** Call from within the xCreate() or xConnect() methods to provide
102511** the SQLite core with additional information about the behavior
102512** of the virtual table being implemented.
102513*/
102514SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
102515  va_list ap;
102516  int rc = SQLITE_OK;
102517
102518  sqlite3_mutex_enter(db->mutex);
102519
102520  va_start(ap, op);
102521  switch( op ){
102522    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
102523      VtabCtx *p = db->pVtabCtx;
102524      if( !p ){
102525        rc = SQLITE_MISUSE_BKPT;
102526      }else{
102527        assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
102528        p->pVTable->bConstraint = (u8)va_arg(ap, int);
102529      }
102530      break;
102531    }
102532    default:
102533      rc = SQLITE_MISUSE_BKPT;
102534      break;
102535  }
102536  va_end(ap);
102537
102538  if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
102539  sqlite3_mutex_leave(db->mutex);
102540  return rc;
102541}
102542
102543#endif /* SQLITE_OMIT_VIRTUALTABLE */
102544
102545/************** End of vtab.c ************************************************/
102546/************** Begin file where.c *******************************************/
102547/*
102548** 2001 September 15
102549**
102550** The author disclaims copyright to this source code.  In place of
102551** a legal notice, here is a blessing:
102552**
102553**    May you do good and not evil.
102554**    May you find forgiveness for yourself and forgive others.
102555**    May you share freely, never taking more than you give.
102556**
102557*************************************************************************
102558** This module contains C code that generates VDBE code used to process
102559** the WHERE clause of SQL statements.  This module is responsible for
102560** generating the code that loops through a table looking for applicable
102561** rows.  Indices are selected and used to speed the search when doing
102562** so is applicable.  Because this module is responsible for selecting
102563** indices, you might also think of this module as the "query optimizer".
102564*/
102565
102566
102567/*
102568** Trace output macros
102569*/
102570#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
102571SQLITE_PRIVATE int sqlite3WhereTrace = 0;
102572#endif
102573#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
102574# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
102575#else
102576# define WHERETRACE(X)
102577#endif
102578
102579/* Forward reference
102580*/
102581typedef struct WhereClause WhereClause;
102582typedef struct WhereMaskSet WhereMaskSet;
102583typedef struct WhereOrInfo WhereOrInfo;
102584typedef struct WhereAndInfo WhereAndInfo;
102585typedef struct WhereCost WhereCost;
102586
102587/*
102588** The query generator uses an array of instances of this structure to
102589** help it analyze the subexpressions of the WHERE clause.  Each WHERE
102590** clause subexpression is separated from the others by AND operators,
102591** usually, or sometimes subexpressions separated by OR.
102592**
102593** All WhereTerms are collected into a single WhereClause structure.
102594** The following identity holds:
102595**
102596**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
102597**
102598** When a term is of the form:
102599**
102600**              X <op> <expr>
102601**
102602** where X is a column name and <op> is one of certain operators,
102603** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
102604** cursor number and column number for X.  WhereTerm.eOperator records
102605** the <op> using a bitmask encoding defined by WO_xxx below.  The
102606** use of a bitmask encoding for the operator allows us to search
102607** quickly for terms that match any of several different operators.
102608**
102609** A WhereTerm might also be two or more subterms connected by OR:
102610**
102611**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
102612**
102613** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
102614** and the WhereTerm.u.pOrInfo field points to auxiliary information that
102615** is collected about the
102616**
102617** If a term in the WHERE clause does not match either of the two previous
102618** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
102619** to the original subexpression content and wtFlags is set up appropriately
102620** but no other fields in the WhereTerm object are meaningful.
102621**
102622** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
102623** but they do so indirectly.  A single WhereMaskSet structure translates
102624** cursor number into bits and the translated bit is stored in the prereq
102625** fields.  The translation is used in order to maximize the number of
102626** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
102627** spread out over the non-negative integers.  For example, the cursor
102628** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
102629** translates these sparse cursor numbers into consecutive integers
102630** beginning with 0 in order to make the best possible use of the available
102631** bits in the Bitmask.  So, in the example above, the cursor numbers
102632** would be mapped into integers 0 through 7.
102633**
102634** The number of terms in a join is limited by the number of bits
102635** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
102636** is only able to process joins with 64 or fewer tables.
102637*/
102638typedef struct WhereTerm WhereTerm;
102639struct WhereTerm {
102640  Expr *pExpr;            /* Pointer to the subexpression that is this term */
102641  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
102642  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
102643  union {
102644    int leftColumn;         /* Column number of X in "X <op> <expr>" */
102645    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
102646    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
102647  } u;
102648  u16 eOperator;          /* A WO_xx value describing <op> */
102649  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
102650  u8 nChild;              /* Number of children that must disable us */
102651  WhereClause *pWC;       /* The clause this term is part of */
102652  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
102653  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
102654};
102655
102656/*
102657** Allowed values of WhereTerm.wtFlags
102658*/
102659#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
102660#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
102661#define TERM_CODED      0x04   /* This term is already coded */
102662#define TERM_COPIED     0x08   /* Has a child */
102663#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
102664#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
102665#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
102666#ifdef SQLITE_ENABLE_STAT3
102667#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
102668#else
102669#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
102670#endif
102671
102672/*
102673** An instance of the following structure holds all information about a
102674** WHERE clause.  Mostly this is a container for one or more WhereTerms.
102675**
102676** Explanation of pOuter:  For a WHERE clause of the form
102677**
102678**           a AND ((b AND c) OR (d AND e)) AND f
102679**
102680** There are separate WhereClause objects for the whole clause and for
102681** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
102682** subclauses points to the WhereClause object for the whole clause.
102683*/
102684struct WhereClause {
102685  Parse *pParse;           /* The parser context */
102686  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
102687  Bitmask vmask;           /* Bitmask identifying virtual table cursors */
102688  WhereClause *pOuter;     /* Outer conjunction */
102689  u8 op;                   /* Split operator.  TK_AND or TK_OR */
102690  u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
102691  int nTerm;               /* Number of terms */
102692  int nSlot;               /* Number of entries in a[] */
102693  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
102694#if defined(SQLITE_SMALL_STACK)
102695  WhereTerm aStatic[1];    /* Initial static space for a[] */
102696#else
102697  WhereTerm aStatic[8];    /* Initial static space for a[] */
102698#endif
102699};
102700
102701/*
102702** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
102703** a dynamically allocated instance of the following structure.
102704*/
102705struct WhereOrInfo {
102706  WhereClause wc;          /* Decomposition into subterms */
102707  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
102708};
102709
102710/*
102711** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
102712** a dynamically allocated instance of the following structure.
102713*/
102714struct WhereAndInfo {
102715  WhereClause wc;          /* The subexpression broken out */
102716};
102717
102718/*
102719** An instance of the following structure keeps track of a mapping
102720** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
102721**
102722** The VDBE cursor numbers are small integers contained in
102723** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
102724** clause, the cursor numbers might not begin with 0 and they might
102725** contain gaps in the numbering sequence.  But we want to make maximum
102726** use of the bits in our bitmasks.  This structure provides a mapping
102727** from the sparse cursor numbers into consecutive integers beginning
102728** with 0.
102729**
102730** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
102731** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
102732**
102733** For example, if the WHERE clause expression used these VDBE
102734** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
102735** would map those cursor numbers into bits 0 through 5.
102736**
102737** Note that the mapping is not necessarily ordered.  In the example
102738** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
102739** 57->5, 73->4.  Or one of 719 other combinations might be used. It
102740** does not really matter.  What is important is that sparse cursor
102741** numbers all get mapped into bit numbers that begin with 0 and contain
102742** no gaps.
102743*/
102744struct WhereMaskSet {
102745  int n;                        /* Number of assigned cursor values */
102746  int ix[BMS];                  /* Cursor assigned to each bit */
102747};
102748
102749/*
102750** A WhereCost object records a lookup strategy and the estimated
102751** cost of pursuing that strategy.
102752*/
102753struct WhereCost {
102754  WherePlan plan;    /* The lookup strategy */
102755  double rCost;      /* Overall cost of pursuing this search strategy */
102756  Bitmask used;      /* Bitmask of cursors used by this plan */
102757};
102758
102759/*
102760** Bitmasks for the operators that indices are able to exploit.  An
102761** OR-ed combination of these values can be used when searching for
102762** terms in the where clause.
102763*/
102764#define WO_IN     0x001
102765#define WO_EQ     0x002
102766#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
102767#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
102768#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
102769#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
102770#define WO_MATCH  0x040
102771#define WO_ISNULL 0x080
102772#define WO_OR     0x100       /* Two or more OR-connected terms */
102773#define WO_AND    0x200       /* Two or more AND-connected terms */
102774#define WO_NOOP   0x800       /* This term does not restrict search space */
102775
102776#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
102777#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
102778
102779/*
102780** Value for wsFlags returned by bestIndex() and stored in
102781** WhereLevel.wsFlags.  These flags determine which search
102782** strategies are appropriate.
102783**
102784** The least significant 12 bits is reserved as a mask for WO_ values above.
102785** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
102786** But if the table is the right table of a left join, WhereLevel.wsFlags
102787** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
102788** the "op" parameter to findTerm when we are resolving equality constraints.
102789** ISNULL constraints will then not be used on the right table of a left
102790** join.  Tickets #2177 and #2189.
102791*/
102792#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
102793#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
102794#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
102795#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
102796#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
102797#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
102798#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
102799#define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
102800#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
102801#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
102802#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
102803#define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
102804#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
102805#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
102806#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
102807#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
102808#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
102809#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
102810#define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
102811#define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
102812
102813/*
102814** Initialize a preallocated WhereClause structure.
102815*/
102816static void whereClauseInit(
102817  WhereClause *pWC,        /* The WhereClause to be initialized */
102818  Parse *pParse,           /* The parsing context */
102819  WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
102820  u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
102821){
102822  pWC->pParse = pParse;
102823  pWC->pMaskSet = pMaskSet;
102824  pWC->pOuter = 0;
102825  pWC->nTerm = 0;
102826  pWC->nSlot = ArraySize(pWC->aStatic);
102827  pWC->a = pWC->aStatic;
102828  pWC->vmask = 0;
102829  pWC->wctrlFlags = wctrlFlags;
102830}
102831
102832/* Forward reference */
102833static void whereClauseClear(WhereClause*);
102834
102835/*
102836** Deallocate all memory associated with a WhereOrInfo object.
102837*/
102838static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
102839  whereClauseClear(&p->wc);
102840  sqlite3DbFree(db, p);
102841}
102842
102843/*
102844** Deallocate all memory associated with a WhereAndInfo object.
102845*/
102846static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
102847  whereClauseClear(&p->wc);
102848  sqlite3DbFree(db, p);
102849}
102850
102851/*
102852** Deallocate a WhereClause structure.  The WhereClause structure
102853** itself is not freed.  This routine is the inverse of whereClauseInit().
102854*/
102855static void whereClauseClear(WhereClause *pWC){
102856  int i;
102857  WhereTerm *a;
102858  sqlite3 *db = pWC->pParse->db;
102859  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
102860    if( a->wtFlags & TERM_DYNAMIC ){
102861      sqlite3ExprDelete(db, a->pExpr);
102862    }
102863    if( a->wtFlags & TERM_ORINFO ){
102864      whereOrInfoDelete(db, a->u.pOrInfo);
102865    }else if( a->wtFlags & TERM_ANDINFO ){
102866      whereAndInfoDelete(db, a->u.pAndInfo);
102867    }
102868  }
102869  if( pWC->a!=pWC->aStatic ){
102870    sqlite3DbFree(db, pWC->a);
102871  }
102872}
102873
102874/*
102875** Add a single new WhereTerm entry to the WhereClause object pWC.
102876** The new WhereTerm object is constructed from Expr p and with wtFlags.
102877** The index in pWC->a[] of the new WhereTerm is returned on success.
102878** 0 is returned if the new WhereTerm could not be added due to a memory
102879** allocation error.  The memory allocation failure will be recorded in
102880** the db->mallocFailed flag so that higher-level functions can detect it.
102881**
102882** This routine will increase the size of the pWC->a[] array as necessary.
102883**
102884** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
102885** for freeing the expression p is assumed by the WhereClause object pWC.
102886** This is true even if this routine fails to allocate a new WhereTerm.
102887**
102888** WARNING:  This routine might reallocate the space used to store
102889** WhereTerms.  All pointers to WhereTerms should be invalidated after
102890** calling this routine.  Such pointers may be reinitialized by referencing
102891** the pWC->a[] array.
102892*/
102893static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
102894  WhereTerm *pTerm;
102895  int idx;
102896  testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
102897  if( pWC->nTerm>=pWC->nSlot ){
102898    WhereTerm *pOld = pWC->a;
102899    sqlite3 *db = pWC->pParse->db;
102900    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
102901    if( pWC->a==0 ){
102902      if( wtFlags & TERM_DYNAMIC ){
102903        sqlite3ExprDelete(db, p);
102904      }
102905      pWC->a = pOld;
102906      return 0;
102907    }
102908    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
102909    if( pOld!=pWC->aStatic ){
102910      sqlite3DbFree(db, pOld);
102911    }
102912    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
102913  }
102914  pTerm = &pWC->a[idx = pWC->nTerm++];
102915  pTerm->pExpr = p;
102916  pTerm->wtFlags = wtFlags;
102917  pTerm->pWC = pWC;
102918  pTerm->iParent = -1;
102919  return idx;
102920}
102921
102922/*
102923** This routine identifies subexpressions in the WHERE clause where
102924** each subexpression is separated by the AND operator or some other
102925** operator specified in the op parameter.  The WhereClause structure
102926** is filled with pointers to subexpressions.  For example:
102927**
102928**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
102929**           \________/     \_______________/     \________________/
102930**            slot[0]            slot[1]               slot[2]
102931**
102932** The original WHERE clause in pExpr is unaltered.  All this routine
102933** does is make slot[] entries point to substructure within pExpr.
102934**
102935** In the previous sentence and in the diagram, "slot[]" refers to
102936** the WhereClause.a[] array.  The slot[] array grows as needed to contain
102937** all terms of the WHERE clause.
102938*/
102939static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
102940  pWC->op = (u8)op;
102941  if( pExpr==0 ) return;
102942  if( pExpr->op!=op ){
102943    whereClauseInsert(pWC, pExpr, 0);
102944  }else{
102945    whereSplit(pWC, pExpr->pLeft, op);
102946    whereSplit(pWC, pExpr->pRight, op);
102947  }
102948}
102949
102950/*
102951** Initialize an expression mask set (a WhereMaskSet object)
102952*/
102953#define initMaskSet(P)  memset(P, 0, sizeof(*P))
102954
102955/*
102956** Return the bitmask for the given cursor number.  Return 0 if
102957** iCursor is not in the set.
102958*/
102959static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
102960  int i;
102961  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
102962  for(i=0; i<pMaskSet->n; i++){
102963    if( pMaskSet->ix[i]==iCursor ){
102964      return ((Bitmask)1)<<i;
102965    }
102966  }
102967  return 0;
102968}
102969
102970/*
102971** Create a new mask for cursor iCursor.
102972**
102973** There is one cursor per table in the FROM clause.  The number of
102974** tables in the FROM clause is limited by a test early in the
102975** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
102976** array will never overflow.
102977*/
102978static void createMask(WhereMaskSet *pMaskSet, int iCursor){
102979  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
102980  pMaskSet->ix[pMaskSet->n++] = iCursor;
102981}
102982
102983/*
102984** This routine walks (recursively) an expression tree and generates
102985** a bitmask indicating which tables are used in that expression
102986** tree.
102987**
102988** In order for this routine to work, the calling function must have
102989** previously invoked sqlite3ResolveExprNames() on the expression.  See
102990** the header comment on that routine for additional information.
102991** The sqlite3ResolveExprNames() routines looks for column names and
102992** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
102993** the VDBE cursor number of the table.  This routine just has to
102994** translate the cursor numbers into bitmask values and OR all
102995** the bitmasks together.
102996*/
102997static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
102998static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
102999static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
103000  Bitmask mask = 0;
103001  if( p==0 ) return 0;
103002  if( p->op==TK_COLUMN ){
103003    mask = getMask(pMaskSet, p->iTable);
103004    return mask;
103005  }
103006  mask = exprTableUsage(pMaskSet, p->pRight);
103007  mask |= exprTableUsage(pMaskSet, p->pLeft);
103008  if( ExprHasProperty(p, EP_xIsSelect) ){
103009    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
103010  }else{
103011    mask |= exprListTableUsage(pMaskSet, p->x.pList);
103012  }
103013  return mask;
103014}
103015static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
103016  int i;
103017  Bitmask mask = 0;
103018  if( pList ){
103019    for(i=0; i<pList->nExpr; i++){
103020      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
103021    }
103022  }
103023  return mask;
103024}
103025static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
103026  Bitmask mask = 0;
103027  while( pS ){
103028    SrcList *pSrc = pS->pSrc;
103029    mask |= exprListTableUsage(pMaskSet, pS->pEList);
103030    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
103031    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
103032    mask |= exprTableUsage(pMaskSet, pS->pWhere);
103033    mask |= exprTableUsage(pMaskSet, pS->pHaving);
103034    if( ALWAYS(pSrc!=0) ){
103035      int i;
103036      for(i=0; i<pSrc->nSrc; i++){
103037        mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
103038        mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
103039      }
103040    }
103041    pS = pS->pPrior;
103042  }
103043  return mask;
103044}
103045
103046/*
103047** Return TRUE if the given operator is one of the operators that is
103048** allowed for an indexable WHERE clause term.  The allowed operators are
103049** "=", "<", ">", "<=", ">=", and "IN".
103050**
103051** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
103052** of one of the following forms: column = expression column > expression
103053** column >= expression column < expression column <= expression
103054** expression = column expression > column expression >= column
103055** expression < column expression <= column column IN
103056** (expression-list) column IN (subquery) column IS NULL
103057*/
103058static int allowedOp(int op){
103059  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
103060  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
103061  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
103062  assert( TK_GE==TK_EQ+4 );
103063  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
103064}
103065
103066/*
103067** Swap two objects of type TYPE.
103068*/
103069#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
103070
103071/*
103072** Commute a comparison operator.  Expressions of the form "X op Y"
103073** are converted into "Y op X".
103074**
103075** If a collation sequence is associated with either the left or right
103076** side of the comparison, it remains associated with the same side after
103077** the commutation. So "Y collate NOCASE op X" becomes
103078** "X collate NOCASE op Y". This is because any collation sequence on
103079** the left hand side of a comparison overrides any collation sequence
103080** attached to the right. For the same reason the EP_ExpCollate flag
103081** is not commuted.
103082*/
103083static void exprCommute(Parse *pParse, Expr *pExpr){
103084  u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
103085  u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
103086  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
103087  pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
103088  pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
103089  SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
103090  pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
103091  pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
103092  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
103093  if( pExpr->op>=TK_GT ){
103094    assert( TK_LT==TK_GT+2 );
103095    assert( TK_GE==TK_LE+2 );
103096    assert( TK_GT>TK_EQ );
103097    assert( TK_GT<TK_LE );
103098    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
103099    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
103100  }
103101}
103102
103103/*
103104** Translate from TK_xx operator to WO_xx bitmask.
103105*/
103106static u16 operatorMask(int op){
103107  u16 c;
103108  assert( allowedOp(op) );
103109  if( op==TK_IN ){
103110    c = WO_IN;
103111  }else if( op==TK_ISNULL ){
103112    c = WO_ISNULL;
103113  }else{
103114    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
103115    c = (u16)(WO_EQ<<(op-TK_EQ));
103116  }
103117  assert( op!=TK_ISNULL || c==WO_ISNULL );
103118  assert( op!=TK_IN || c==WO_IN );
103119  assert( op!=TK_EQ || c==WO_EQ );
103120  assert( op!=TK_LT || c==WO_LT );
103121  assert( op!=TK_LE || c==WO_LE );
103122  assert( op!=TK_GT || c==WO_GT );
103123  assert( op!=TK_GE || c==WO_GE );
103124  return c;
103125}
103126
103127/*
103128** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
103129** where X is a reference to the iColumn of table iCur and <op> is one of
103130** the WO_xx operator codes specified by the op parameter.
103131** Return a pointer to the term.  Return 0 if not found.
103132*/
103133static WhereTerm *findTerm(
103134  WhereClause *pWC,     /* The WHERE clause to be searched */
103135  int iCur,             /* Cursor number of LHS */
103136  int iColumn,          /* Column number of LHS */
103137  Bitmask notReady,     /* RHS must not overlap with this mask */
103138  u32 op,               /* Mask of WO_xx values describing operator */
103139  Index *pIdx           /* Must be compatible with this index, if not NULL */
103140){
103141  WhereTerm *pTerm;
103142  int k;
103143  assert( iCur>=0 );
103144  op &= WO_ALL;
103145  for(; pWC; pWC=pWC->pOuter){
103146    for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
103147      if( pTerm->leftCursor==iCur
103148         && (pTerm->prereqRight & notReady)==0
103149         && pTerm->u.leftColumn==iColumn
103150         && (pTerm->eOperator & op)!=0
103151      ){
103152        if( iColumn>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
103153          Expr *pX = pTerm->pExpr;
103154          CollSeq *pColl;
103155          char idxaff;
103156          int j;
103157          Parse *pParse = pWC->pParse;
103158
103159          idxaff = pIdx->pTable->aCol[iColumn].affinity;
103160          if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
103161
103162          /* Figure out the collation sequence required from an index for
103163          ** it to be useful for optimising expression pX. Store this
103164          ** value in variable pColl.
103165          */
103166          assert(pX->pLeft);
103167          pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
103168          assert(pColl || pParse->nErr);
103169
103170          for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
103171            if( NEVER(j>=pIdx->nColumn) ) return 0;
103172          }
103173          if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
103174        }
103175        return pTerm;
103176      }
103177    }
103178  }
103179  return 0;
103180}
103181
103182/* Forward reference */
103183static void exprAnalyze(SrcList*, WhereClause*, int);
103184
103185/*
103186** Call exprAnalyze on all terms in a WHERE clause.
103187**
103188**
103189*/
103190static void exprAnalyzeAll(
103191  SrcList *pTabList,       /* the FROM clause */
103192  WhereClause *pWC         /* the WHERE clause to be analyzed */
103193){
103194  int i;
103195  for(i=pWC->nTerm-1; i>=0; i--){
103196    exprAnalyze(pTabList, pWC, i);
103197  }
103198}
103199
103200#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
103201/*
103202** Check to see if the given expression is a LIKE or GLOB operator that
103203** can be optimized using inequality constraints.  Return TRUE if it is
103204** so and false if not.
103205**
103206** In order for the operator to be optimizible, the RHS must be a string
103207** literal that does not begin with a wildcard.
103208*/
103209static int isLikeOrGlob(
103210  Parse *pParse,    /* Parsing and code generating context */
103211  Expr *pExpr,      /* Test this expression */
103212  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
103213  int *pisComplete, /* True if the only wildcard is % in the last character */
103214  int *pnoCase      /* True if uppercase is equivalent to lowercase */
103215){
103216  const char *z = 0;         /* String on RHS of LIKE operator */
103217  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
103218  ExprList *pList;           /* List of operands to the LIKE operator */
103219  int c;                     /* One character in z[] */
103220  int cnt;                   /* Number of non-wildcard prefix characters */
103221  char wc[3];                /* Wildcard characters */
103222  sqlite3 *db = pParse->db;  /* Database connection */
103223  sqlite3_value *pVal = 0;
103224  int op;                    /* Opcode of pRight */
103225
103226  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
103227    return 0;
103228  }
103229#ifdef SQLITE_EBCDIC
103230  if( *pnoCase ) return 0;
103231#endif
103232  pList = pExpr->x.pList;
103233  pLeft = pList->a[1].pExpr;
103234  if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
103235    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
103236    ** be the name of an indexed column with TEXT affinity. */
103237    return 0;
103238  }
103239  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
103240
103241  pRight = pList->a[0].pExpr;
103242  op = pRight->op;
103243  if( op==TK_REGISTER ){
103244    op = pRight->op2;
103245  }
103246  if( op==TK_VARIABLE ){
103247    Vdbe *pReprepare = pParse->pReprepare;
103248    int iCol = pRight->iColumn;
103249    pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
103250    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
103251      z = (char *)sqlite3_value_text(pVal);
103252    }
103253    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
103254    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
103255  }else if( op==TK_STRING ){
103256    z = pRight->u.zToken;
103257  }
103258  if( z ){
103259    cnt = 0;
103260    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
103261      cnt++;
103262    }
103263    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
103264      Expr *pPrefix;
103265      *pisComplete = c==wc[0] && z[cnt+1]==0;
103266      pPrefix = sqlite3Expr(db, TK_STRING, z);
103267      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
103268      *ppPrefix = pPrefix;
103269      if( op==TK_VARIABLE ){
103270        Vdbe *v = pParse->pVdbe;
103271        sqlite3VdbeSetVarmask(v, pRight->iColumn);
103272        if( *pisComplete && pRight->u.zToken[1] ){
103273          /* If the rhs of the LIKE expression is a variable, and the current
103274          ** value of the variable means there is no need to invoke the LIKE
103275          ** function, then no OP_Variable will be added to the program.
103276          ** This causes problems for the sqlite3_bind_parameter_name()
103277          ** API. To workaround them, add a dummy OP_Variable here.
103278          */
103279          int r1 = sqlite3GetTempReg(pParse);
103280          sqlite3ExprCodeTarget(pParse, pRight, r1);
103281          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
103282          sqlite3ReleaseTempReg(pParse, r1);
103283        }
103284      }
103285    }else{
103286      z = 0;
103287    }
103288  }
103289
103290  sqlite3ValueFree(pVal);
103291  return (z!=0);
103292}
103293#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
103294
103295
103296#ifndef SQLITE_OMIT_VIRTUALTABLE
103297/*
103298** Check to see if the given expression is of the form
103299**
103300**         column MATCH expr
103301**
103302** If it is then return TRUE.  If not, return FALSE.
103303*/
103304static int isMatchOfColumn(
103305  Expr *pExpr      /* Test this expression */
103306){
103307  ExprList *pList;
103308
103309  if( pExpr->op!=TK_FUNCTION ){
103310    return 0;
103311  }
103312  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
103313    return 0;
103314  }
103315  pList = pExpr->x.pList;
103316  if( pList->nExpr!=2 ){
103317    return 0;
103318  }
103319  if( pList->a[1].pExpr->op != TK_COLUMN ){
103320    return 0;
103321  }
103322  return 1;
103323}
103324#endif /* SQLITE_OMIT_VIRTUALTABLE */
103325
103326/*
103327** If the pBase expression originated in the ON or USING clause of
103328** a join, then transfer the appropriate markings over to derived.
103329*/
103330static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
103331  pDerived->flags |= pBase->flags & EP_FromJoin;
103332  pDerived->iRightJoinTable = pBase->iRightJoinTable;
103333}
103334
103335#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
103336/*
103337** Analyze a term that consists of two or more OR-connected
103338** subterms.  So in:
103339**
103340**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
103341**                          ^^^^^^^^^^^^^^^^^^^^
103342**
103343** This routine analyzes terms such as the middle term in the above example.
103344** A WhereOrTerm object is computed and attached to the term under
103345** analysis, regardless of the outcome of the analysis.  Hence:
103346**
103347**     WhereTerm.wtFlags   |=  TERM_ORINFO
103348**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
103349**
103350** The term being analyzed must have two or more of OR-connected subterms.
103351** A single subterm might be a set of AND-connected sub-subterms.
103352** Examples of terms under analysis:
103353**
103354**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
103355**     (B)     x=expr1 OR expr2=x OR x=expr3
103356**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
103357**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
103358**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
103359**
103360** CASE 1:
103361**
103362** If all subterms are of the form T.C=expr for some single column of C
103363** a single table T (as shown in example B above) then create a new virtual
103364** term that is an equivalent IN expression.  In other words, if the term
103365** being analyzed is:
103366**
103367**      x = expr1  OR  expr2 = x  OR  x = expr3
103368**
103369** then create a new virtual term like this:
103370**
103371**      x IN (expr1,expr2,expr3)
103372**
103373** CASE 2:
103374**
103375** If all subterms are indexable by a single table T, then set
103376**
103377**     WhereTerm.eOperator              =  WO_OR
103378**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
103379**
103380** A subterm is "indexable" if it is of the form
103381** "T.C <op> <expr>" where C is any column of table T and
103382** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
103383** A subterm is also indexable if it is an AND of two or more
103384** subsubterms at least one of which is indexable.  Indexable AND
103385** subterms have their eOperator set to WO_AND and they have
103386** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
103387**
103388** From another point of view, "indexable" means that the subterm could
103389** potentially be used with an index if an appropriate index exists.
103390** This analysis does not consider whether or not the index exists; that
103391** is something the bestIndex() routine will determine.  This analysis
103392** only looks at whether subterms appropriate for indexing exist.
103393**
103394** All examples A through E above all satisfy case 2.  But if a term
103395** also statisfies case 1 (such as B) we know that the optimizer will
103396** always prefer case 1, so in that case we pretend that case 2 is not
103397** satisfied.
103398**
103399** It might be the case that multiple tables are indexable.  For example,
103400** (E) above is indexable on tables P, Q, and R.
103401**
103402** Terms that satisfy case 2 are candidates for lookup by using
103403** separate indices to find rowids for each subterm and composing
103404** the union of all rowids using a RowSet object.  This is similar
103405** to "bitmap indices" in other database engines.
103406**
103407** OTHERWISE:
103408**
103409** If neither case 1 nor case 2 apply, then leave the eOperator set to
103410** zero.  This term is not useful for search.
103411*/
103412static void exprAnalyzeOrTerm(
103413  SrcList *pSrc,            /* the FROM clause */
103414  WhereClause *pWC,         /* the complete WHERE clause */
103415  int idxTerm               /* Index of the OR-term to be analyzed */
103416){
103417  Parse *pParse = pWC->pParse;            /* Parser context */
103418  sqlite3 *db = pParse->db;               /* Database connection */
103419  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
103420  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
103421  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
103422  int i;                                  /* Loop counters */
103423  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
103424  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
103425  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
103426  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
103427  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
103428
103429  /*
103430  ** Break the OR clause into its separate subterms.  The subterms are
103431  ** stored in a WhereClause structure containing within the WhereOrInfo
103432  ** object that is attached to the original OR clause term.
103433  */
103434  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
103435  assert( pExpr->op==TK_OR );
103436  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
103437  if( pOrInfo==0 ) return;
103438  pTerm->wtFlags |= TERM_ORINFO;
103439  pOrWc = &pOrInfo->wc;
103440  whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103441  whereSplit(pOrWc, pExpr, TK_OR);
103442  exprAnalyzeAll(pSrc, pOrWc);
103443  if( db->mallocFailed ) return;
103444  assert( pOrWc->nTerm>=2 );
103445
103446  /*
103447  ** Compute the set of tables that might satisfy cases 1 or 2.
103448  */
103449  indexable = ~(Bitmask)0;
103450  chngToIN = ~(pWC->vmask);
103451  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
103452    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
103453      WhereAndInfo *pAndInfo;
103454      assert( pOrTerm->eOperator==0 );
103455      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
103456      chngToIN = 0;
103457      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
103458      if( pAndInfo ){
103459        WhereClause *pAndWC;
103460        WhereTerm *pAndTerm;
103461        int j;
103462        Bitmask b = 0;
103463        pOrTerm->u.pAndInfo = pAndInfo;
103464        pOrTerm->wtFlags |= TERM_ANDINFO;
103465        pOrTerm->eOperator = WO_AND;
103466        pAndWC = &pAndInfo->wc;
103467        whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103468        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
103469        exprAnalyzeAll(pSrc, pAndWC);
103470        pAndWC->pOuter = pWC;
103471        testcase( db->mallocFailed );
103472        if( !db->mallocFailed ){
103473          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
103474            assert( pAndTerm->pExpr );
103475            if( allowedOp(pAndTerm->pExpr->op) ){
103476              b |= getMask(pMaskSet, pAndTerm->leftCursor);
103477            }
103478          }
103479        }
103480        indexable &= b;
103481      }
103482    }else if( pOrTerm->wtFlags & TERM_COPIED ){
103483      /* Skip this term for now.  We revisit it when we process the
103484      ** corresponding TERM_VIRTUAL term */
103485    }else{
103486      Bitmask b;
103487      b = getMask(pMaskSet, pOrTerm->leftCursor);
103488      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
103489        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
103490        b |= getMask(pMaskSet, pOther->leftCursor);
103491      }
103492      indexable &= b;
103493      if( pOrTerm->eOperator!=WO_EQ ){
103494        chngToIN = 0;
103495      }else{
103496        chngToIN &= b;
103497      }
103498    }
103499  }
103500
103501  /*
103502  ** Record the set of tables that satisfy case 2.  The set might be
103503  ** empty.
103504  */
103505  pOrInfo->indexable = indexable;
103506  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
103507
103508  /*
103509  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
103510  ** we have to do some additional checking to see if case 1 really
103511  ** is satisfied.
103512  **
103513  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
103514  ** that there is no possibility of transforming the OR clause into an
103515  ** IN operator because one or more terms in the OR clause contain
103516  ** something other than == on a column in the single table.  The 1-bit
103517  ** case means that every term of the OR clause is of the form
103518  ** "table.column=expr" for some single table.  The one bit that is set
103519  ** will correspond to the common table.  We still need to check to make
103520  ** sure the same column is used on all terms.  The 2-bit case is when
103521  ** the all terms are of the form "table1.column=table2.column".  It
103522  ** might be possible to form an IN operator with either table1.column
103523  ** or table2.column as the LHS if either is common to every term of
103524  ** the OR clause.
103525  **
103526  ** Note that terms of the form "table.column1=table.column2" (the
103527  ** same table on both sizes of the ==) cannot be optimized.
103528  */
103529  if( chngToIN ){
103530    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
103531    int iColumn = -1;         /* Column index on lhs of IN operator */
103532    int iCursor = -1;         /* Table cursor common to all terms */
103533    int j = 0;                /* Loop counter */
103534
103535    /* Search for a table and column that appears on one side or the
103536    ** other of the == operator in every subterm.  That table and column
103537    ** will be recorded in iCursor and iColumn.  There might not be any
103538    ** such table and column.  Set okToChngToIN if an appropriate table
103539    ** and column is found but leave okToChngToIN false if not found.
103540    */
103541    for(j=0; j<2 && !okToChngToIN; j++){
103542      pOrTerm = pOrWc->a;
103543      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
103544        assert( pOrTerm->eOperator==WO_EQ );
103545        pOrTerm->wtFlags &= ~TERM_OR_OK;
103546        if( pOrTerm->leftCursor==iCursor ){
103547          /* This is the 2-bit case and we are on the second iteration and
103548          ** current term is from the first iteration.  So skip this term. */
103549          assert( j==1 );
103550          continue;
103551        }
103552        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
103553          /* This term must be of the form t1.a==t2.b where t2 is in the
103554          ** chngToIN set but t1 is not.  This term will be either preceeded
103555          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
103556          ** and use its inversion. */
103557          testcase( pOrTerm->wtFlags & TERM_COPIED );
103558          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
103559          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
103560          continue;
103561        }
103562        iColumn = pOrTerm->u.leftColumn;
103563        iCursor = pOrTerm->leftCursor;
103564        break;
103565      }
103566      if( i<0 ){
103567        /* No candidate table+column was found.  This can only occur
103568        ** on the second iteration */
103569        assert( j==1 );
103570        assert( (chngToIN&(chngToIN-1))==0 );
103571        assert( chngToIN==getMask(pMaskSet, iCursor) );
103572        break;
103573      }
103574      testcase( j==1 );
103575
103576      /* We have found a candidate table and column.  Check to see if that
103577      ** table and column is common to every term in the OR clause */
103578      okToChngToIN = 1;
103579      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
103580        assert( pOrTerm->eOperator==WO_EQ );
103581        if( pOrTerm->leftCursor!=iCursor ){
103582          pOrTerm->wtFlags &= ~TERM_OR_OK;
103583        }else if( pOrTerm->u.leftColumn!=iColumn ){
103584          okToChngToIN = 0;
103585        }else{
103586          int affLeft, affRight;
103587          /* If the right-hand side is also a column, then the affinities
103588          ** of both right and left sides must be such that no type
103589          ** conversions are required on the right.  (Ticket #2249)
103590          */
103591          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
103592          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
103593          if( affRight!=0 && affRight!=affLeft ){
103594            okToChngToIN = 0;
103595          }else{
103596            pOrTerm->wtFlags |= TERM_OR_OK;
103597          }
103598        }
103599      }
103600    }
103601
103602    /* At this point, okToChngToIN is true if original pTerm satisfies
103603    ** case 1.  In that case, construct a new virtual term that is
103604    ** pTerm converted into an IN operator.
103605    **
103606    ** EV: R-00211-15100
103607    */
103608    if( okToChngToIN ){
103609      Expr *pDup;            /* A transient duplicate expression */
103610      ExprList *pList = 0;   /* The RHS of the IN operator */
103611      Expr *pLeft = 0;       /* The LHS of the IN operator */
103612      Expr *pNew;            /* The complete IN operator */
103613
103614      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
103615        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
103616        assert( pOrTerm->eOperator==WO_EQ );
103617        assert( pOrTerm->leftCursor==iCursor );
103618        assert( pOrTerm->u.leftColumn==iColumn );
103619        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
103620        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
103621        pLeft = pOrTerm->pExpr->pLeft;
103622      }
103623      assert( pLeft!=0 );
103624      pDup = sqlite3ExprDup(db, pLeft, 0);
103625      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
103626      if( pNew ){
103627        int idxNew;
103628        transferJoinMarkings(pNew, pExpr);
103629        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
103630        pNew->x.pList = pList;
103631        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
103632        testcase( idxNew==0 );
103633        exprAnalyze(pSrc, pWC, idxNew);
103634        pTerm = &pWC->a[idxTerm];
103635        pWC->a[idxNew].iParent = idxTerm;
103636        pTerm->nChild = 1;
103637      }else{
103638        sqlite3ExprListDelete(db, pList);
103639      }
103640      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
103641    }
103642  }
103643}
103644#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
103645
103646
103647/*
103648** The input to this routine is an WhereTerm structure with only the
103649** "pExpr" field filled in.  The job of this routine is to analyze the
103650** subexpression and populate all the other fields of the WhereTerm
103651** structure.
103652**
103653** If the expression is of the form "<expr> <op> X" it gets commuted
103654** to the standard form of "X <op> <expr>".
103655**
103656** If the expression is of the form "X <op> Y" where both X and Y are
103657** columns, then the original expression is unchanged and a new virtual
103658** term of the form "Y <op> X" is added to the WHERE clause and
103659** analyzed separately.  The original term is marked with TERM_COPIED
103660** and the new term is marked with TERM_DYNAMIC (because it's pExpr
103661** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
103662** is a commuted copy of a prior term.)  The original term has nChild=1
103663** and the copy has idxParent set to the index of the original term.
103664*/
103665static void exprAnalyze(
103666  SrcList *pSrc,            /* the FROM clause */
103667  WhereClause *pWC,         /* the WHERE clause */
103668  int idxTerm               /* Index of the term to be analyzed */
103669){
103670  WhereTerm *pTerm;                /* The term to be analyzed */
103671  WhereMaskSet *pMaskSet;          /* Set of table index masks */
103672  Expr *pExpr;                     /* The expression to be analyzed */
103673  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
103674  Bitmask prereqAll;               /* Prerequesites of pExpr */
103675  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
103676  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
103677  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
103678  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
103679  int op;                          /* Top-level operator.  pExpr->op */
103680  Parse *pParse = pWC->pParse;     /* Parsing context */
103681  sqlite3 *db = pParse->db;        /* Database connection */
103682
103683  if( db->mallocFailed ){
103684    return;
103685  }
103686  pTerm = &pWC->a[idxTerm];
103687  pMaskSet = pWC->pMaskSet;
103688  pExpr = pTerm->pExpr;
103689  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
103690  op = pExpr->op;
103691  if( op==TK_IN ){
103692    assert( pExpr->pRight==0 );
103693    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
103694      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
103695    }else{
103696      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
103697    }
103698  }else if( op==TK_ISNULL ){
103699    pTerm->prereqRight = 0;
103700  }else{
103701    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
103702  }
103703  prereqAll = exprTableUsage(pMaskSet, pExpr);
103704  if( ExprHasProperty(pExpr, EP_FromJoin) ){
103705    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
103706    prereqAll |= x;
103707    extraRight = x-1;  /* ON clause terms may not be used with an index
103708                       ** on left table of a LEFT JOIN.  Ticket #3015 */
103709  }
103710  pTerm->prereqAll = prereqAll;
103711  pTerm->leftCursor = -1;
103712  pTerm->iParent = -1;
103713  pTerm->eOperator = 0;
103714  if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
103715    Expr *pLeft = pExpr->pLeft;
103716    Expr *pRight = pExpr->pRight;
103717    if( pLeft->op==TK_COLUMN ){
103718      pTerm->leftCursor = pLeft->iTable;
103719      pTerm->u.leftColumn = pLeft->iColumn;
103720      pTerm->eOperator = operatorMask(op);
103721    }
103722    if( pRight && pRight->op==TK_COLUMN ){
103723      WhereTerm *pNew;
103724      Expr *pDup;
103725      if( pTerm->leftCursor>=0 ){
103726        int idxNew;
103727        pDup = sqlite3ExprDup(db, pExpr, 0);
103728        if( db->mallocFailed ){
103729          sqlite3ExprDelete(db, pDup);
103730          return;
103731        }
103732        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
103733        if( idxNew==0 ) return;
103734        pNew = &pWC->a[idxNew];
103735        pNew->iParent = idxTerm;
103736        pTerm = &pWC->a[idxTerm];
103737        pTerm->nChild = 1;
103738        pTerm->wtFlags |= TERM_COPIED;
103739      }else{
103740        pDup = pExpr;
103741        pNew = pTerm;
103742      }
103743      exprCommute(pParse, pDup);
103744      pLeft = pDup->pLeft;
103745      pNew->leftCursor = pLeft->iTable;
103746      pNew->u.leftColumn = pLeft->iColumn;
103747      testcase( (prereqLeft | extraRight) != prereqLeft );
103748      pNew->prereqRight = prereqLeft | extraRight;
103749      pNew->prereqAll = prereqAll;
103750      pNew->eOperator = operatorMask(pDup->op);
103751    }
103752  }
103753
103754#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
103755  /* If a term is the BETWEEN operator, create two new virtual terms
103756  ** that define the range that the BETWEEN implements.  For example:
103757  **
103758  **      a BETWEEN b AND c
103759  **
103760  ** is converted into:
103761  **
103762  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
103763  **
103764  ** The two new terms are added onto the end of the WhereClause object.
103765  ** The new terms are "dynamic" and are children of the original BETWEEN
103766  ** term.  That means that if the BETWEEN term is coded, the children are
103767  ** skipped.  Or, if the children are satisfied by an index, the original
103768  ** BETWEEN term is skipped.
103769  */
103770  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
103771    ExprList *pList = pExpr->x.pList;
103772    int i;
103773    static const u8 ops[] = {TK_GE, TK_LE};
103774    assert( pList!=0 );
103775    assert( pList->nExpr==2 );
103776    for(i=0; i<2; i++){
103777      Expr *pNewExpr;
103778      int idxNew;
103779      pNewExpr = sqlite3PExpr(pParse, ops[i],
103780                             sqlite3ExprDup(db, pExpr->pLeft, 0),
103781                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
103782      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
103783      testcase( idxNew==0 );
103784      exprAnalyze(pSrc, pWC, idxNew);
103785      pTerm = &pWC->a[idxTerm];
103786      pWC->a[idxNew].iParent = idxTerm;
103787    }
103788    pTerm->nChild = 2;
103789  }
103790#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
103791
103792#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
103793  /* Analyze a term that is composed of two or more subterms connected by
103794  ** an OR operator.
103795  */
103796  else if( pExpr->op==TK_OR ){
103797    assert( pWC->op==TK_AND );
103798    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
103799    pTerm = &pWC->a[idxTerm];
103800  }
103801#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
103802
103803#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
103804  /* Add constraints to reduce the search space on a LIKE or GLOB
103805  ** operator.
103806  **
103807  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
103808  **
103809  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
103810  **
103811  ** The last character of the prefix "abc" is incremented to form the
103812  ** termination condition "abd".
103813  */
103814  if( pWC->op==TK_AND
103815   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
103816  ){
103817    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
103818    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
103819    Expr *pNewExpr1;
103820    Expr *pNewExpr2;
103821    int idxNew1;
103822    int idxNew2;
103823    CollSeq *pColl;    /* Collating sequence to use */
103824
103825    pLeft = pExpr->x.pList->a[1].pExpr;
103826    pStr2 = sqlite3ExprDup(db, pStr1, 0);
103827    if( !db->mallocFailed ){
103828      u8 c, *pC;       /* Last character before the first wildcard */
103829      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
103830      c = *pC;
103831      if( noCase ){
103832        /* The point is to increment the last character before the first
103833        ** wildcard.  But if we increment '@', that will push it into the
103834        ** alphabetic range where case conversions will mess up the
103835        ** inequality.  To avoid this, make sure to also run the full
103836        ** LIKE on all candidate expressions by clearing the isComplete flag
103837        */
103838        if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
103839
103840
103841        c = sqlite3UpperToLower[c];
103842      }
103843      *pC = c + 1;
103844    }
103845    pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
103846    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
103847                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
103848                     pStr1, 0);
103849    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
103850    testcase( idxNew1==0 );
103851    exprAnalyze(pSrc, pWC, idxNew1);
103852    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
103853                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
103854                     pStr2, 0);
103855    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
103856    testcase( idxNew2==0 );
103857    exprAnalyze(pSrc, pWC, idxNew2);
103858    pTerm = &pWC->a[idxTerm];
103859    if( isComplete ){
103860      pWC->a[idxNew1].iParent = idxTerm;
103861      pWC->a[idxNew2].iParent = idxTerm;
103862      pTerm->nChild = 2;
103863    }
103864  }
103865#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
103866
103867#ifndef SQLITE_OMIT_VIRTUALTABLE
103868  /* Add a WO_MATCH auxiliary term to the constraint set if the
103869  ** current expression is of the form:  column MATCH expr.
103870  ** This information is used by the xBestIndex methods of
103871  ** virtual tables.  The native query optimizer does not attempt
103872  ** to do anything with MATCH functions.
103873  */
103874  if( isMatchOfColumn(pExpr) ){
103875    int idxNew;
103876    Expr *pRight, *pLeft;
103877    WhereTerm *pNewTerm;
103878    Bitmask prereqColumn, prereqExpr;
103879
103880    pRight = pExpr->x.pList->a[0].pExpr;
103881    pLeft = pExpr->x.pList->a[1].pExpr;
103882    prereqExpr = exprTableUsage(pMaskSet, pRight);
103883    prereqColumn = exprTableUsage(pMaskSet, pLeft);
103884    if( (prereqExpr & prereqColumn)==0 ){
103885      Expr *pNewExpr;
103886      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
103887                              0, sqlite3ExprDup(db, pRight, 0), 0);
103888      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
103889      testcase( idxNew==0 );
103890      pNewTerm = &pWC->a[idxNew];
103891      pNewTerm->prereqRight = prereqExpr;
103892      pNewTerm->leftCursor = pLeft->iTable;
103893      pNewTerm->u.leftColumn = pLeft->iColumn;
103894      pNewTerm->eOperator = WO_MATCH;
103895      pNewTerm->iParent = idxTerm;
103896      pTerm = &pWC->a[idxTerm];
103897      pTerm->nChild = 1;
103898      pTerm->wtFlags |= TERM_COPIED;
103899      pNewTerm->prereqAll = pTerm->prereqAll;
103900    }
103901  }
103902#endif /* SQLITE_OMIT_VIRTUALTABLE */
103903
103904#ifdef SQLITE_ENABLE_STAT3
103905  /* When sqlite_stat3 histogram data is available an operator of the
103906  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
103907  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
103908  ** virtual term of that form.
103909  **
103910  ** Note that the virtual term must be tagged with TERM_VNULL.  This
103911  ** TERM_VNULL tag will suppress the not-null check at the beginning
103912  ** of the loop.  Without the TERM_VNULL flag, the not-null check at
103913  ** the start of the loop will prevent any results from being returned.
103914  */
103915  if( pExpr->op==TK_NOTNULL
103916   && pExpr->pLeft->op==TK_COLUMN
103917   && pExpr->pLeft->iColumn>=0
103918  ){
103919    Expr *pNewExpr;
103920    Expr *pLeft = pExpr->pLeft;
103921    int idxNew;
103922    WhereTerm *pNewTerm;
103923
103924    pNewExpr = sqlite3PExpr(pParse, TK_GT,
103925                            sqlite3ExprDup(db, pLeft, 0),
103926                            sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
103927
103928    idxNew = whereClauseInsert(pWC, pNewExpr,
103929                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
103930    if( idxNew ){
103931      pNewTerm = &pWC->a[idxNew];
103932      pNewTerm->prereqRight = 0;
103933      pNewTerm->leftCursor = pLeft->iTable;
103934      pNewTerm->u.leftColumn = pLeft->iColumn;
103935      pNewTerm->eOperator = WO_GT;
103936      pNewTerm->iParent = idxTerm;
103937      pTerm = &pWC->a[idxTerm];
103938      pTerm->nChild = 1;
103939      pTerm->wtFlags |= TERM_COPIED;
103940      pNewTerm->prereqAll = pTerm->prereqAll;
103941    }
103942  }
103943#endif /* SQLITE_ENABLE_STAT */
103944
103945  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
103946  ** an index for tables to the left of the join.
103947  */
103948  pTerm->prereqRight |= extraRight;
103949}
103950
103951/*
103952** Return TRUE if any of the expressions in pList->a[iFirst...] contain
103953** a reference to any table other than the iBase table.
103954*/
103955static int referencesOtherTables(
103956  ExprList *pList,          /* Search expressions in ths list */
103957  WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
103958  int iFirst,               /* Be searching with the iFirst-th expression */
103959  int iBase                 /* Ignore references to this table */
103960){
103961  Bitmask allowed = ~getMask(pMaskSet, iBase);
103962  while( iFirst<pList->nExpr ){
103963    if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
103964      return 1;
103965    }
103966  }
103967  return 0;
103968}
103969
103970/*
103971** This function searches the expression list passed as the second argument
103972** for an expression of type TK_COLUMN that refers to the same column and
103973** uses the same collation sequence as the iCol'th column of index pIdx.
103974** Argument iBase is the cursor number used for the table that pIdx refers
103975** to.
103976**
103977** If such an expression is found, its index in pList->a[] is returned. If
103978** no expression is found, -1 is returned.
103979*/
103980static int findIndexCol(
103981  Parse *pParse,                  /* Parse context */
103982  ExprList *pList,                /* Expression list to search */
103983  int iBase,                      /* Cursor for table associated with pIdx */
103984  Index *pIdx,                    /* Index to match column of */
103985  int iCol                        /* Column of index to match */
103986){
103987  int i;
103988  const char *zColl = pIdx->azColl[iCol];
103989
103990  for(i=0; i<pList->nExpr; i++){
103991    Expr *p = pList->a[i].pExpr;
103992    if( p->op==TK_COLUMN
103993     && p->iColumn==pIdx->aiColumn[iCol]
103994     && p->iTable==iBase
103995    ){
103996      CollSeq *pColl = sqlite3ExprCollSeq(pParse, p);
103997      if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
103998        return i;
103999      }
104000    }
104001  }
104002
104003  return -1;
104004}
104005
104006/*
104007** This routine determines if pIdx can be used to assist in processing a
104008** DISTINCT qualifier. In other words, it tests whether or not using this
104009** index for the outer loop guarantees that rows with equal values for
104010** all expressions in the pDistinct list are delivered grouped together.
104011**
104012** For example, the query
104013**
104014**   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
104015**
104016** can benefit from any index on columns "b" and "c".
104017*/
104018static int isDistinctIndex(
104019  Parse *pParse,                  /* Parsing context */
104020  WhereClause *pWC,               /* The WHERE clause */
104021  Index *pIdx,                    /* The index being considered */
104022  int base,                       /* Cursor number for the table pIdx is on */
104023  ExprList *pDistinct,            /* The DISTINCT expressions */
104024  int nEqCol                      /* Number of index columns with == */
104025){
104026  Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
104027  int i;                          /* Iterator variable */
104028
104029  if( pIdx->zName==0 || pDistinct==0 || pDistinct->nExpr>=BMS ) return 0;
104030  testcase( pDistinct->nExpr==BMS-1 );
104031
104032  /* Loop through all the expressions in the distinct list. If any of them
104033  ** are not simple column references, return early. Otherwise, test if the
104034  ** WHERE clause contains a "col=X" clause. If it does, the expression
104035  ** can be ignored. If it does not, and the column does not belong to the
104036  ** same table as index pIdx, return early. Finally, if there is no
104037  ** matching "col=X" expression and the column is on the same table as pIdx,
104038  ** set the corresponding bit in variable mask.
104039  */
104040  for(i=0; i<pDistinct->nExpr; i++){
104041    WhereTerm *pTerm;
104042    Expr *p = pDistinct->a[i].pExpr;
104043    if( p->op!=TK_COLUMN ) return 0;
104044    pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
104045    if( pTerm ){
104046      Expr *pX = pTerm->pExpr;
104047      CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104048      CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
104049      if( p1==p2 ) continue;
104050    }
104051    if( p->iTable!=base ) return 0;
104052    mask |= (((Bitmask)1) << i);
104053  }
104054
104055  for(i=nEqCol; mask && i<pIdx->nColumn; i++){
104056    int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
104057    if( iExpr<0 ) break;
104058    mask &= ~(((Bitmask)1) << iExpr);
104059  }
104060
104061  return (mask==0);
104062}
104063
104064
104065/*
104066** Return true if the DISTINCT expression-list passed as the third argument
104067** is redundant. A DISTINCT list is redundant if the database contains a
104068** UNIQUE index that guarantees that the result of the query will be distinct
104069** anyway.
104070*/
104071static int isDistinctRedundant(
104072  Parse *pParse,
104073  SrcList *pTabList,
104074  WhereClause *pWC,
104075  ExprList *pDistinct
104076){
104077  Table *pTab;
104078  Index *pIdx;
104079  int i;
104080  int iBase;
104081
104082  /* If there is more than one table or sub-select in the FROM clause of
104083  ** this query, then it will not be possible to show that the DISTINCT
104084  ** clause is redundant. */
104085  if( pTabList->nSrc!=1 ) return 0;
104086  iBase = pTabList->a[0].iCursor;
104087  pTab = pTabList->a[0].pTab;
104088
104089  /* If any of the expressions is an IPK column on table iBase, then return
104090  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
104091  ** current SELECT is a correlated sub-query.
104092  */
104093  for(i=0; i<pDistinct->nExpr; i++){
104094    Expr *p = pDistinct->a[i].pExpr;
104095    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
104096  }
104097
104098  /* Loop through all indices on the table, checking each to see if it makes
104099  ** the DISTINCT qualifier redundant. It does so if:
104100  **
104101  **   1. The index is itself UNIQUE, and
104102  **
104103  **   2. All of the columns in the index are either part of the pDistinct
104104  **      list, or else the WHERE clause contains a term of the form "col=X",
104105  **      where X is a constant value. The collation sequences of the
104106  **      comparison and select-list expressions must match those of the index.
104107  */
104108  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
104109    if( pIdx->onError==OE_None ) continue;
104110    for(i=0; i<pIdx->nColumn; i++){
104111      int iCol = pIdx->aiColumn[i];
104112      if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx)
104113       && 0>findIndexCol(pParse, pDistinct, iBase, pIdx, i)
104114      ){
104115        break;
104116      }
104117    }
104118    if( i==pIdx->nColumn ){
104119      /* This index implies that the DISTINCT qualifier is redundant. */
104120      return 1;
104121    }
104122  }
104123
104124  return 0;
104125}
104126
104127/*
104128** This routine decides if pIdx can be used to satisfy the ORDER BY
104129** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
104130** ORDER BY clause, this routine returns 0.
104131**
104132** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
104133** left-most table in the FROM clause of that same SELECT statement and
104134** the table has a cursor number of "base".  pIdx is an index on pTab.
104135**
104136** nEqCol is the number of columns of pIdx that are used as equality
104137** constraints.  Any of these columns may be missing from the ORDER BY
104138** clause and the match can still be a success.
104139**
104140** All terms of the ORDER BY that match against the index must be either
104141** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
104142** index do not need to satisfy this constraint.)  The *pbRev value is
104143** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
104144** the ORDER BY clause is all ASC.
104145*/
104146static int isSortingIndex(
104147  Parse *pParse,          /* Parsing context */
104148  WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
104149  Index *pIdx,            /* The index we are testing */
104150  int base,               /* Cursor number for the table to be sorted */
104151  ExprList *pOrderBy,     /* The ORDER BY clause */
104152  int nEqCol,             /* Number of index columns with == constraints */
104153  int wsFlags,            /* Index usages flags */
104154  int *pbRev              /* Set to 1 if ORDER BY is DESC */
104155){
104156  int i, j;                       /* Loop counters */
104157  int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
104158  int nTerm;                      /* Number of ORDER BY terms */
104159  struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
104160  sqlite3 *db = pParse->db;
104161
104162  if( !pOrderBy ) return 0;
104163  if( wsFlags & WHERE_COLUMN_IN ) return 0;
104164  if( pIdx->bUnordered ) return 0;
104165
104166  nTerm = pOrderBy->nExpr;
104167  assert( nTerm>0 );
104168
104169  /* Argument pIdx must either point to a 'real' named index structure,
104170  ** or an index structure allocated on the stack by bestBtreeIndex() to
104171  ** represent the rowid index that is part of every table.  */
104172  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
104173
104174  /* Match terms of the ORDER BY clause against columns of
104175  ** the index.
104176  **
104177  ** Note that indices have pIdx->nColumn regular columns plus
104178  ** one additional column containing the rowid.  The rowid column
104179  ** of the index is also allowed to match against the ORDER BY
104180  ** clause.
104181  */
104182  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
104183    Expr *pExpr;       /* The expression of the ORDER BY pTerm */
104184    CollSeq *pColl;    /* The collating sequence of pExpr */
104185    int termSortOrder; /* Sort order for this term */
104186    int iColumn;       /* The i-th column of the index.  -1 for rowid */
104187    int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
104188    const char *zColl; /* Name of the collating sequence for i-th index term */
104189
104190    pExpr = pTerm->pExpr;
104191    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
104192      /* Can not use an index sort on anything that is not a column in the
104193      ** left-most table of the FROM clause */
104194      break;
104195    }
104196    pColl = sqlite3ExprCollSeq(pParse, pExpr);
104197    if( !pColl ){
104198      pColl = db->pDfltColl;
104199    }
104200    if( pIdx->zName && i<pIdx->nColumn ){
104201      iColumn = pIdx->aiColumn[i];
104202      if( iColumn==pIdx->pTable->iPKey ){
104203        iColumn = -1;
104204      }
104205      iSortOrder = pIdx->aSortOrder[i];
104206      zColl = pIdx->azColl[i];
104207    }else{
104208      iColumn = -1;
104209      iSortOrder = 0;
104210      zColl = pColl->zName;
104211    }
104212    if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
104213      /* Term j of the ORDER BY clause does not match column i of the index */
104214      if( i<nEqCol ){
104215        /* If an index column that is constrained by == fails to match an
104216        ** ORDER BY term, that is OK.  Just ignore that column of the index
104217        */
104218        continue;
104219      }else if( i==pIdx->nColumn ){
104220        /* Index column i is the rowid.  All other terms match. */
104221        break;
104222      }else{
104223        /* If an index column fails to match and is not constrained by ==
104224        ** then the index cannot satisfy the ORDER BY constraint.
104225        */
104226        return 0;
104227      }
104228    }
104229    assert( pIdx->aSortOrder!=0 || iColumn==-1 );
104230    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
104231    assert( iSortOrder==0 || iSortOrder==1 );
104232    termSortOrder = iSortOrder ^ pTerm->sortOrder;
104233    if( i>nEqCol ){
104234      if( termSortOrder!=sortOrder ){
104235        /* Indices can only be used if all ORDER BY terms past the
104236        ** equality constraints are all either DESC or ASC. */
104237        return 0;
104238      }
104239    }else{
104240      sortOrder = termSortOrder;
104241    }
104242    j++;
104243    pTerm++;
104244    if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
104245      /* If the indexed column is the primary key and everything matches
104246      ** so far and none of the ORDER BY terms to the right reference other
104247      ** tables in the join, then we are assured that the index can be used
104248      ** to sort because the primary key is unique and so none of the other
104249      ** columns will make any difference
104250      */
104251      j = nTerm;
104252    }
104253  }
104254
104255  *pbRev = sortOrder!=0;
104256  if( j>=nTerm ){
104257    /* All terms of the ORDER BY clause are covered by this index so
104258    ** this index can be used for sorting. */
104259    return 1;
104260  }
104261  if( pIdx->onError!=OE_None && i==pIdx->nColumn
104262      && (wsFlags & WHERE_COLUMN_NULL)==0
104263      && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
104264    /* All terms of this index match some prefix of the ORDER BY clause
104265    ** and the index is UNIQUE and no terms on the tail of the ORDER BY
104266    ** clause reference other tables in a join.  If this is all true then
104267    ** the order by clause is superfluous.  Not that if the matching
104268    ** condition is IS NULL then the result is not necessarily unique
104269    ** even on a UNIQUE index, so disallow those cases. */
104270    return 1;
104271  }
104272  return 0;
104273}
104274
104275/*
104276** Prepare a crude estimate of the logarithm of the input value.
104277** The results need not be exact.  This is only used for estimating
104278** the total cost of performing operations with O(logN) or O(NlogN)
104279** complexity.  Because N is just a guess, it is no great tragedy if
104280** logN is a little off.
104281*/
104282static double estLog(double N){
104283  double logN = 1;
104284  double x = 10;
104285  while( N>x ){
104286    logN += 1;
104287    x *= 10;
104288  }
104289  return logN;
104290}
104291
104292/*
104293** Two routines for printing the content of an sqlite3_index_info
104294** structure.  Used for testing and debugging only.  If neither
104295** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
104296** are no-ops.
104297*/
104298#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
104299static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
104300  int i;
104301  if( !sqlite3WhereTrace ) return;
104302  for(i=0; i<p->nConstraint; i++){
104303    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
104304       i,
104305       p->aConstraint[i].iColumn,
104306       p->aConstraint[i].iTermOffset,
104307       p->aConstraint[i].op,
104308       p->aConstraint[i].usable);
104309  }
104310  for(i=0; i<p->nOrderBy; i++){
104311    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
104312       i,
104313       p->aOrderBy[i].iColumn,
104314       p->aOrderBy[i].desc);
104315  }
104316}
104317static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
104318  int i;
104319  if( !sqlite3WhereTrace ) return;
104320  for(i=0; i<p->nConstraint; i++){
104321    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
104322       i,
104323       p->aConstraintUsage[i].argvIndex,
104324       p->aConstraintUsage[i].omit);
104325  }
104326  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
104327  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
104328  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
104329  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
104330}
104331#else
104332#define TRACE_IDX_INPUTS(A)
104333#define TRACE_IDX_OUTPUTS(A)
104334#endif
104335
104336/*
104337** Required because bestIndex() is called by bestOrClauseIndex()
104338*/
104339static void bestIndex(
104340    Parse*, WhereClause*, struct SrcList_item*,
104341    Bitmask, Bitmask, ExprList*, WhereCost*);
104342
104343/*
104344** This routine attempts to find an scanning strategy that can be used
104345** to optimize an 'OR' expression that is part of a WHERE clause.
104346**
104347** The table associated with FROM clause term pSrc may be either a
104348** regular B-Tree table or a virtual table.
104349*/
104350static void bestOrClauseIndex(
104351  Parse *pParse,              /* The parsing context */
104352  WhereClause *pWC,           /* The WHERE clause */
104353  struct SrcList_item *pSrc,  /* The FROM clause term to search */
104354  Bitmask notReady,           /* Mask of cursors not available for indexing */
104355  Bitmask notValid,           /* Cursors not available for any purpose */
104356  ExprList *pOrderBy,         /* The ORDER BY clause */
104357  WhereCost *pCost            /* Lowest cost query plan */
104358){
104359#ifndef SQLITE_OMIT_OR_OPTIMIZATION
104360  const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
104361  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
104362  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
104363  WhereTerm *pTerm;                 /* A single term of the WHERE clause */
104364
104365  /* The OR-clause optimization is disallowed if the INDEXED BY or
104366  ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
104367  if( pSrc->notIndexed || pSrc->pIndex!=0 ){
104368    return;
104369  }
104370  if( pWC->wctrlFlags & WHERE_AND_ONLY ){
104371    return;
104372  }
104373
104374  /* Search the WHERE clause terms for a usable WO_OR term. */
104375  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104376    if( pTerm->eOperator==WO_OR
104377     && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
104378     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
104379    ){
104380      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
104381      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
104382      WhereTerm *pOrTerm;
104383      int flags = WHERE_MULTI_OR;
104384      double rTotal = 0;
104385      double nRow = 0;
104386      Bitmask used = 0;
104387
104388      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
104389        WhereCost sTermCost;
104390        WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
104391          (pOrTerm - pOrWC->a), (pTerm - pWC->a)
104392        ));
104393        if( pOrTerm->eOperator==WO_AND ){
104394          WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
104395          bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
104396        }else if( pOrTerm->leftCursor==iCur ){
104397          WhereClause tempWC;
104398          tempWC.pParse = pWC->pParse;
104399          tempWC.pMaskSet = pWC->pMaskSet;
104400          tempWC.pOuter = pWC;
104401          tempWC.op = TK_AND;
104402          tempWC.a = pOrTerm;
104403          tempWC.wctrlFlags = 0;
104404          tempWC.nTerm = 1;
104405          bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
104406        }else{
104407          continue;
104408        }
104409        rTotal += sTermCost.rCost;
104410        nRow += sTermCost.plan.nRow;
104411        used |= sTermCost.used;
104412        if( rTotal>=pCost->rCost ) break;
104413      }
104414
104415      /* If there is an ORDER BY clause, increase the scan cost to account
104416      ** for the cost of the sort. */
104417      if( pOrderBy!=0 ){
104418        WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
104419                    rTotal, rTotal+nRow*estLog(nRow)));
104420        rTotal += nRow*estLog(nRow);
104421      }
104422
104423      /* If the cost of scanning using this OR term for optimization is
104424      ** less than the current cost stored in pCost, replace the contents
104425      ** of pCost. */
104426      WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
104427      if( rTotal<pCost->rCost ){
104428        pCost->rCost = rTotal;
104429        pCost->used = used;
104430        pCost->plan.nRow = nRow;
104431        pCost->plan.wsFlags = flags;
104432        pCost->plan.u.pTerm = pTerm;
104433      }
104434    }
104435  }
104436#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
104437}
104438
104439#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104440/*
104441** Return TRUE if the WHERE clause term pTerm is of a form where it
104442** could be used with an index to access pSrc, assuming an appropriate
104443** index existed.
104444*/
104445static int termCanDriveIndex(
104446  WhereTerm *pTerm,              /* WHERE clause term to check */
104447  struct SrcList_item *pSrc,     /* Table we are trying to access */
104448  Bitmask notReady               /* Tables in outer loops of the join */
104449){
104450  char aff;
104451  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
104452  if( pTerm->eOperator!=WO_EQ ) return 0;
104453  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
104454  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
104455  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
104456  return 1;
104457}
104458#endif
104459
104460#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104461/*
104462** If the query plan for pSrc specified in pCost is a full table scan
104463** and indexing is allows (if there is no NOT INDEXED clause) and it
104464** possible to construct a transient index that would perform better
104465** than a full table scan even when the cost of constructing the index
104466** is taken into account, then alter the query plan to use the
104467** transient index.
104468*/
104469static void bestAutomaticIndex(
104470  Parse *pParse,              /* The parsing context */
104471  WhereClause *pWC,           /* The WHERE clause */
104472  struct SrcList_item *pSrc,  /* The FROM clause term to search */
104473  Bitmask notReady,           /* Mask of cursors that are not available */
104474  WhereCost *pCost            /* Lowest cost query plan */
104475){
104476  double nTableRow;           /* Rows in the input table */
104477  double logN;                /* log(nTableRow) */
104478  double costTempIdx;         /* per-query cost of the transient index */
104479  WhereTerm *pTerm;           /* A single term of the WHERE clause */
104480  WhereTerm *pWCEnd;          /* End of pWC->a[] */
104481  Table *pTable;              /* Table tht might be indexed */
104482
104483  if( pParse->nQueryLoop<=(double)1 ){
104484    /* There is no point in building an automatic index for a single scan */
104485    return;
104486  }
104487  if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
104488    /* Automatic indices are disabled at run-time */
104489    return;
104490  }
104491  if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
104492    /* We already have some kind of index in use for this query. */
104493    return;
104494  }
104495  if( pSrc->notIndexed ){
104496    /* The NOT INDEXED clause appears in the SQL. */
104497    return;
104498  }
104499  if( pSrc->isCorrelated ){
104500    /* The source is a correlated sub-query. No point in indexing it. */
104501    return;
104502  }
104503
104504  assert( pParse->nQueryLoop >= (double)1 );
104505  pTable = pSrc->pTab;
104506  nTableRow = pTable->nRowEst;
104507  logN = estLog(nTableRow);
104508  costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
104509  if( costTempIdx>=pCost->rCost ){
104510    /* The cost of creating the transient table would be greater than
104511    ** doing the full table scan */
104512    return;
104513  }
104514
104515  /* Search for any equality comparison term */
104516  pWCEnd = &pWC->a[pWC->nTerm];
104517  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104518    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104519      WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
104520                    pCost->rCost, costTempIdx));
104521      pCost->rCost = costTempIdx;
104522      pCost->plan.nRow = logN + 1;
104523      pCost->plan.wsFlags = WHERE_TEMP_INDEX;
104524      pCost->used = pTerm->prereqRight;
104525      break;
104526    }
104527  }
104528}
104529#else
104530# define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
104531#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
104532
104533
104534#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104535/*
104536** Generate code to construct the Index object for an automatic index
104537** and to set up the WhereLevel object pLevel so that the code generator
104538** makes use of the automatic index.
104539*/
104540static void constructAutomaticIndex(
104541  Parse *pParse,              /* The parsing context */
104542  WhereClause *pWC,           /* The WHERE clause */
104543  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
104544  Bitmask notReady,           /* Mask of cursors that are not available */
104545  WhereLevel *pLevel          /* Write new index here */
104546){
104547  int nColumn;                /* Number of columns in the constructed index */
104548  WhereTerm *pTerm;           /* A single term of the WHERE clause */
104549  WhereTerm *pWCEnd;          /* End of pWC->a[] */
104550  int nByte;                  /* Byte of memory needed for pIdx */
104551  Index *pIdx;                /* Object describing the transient index */
104552  Vdbe *v;                    /* Prepared statement under construction */
104553  int addrInit;               /* Address of the initialization bypass jump */
104554  Table *pTable;              /* The table being indexed */
104555  KeyInfo *pKeyinfo;          /* Key information for the index */
104556  int addrTop;                /* Top of the index fill loop */
104557  int regRecord;              /* Register holding an index record */
104558  int n;                      /* Column counter */
104559  int i;                      /* Loop counter */
104560  int mxBitCol;               /* Maximum column in pSrc->colUsed */
104561  CollSeq *pColl;             /* Collating sequence to on a column */
104562  Bitmask idxCols;            /* Bitmap of columns used for indexing */
104563  Bitmask extraCols;          /* Bitmap of additional columns */
104564
104565  /* Generate code to skip over the creation and initialization of the
104566  ** transient index on 2nd and subsequent iterations of the loop. */
104567  v = pParse->pVdbe;
104568  assert( v!=0 );
104569  addrInit = sqlite3CodeOnce(pParse);
104570
104571  /* Count the number of columns that will be added to the index
104572  ** and used to match WHERE clause constraints */
104573  nColumn = 0;
104574  pTable = pSrc->pTab;
104575  pWCEnd = &pWC->a[pWC->nTerm];
104576  idxCols = 0;
104577  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104578    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104579      int iCol = pTerm->u.leftColumn;
104580      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104581      testcase( iCol==BMS );
104582      testcase( iCol==BMS-1 );
104583      if( (idxCols & cMask)==0 ){
104584        nColumn++;
104585        idxCols |= cMask;
104586      }
104587    }
104588  }
104589  assert( nColumn>0 );
104590  pLevel->plan.nEq = nColumn;
104591
104592  /* Count the number of additional columns needed to create a
104593  ** covering index.  A "covering index" is an index that contains all
104594  ** columns that are needed by the query.  With a covering index, the
104595  ** original table never needs to be accessed.  Automatic indices must
104596  ** be a covering index because the index will not be updated if the
104597  ** original table changes and the index and table cannot both be used
104598  ** if they go out of sync.
104599  */
104600  extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
104601  mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
104602  testcase( pTable->nCol==BMS-1 );
104603  testcase( pTable->nCol==BMS-2 );
104604  for(i=0; i<mxBitCol; i++){
104605    if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
104606  }
104607  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104608    nColumn += pTable->nCol - BMS + 1;
104609  }
104610  pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
104611
104612  /* Construct the Index object to describe this index */
104613  nByte = sizeof(Index);
104614  nByte += nColumn*sizeof(int);     /* Index.aiColumn */
104615  nByte += nColumn*sizeof(char*);   /* Index.azColl */
104616  nByte += nColumn;                 /* Index.aSortOrder */
104617  pIdx = sqlite3DbMallocZero(pParse->db, nByte);
104618  if( pIdx==0 ) return;
104619  pLevel->plan.u.pIdx = pIdx;
104620  pIdx->azColl = (char**)&pIdx[1];
104621  pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
104622  pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
104623  pIdx->zName = "auto-index";
104624  pIdx->nColumn = nColumn;
104625  pIdx->pTable = pTable;
104626  n = 0;
104627  idxCols = 0;
104628  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104629    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104630      int iCol = pTerm->u.leftColumn;
104631      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104632      if( (idxCols & cMask)==0 ){
104633        Expr *pX = pTerm->pExpr;
104634        idxCols |= cMask;
104635        pIdx->aiColumn[n] = pTerm->u.leftColumn;
104636        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104637        pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
104638        n++;
104639      }
104640    }
104641  }
104642  assert( (u32)n==pLevel->plan.nEq );
104643
104644  /* Add additional columns needed to make the automatic index into
104645  ** a covering index */
104646  for(i=0; i<mxBitCol; i++){
104647    if( extraCols & (((Bitmask)1)<<i) ){
104648      pIdx->aiColumn[n] = i;
104649      pIdx->azColl[n] = "BINARY";
104650      n++;
104651    }
104652  }
104653  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104654    for(i=BMS-1; i<pTable->nCol; i++){
104655      pIdx->aiColumn[n] = i;
104656      pIdx->azColl[n] = "BINARY";
104657      n++;
104658    }
104659  }
104660  assert( n==nColumn );
104661
104662  /* Create the automatic index */
104663  pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
104664  assert( pLevel->iIdxCur>=0 );
104665  sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
104666                    (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
104667  VdbeComment((v, "for %s", pTable->zName));
104668
104669  /* Fill the automatic index with content */
104670  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
104671  regRecord = sqlite3GetTempReg(pParse);
104672  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
104673  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
104674  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
104675  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
104676  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
104677  sqlite3VdbeJumpHere(v, addrTop);
104678  sqlite3ReleaseTempReg(pParse, regRecord);
104679
104680  /* Jump here when skipping the initialization */
104681  sqlite3VdbeJumpHere(v, addrInit);
104682}
104683#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
104684
104685#ifndef SQLITE_OMIT_VIRTUALTABLE
104686/*
104687** Allocate and populate an sqlite3_index_info structure. It is the
104688** responsibility of the caller to eventually release the structure
104689** by passing the pointer returned by this function to sqlite3_free().
104690*/
104691static sqlite3_index_info *allocateIndexInfo(
104692  Parse *pParse,
104693  WhereClause *pWC,
104694  struct SrcList_item *pSrc,
104695  ExprList *pOrderBy
104696){
104697  int i, j;
104698  int nTerm;
104699  struct sqlite3_index_constraint *pIdxCons;
104700  struct sqlite3_index_orderby *pIdxOrderBy;
104701  struct sqlite3_index_constraint_usage *pUsage;
104702  WhereTerm *pTerm;
104703  int nOrderBy;
104704  sqlite3_index_info *pIdxInfo;
104705
104706  WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
104707
104708  /* Count the number of possible WHERE clause constraints referring
104709  ** to this virtual table */
104710  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
104711    if( pTerm->leftCursor != pSrc->iCursor ) continue;
104712    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
104713    testcase( pTerm->eOperator==WO_IN );
104714    testcase( pTerm->eOperator==WO_ISNULL );
104715    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
104716    if( pTerm->wtFlags & TERM_VNULL ) continue;
104717    nTerm++;
104718  }
104719
104720  /* If the ORDER BY clause contains only columns in the current
104721  ** virtual table then allocate space for the aOrderBy part of
104722  ** the sqlite3_index_info structure.
104723  */
104724  nOrderBy = 0;
104725  if( pOrderBy ){
104726    for(i=0; i<pOrderBy->nExpr; i++){
104727      Expr *pExpr = pOrderBy->a[i].pExpr;
104728      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
104729    }
104730    if( i==pOrderBy->nExpr ){
104731      nOrderBy = pOrderBy->nExpr;
104732    }
104733  }
104734
104735  /* Allocate the sqlite3_index_info structure
104736  */
104737  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
104738                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
104739                           + sizeof(*pIdxOrderBy)*nOrderBy );
104740  if( pIdxInfo==0 ){
104741    sqlite3ErrorMsg(pParse, "out of memory");
104742    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
104743    return 0;
104744  }
104745
104746  /* Initialize the structure.  The sqlite3_index_info structure contains
104747  ** many fields that are declared "const" to prevent xBestIndex from
104748  ** changing them.  We have to do some funky casting in order to
104749  ** initialize those fields.
104750  */
104751  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
104752  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
104753  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
104754  *(int*)&pIdxInfo->nConstraint = nTerm;
104755  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
104756  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
104757  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
104758  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
104759                                                                   pUsage;
104760
104761  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
104762    if( pTerm->leftCursor != pSrc->iCursor ) continue;
104763    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
104764    testcase( pTerm->eOperator==WO_IN );
104765    testcase( pTerm->eOperator==WO_ISNULL );
104766    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
104767    if( pTerm->wtFlags & TERM_VNULL ) continue;
104768    pIdxCons[j].iColumn = pTerm->u.leftColumn;
104769    pIdxCons[j].iTermOffset = i;
104770    pIdxCons[j].op = (u8)pTerm->eOperator;
104771    /* The direct assignment in the previous line is possible only because
104772    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
104773    ** following asserts verify this fact. */
104774    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
104775    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
104776    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
104777    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
104778    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
104779    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
104780    assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
104781    j++;
104782  }
104783  for(i=0; i<nOrderBy; i++){
104784    Expr *pExpr = pOrderBy->a[i].pExpr;
104785    pIdxOrderBy[i].iColumn = pExpr->iColumn;
104786    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
104787  }
104788
104789  return pIdxInfo;
104790}
104791
104792/*
104793** The table object reference passed as the second argument to this function
104794** must represent a virtual table. This function invokes the xBestIndex()
104795** method of the virtual table with the sqlite3_index_info pointer passed
104796** as the argument.
104797**
104798** If an error occurs, pParse is populated with an error message and a
104799** non-zero value is returned. Otherwise, 0 is returned and the output
104800** part of the sqlite3_index_info structure is left populated.
104801**
104802** Whether or not an error is returned, it is the responsibility of the
104803** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
104804** that this is required.
104805*/
104806static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
104807  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
104808  int i;
104809  int rc;
104810
104811  WHERETRACE(("xBestIndex for %s\n", pTab->zName));
104812  TRACE_IDX_INPUTS(p);
104813  rc = pVtab->pModule->xBestIndex(pVtab, p);
104814  TRACE_IDX_OUTPUTS(p);
104815
104816  if( rc!=SQLITE_OK ){
104817    if( rc==SQLITE_NOMEM ){
104818      pParse->db->mallocFailed = 1;
104819    }else if( !pVtab->zErrMsg ){
104820      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
104821    }else{
104822      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
104823    }
104824  }
104825  sqlite3_free(pVtab->zErrMsg);
104826  pVtab->zErrMsg = 0;
104827
104828  for(i=0; i<p->nConstraint; i++){
104829    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
104830      sqlite3ErrorMsg(pParse,
104831          "table %s: xBestIndex returned an invalid plan", pTab->zName);
104832    }
104833  }
104834
104835  return pParse->nErr;
104836}
104837
104838
104839/*
104840** Compute the best index for a virtual table.
104841**
104842** The best index is computed by the xBestIndex method of the virtual
104843** table module.  This routine is really just a wrapper that sets up
104844** the sqlite3_index_info structure that is used to communicate with
104845** xBestIndex.
104846**
104847** In a join, this routine might be called multiple times for the
104848** same virtual table.  The sqlite3_index_info structure is created
104849** and initialized on the first invocation and reused on all subsequent
104850** invocations.  The sqlite3_index_info structure is also used when
104851** code is generated to access the virtual table.  The whereInfoDelete()
104852** routine takes care of freeing the sqlite3_index_info structure after
104853** everybody has finished with it.
104854*/
104855static void bestVirtualIndex(
104856  Parse *pParse,                  /* The parsing context */
104857  WhereClause *pWC,               /* The WHERE clause */
104858  struct SrcList_item *pSrc,      /* The FROM clause term to search */
104859  Bitmask notReady,               /* Mask of cursors not available for index */
104860  Bitmask notValid,               /* Cursors not valid for any purpose */
104861  ExprList *pOrderBy,             /* The order by clause */
104862  WhereCost *pCost,               /* Lowest cost query plan */
104863  sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
104864){
104865  Table *pTab = pSrc->pTab;
104866  sqlite3_index_info *pIdxInfo;
104867  struct sqlite3_index_constraint *pIdxCons;
104868  struct sqlite3_index_constraint_usage *pUsage;
104869  WhereTerm *pTerm;
104870  int i, j;
104871  int nOrderBy;
104872  double rCost;
104873
104874  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
104875  ** malloc in allocateIndexInfo() fails and this function returns leaving
104876  ** wsFlags in an uninitialized state, the caller may behave unpredictably.
104877  */
104878  memset(pCost, 0, sizeof(*pCost));
104879  pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
104880
104881  /* If the sqlite3_index_info structure has not been previously
104882  ** allocated and initialized, then allocate and initialize it now.
104883  */
104884  pIdxInfo = *ppIdxInfo;
104885  if( pIdxInfo==0 ){
104886    *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
104887  }
104888  if( pIdxInfo==0 ){
104889    return;
104890  }
104891
104892  /* At this point, the sqlite3_index_info structure that pIdxInfo points
104893  ** to will have been initialized, either during the current invocation or
104894  ** during some prior invocation.  Now we just have to customize the
104895  ** details of pIdxInfo for the current invocation and pass it to
104896  ** xBestIndex.
104897  */
104898
104899  /* The module name must be defined. Also, by this point there must
104900  ** be a pointer to an sqlite3_vtab structure. Otherwise
104901  ** sqlite3ViewGetColumnNames() would have picked up the error.
104902  */
104903  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
104904  assert( sqlite3GetVTable(pParse->db, pTab) );
104905
104906  /* Set the aConstraint[].usable fields and initialize all
104907  ** output variables to zero.
104908  **
104909  ** aConstraint[].usable is true for constraints where the right-hand
104910  ** side contains only references to tables to the left of the current
104911  ** table.  In other words, if the constraint is of the form:
104912  **
104913  **           column = expr
104914  **
104915  ** and we are evaluating a join, then the constraint on column is
104916  ** only valid if all tables referenced in expr occur to the left
104917  ** of the table containing column.
104918  **
104919  ** The aConstraints[] array contains entries for all constraints
104920  ** on the current table.  That way we only have to compute it once
104921  ** even though we might try to pick the best index multiple times.
104922  ** For each attempt at picking an index, the order of tables in the
104923  ** join might be different so we have to recompute the usable flag
104924  ** each time.
104925  */
104926  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
104927  pUsage = pIdxInfo->aConstraintUsage;
104928  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
104929    j = pIdxCons->iTermOffset;
104930    pTerm = &pWC->a[j];
104931    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
104932  }
104933  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
104934  if( pIdxInfo->needToFreeIdxStr ){
104935    sqlite3_free(pIdxInfo->idxStr);
104936  }
104937  pIdxInfo->idxStr = 0;
104938  pIdxInfo->idxNum = 0;
104939  pIdxInfo->needToFreeIdxStr = 0;
104940  pIdxInfo->orderByConsumed = 0;
104941  /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
104942  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
104943  nOrderBy = pIdxInfo->nOrderBy;
104944  if( !pOrderBy ){
104945    pIdxInfo->nOrderBy = 0;
104946  }
104947
104948  if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
104949    return;
104950  }
104951
104952  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
104953  for(i=0; i<pIdxInfo->nConstraint; i++){
104954    if( pUsage[i].argvIndex>0 ){
104955      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
104956    }
104957  }
104958
104959  /* If there is an ORDER BY clause, and the selected virtual table index
104960  ** does not satisfy it, increase the cost of the scan accordingly. This
104961  ** matches the processing for non-virtual tables in bestBtreeIndex().
104962  */
104963  rCost = pIdxInfo->estimatedCost;
104964  if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
104965    rCost += estLog(rCost)*rCost;
104966  }
104967
104968  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
104969  ** inital value of lowestCost in this loop. If it is, then the
104970  ** (cost<lowestCost) test below will never be true.
104971  **
104972  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
104973  ** is defined.
104974  */
104975  if( (SQLITE_BIG_DBL/((double)2))<rCost ){
104976    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
104977  }else{
104978    pCost->rCost = rCost;
104979  }
104980  pCost->plan.u.pVtabIdx = pIdxInfo;
104981  if( pIdxInfo->orderByConsumed ){
104982    pCost->plan.wsFlags |= WHERE_ORDERBY;
104983  }
104984  pCost->plan.nEq = 0;
104985  pIdxInfo->nOrderBy = nOrderBy;
104986
104987  /* Try to find a more efficient access pattern by using multiple indexes
104988  ** to optimize an OR expression within the WHERE clause.
104989  */
104990  bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
104991}
104992#endif /* SQLITE_OMIT_VIRTUALTABLE */
104993
104994#ifdef SQLITE_ENABLE_STAT3
104995/*
104996** Estimate the location of a particular key among all keys in an
104997** index.  Store the results in aStat as follows:
104998**
104999**    aStat[0]      Est. number of rows less than pVal
105000**    aStat[1]      Est. number of rows equal to pVal
105001**
105002** Return SQLITE_OK on success.
105003*/
105004static int whereKeyStats(
105005  Parse *pParse,              /* Database connection */
105006  Index *pIdx,                /* Index to consider domain of */
105007  sqlite3_value *pVal,        /* Value to consider */
105008  int roundUp,                /* Round up if true.  Round down if false */
105009  tRowcnt *aStat              /* OUT: stats written here */
105010){
105011  tRowcnt n;
105012  IndexSample *aSample;
105013  int i, eType;
105014  int isEq = 0;
105015  i64 v;
105016  double r, rS;
105017
105018  assert( roundUp==0 || roundUp==1 );
105019  assert( pIdx->nSample>0 );
105020  if( pVal==0 ) return SQLITE_ERROR;
105021  n = pIdx->aiRowEst[0];
105022  aSample = pIdx->aSample;
105023  eType = sqlite3_value_type(pVal);
105024
105025  if( eType==SQLITE_INTEGER ){
105026    v = sqlite3_value_int64(pVal);
105027    r = (i64)v;
105028    for(i=0; i<pIdx->nSample; i++){
105029      if( aSample[i].eType==SQLITE_NULL ) continue;
105030      if( aSample[i].eType>=SQLITE_TEXT ) break;
105031      if( aSample[i].eType==SQLITE_INTEGER ){
105032        if( aSample[i].u.i>=v ){
105033          isEq = aSample[i].u.i==v;
105034          break;
105035        }
105036      }else{
105037        assert( aSample[i].eType==SQLITE_FLOAT );
105038        if( aSample[i].u.r>=r ){
105039          isEq = aSample[i].u.r==r;
105040          break;
105041        }
105042      }
105043    }
105044  }else if( eType==SQLITE_FLOAT ){
105045    r = sqlite3_value_double(pVal);
105046    for(i=0; i<pIdx->nSample; i++){
105047      if( aSample[i].eType==SQLITE_NULL ) continue;
105048      if( aSample[i].eType>=SQLITE_TEXT ) break;
105049      if( aSample[i].eType==SQLITE_FLOAT ){
105050        rS = aSample[i].u.r;
105051      }else{
105052        rS = aSample[i].u.i;
105053      }
105054      if( rS>=r ){
105055        isEq = rS==r;
105056        break;
105057      }
105058    }
105059  }else if( eType==SQLITE_NULL ){
105060    i = 0;
105061    if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
105062  }else{
105063    assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
105064    for(i=0; i<pIdx->nSample; i++){
105065      if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
105066        break;
105067      }
105068    }
105069    if( i<pIdx->nSample ){
105070      sqlite3 *db = pParse->db;
105071      CollSeq *pColl;
105072      const u8 *z;
105073      if( eType==SQLITE_BLOB ){
105074        z = (const u8 *)sqlite3_value_blob(pVal);
105075        pColl = db->pDfltColl;
105076        assert( pColl->enc==SQLITE_UTF8 );
105077      }else{
105078        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
105079        if( pColl==0 ){
105080          sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
105081                          *pIdx->azColl);
105082          return SQLITE_ERROR;
105083        }
105084        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
105085        if( !z ){
105086          return SQLITE_NOMEM;
105087        }
105088        assert( z && pColl && pColl->xCmp );
105089      }
105090      n = sqlite3ValueBytes(pVal, pColl->enc);
105091
105092      for(; i<pIdx->nSample; i++){
105093        int c;
105094        int eSampletype = aSample[i].eType;
105095        if( eSampletype<eType ) continue;
105096        if( eSampletype!=eType ) break;
105097#ifndef SQLITE_OMIT_UTF16
105098        if( pColl->enc!=SQLITE_UTF8 ){
105099          int nSample;
105100          char *zSample = sqlite3Utf8to16(
105101              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
105102          );
105103          if( !zSample ){
105104            assert( db->mallocFailed );
105105            return SQLITE_NOMEM;
105106          }
105107          c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
105108          sqlite3DbFree(db, zSample);
105109        }else
105110#endif
105111        {
105112          c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
105113        }
105114        if( c>=0 ){
105115          if( c==0 ) isEq = 1;
105116          break;
105117        }
105118      }
105119    }
105120  }
105121
105122  /* At this point, aSample[i] is the first sample that is greater than
105123  ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
105124  ** than pVal.  If aSample[i]==pVal, then isEq==1.
105125  */
105126  if( isEq ){
105127    assert( i<pIdx->nSample );
105128    aStat[0] = aSample[i].nLt;
105129    aStat[1] = aSample[i].nEq;
105130  }else{
105131    tRowcnt iLower, iUpper, iGap;
105132    if( i==0 ){
105133      iLower = 0;
105134      iUpper = aSample[0].nLt;
105135    }else{
105136      iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
105137      iLower = aSample[i-1].nEq + aSample[i-1].nLt;
105138    }
105139    aStat[1] = pIdx->avgEq;
105140    if( iLower>=iUpper ){
105141      iGap = 0;
105142    }else{
105143      iGap = iUpper - iLower;
105144    }
105145    if( roundUp ){
105146      iGap = (iGap*2)/3;
105147    }else{
105148      iGap = iGap/3;
105149    }
105150    aStat[0] = iLower + iGap;
105151  }
105152  return SQLITE_OK;
105153}
105154#endif /* SQLITE_ENABLE_STAT3 */
105155
105156/*
105157** If expression pExpr represents a literal value, set *pp to point to
105158** an sqlite3_value structure containing the same value, with affinity
105159** aff applied to it, before returning. It is the responsibility of the
105160** caller to eventually release this structure by passing it to
105161** sqlite3ValueFree().
105162**
105163** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
105164** is an SQL variable that currently has a non-NULL value bound to it,
105165** create an sqlite3_value structure containing this value, again with
105166** affinity aff applied to it, instead.
105167**
105168** If neither of the above apply, set *pp to NULL.
105169**
105170** If an error occurs, return an error code. Otherwise, SQLITE_OK.
105171*/
105172#ifdef SQLITE_ENABLE_STAT3
105173static int valueFromExpr(
105174  Parse *pParse,
105175  Expr *pExpr,
105176  u8 aff,
105177  sqlite3_value **pp
105178){
105179  if( pExpr->op==TK_VARIABLE
105180   || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
105181  ){
105182    int iVar = pExpr->iColumn;
105183    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
105184    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
105185    return SQLITE_OK;
105186  }
105187  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
105188}
105189#endif
105190
105191/*
105192** This function is used to estimate the number of rows that will be visited
105193** by scanning an index for a range of values. The range may have an upper
105194** bound, a lower bound, or both. The WHERE clause terms that set the upper
105195** and lower bounds are represented by pLower and pUpper respectively. For
105196** example, assuming that index p is on t1(a):
105197**
105198**   ... FROM t1 WHERE a > ? AND a < ? ...
105199**                    |_____|   |_____|
105200**                       |         |
105201**                     pLower    pUpper
105202**
105203** If either of the upper or lower bound is not present, then NULL is passed in
105204** place of the corresponding WhereTerm.
105205**
105206** The nEq parameter is passed the index of the index column subject to the
105207** range constraint. Or, equivalently, the number of equality constraints
105208** optimized by the proposed index scan. For example, assuming index p is
105209** on t1(a, b), and the SQL query is:
105210**
105211**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
105212**
105213** then nEq should be passed the value 1 (as the range restricted column,
105214** b, is the second left-most column of the index). Or, if the query is:
105215**
105216**   ... FROM t1 WHERE a > ? AND a < ? ...
105217**
105218** then nEq should be passed 0.
105219**
105220** The returned value is an integer divisor to reduce the estimated
105221** search space.  A return value of 1 means that range constraints are
105222** no help at all.  A return value of 2 means range constraints are
105223** expected to reduce the search space by half.  And so forth...
105224**
105225** In the absence of sqlite_stat3 ANALYZE data, each range inequality
105226** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
105227** results in a return of 4 and a range constraint (x>? AND x<?) results
105228** in a return of 16.
105229*/
105230static int whereRangeScanEst(
105231  Parse *pParse,       /* Parsing & code generating context */
105232  Index *p,            /* The index containing the range-compared column; "x" */
105233  int nEq,             /* index into p->aCol[] of the range-compared column */
105234  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
105235  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
105236  double *pRangeDiv   /* OUT: Reduce search space by this divisor */
105237){
105238  int rc = SQLITE_OK;
105239
105240#ifdef SQLITE_ENABLE_STAT3
105241
105242  if( nEq==0 && p->nSample ){
105243    sqlite3_value *pRangeVal;
105244    tRowcnt iLower = 0;
105245    tRowcnt iUpper = p->aiRowEst[0];
105246    tRowcnt a[2];
105247    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
105248
105249    if( pLower ){
105250      Expr *pExpr = pLower->pExpr->pRight;
105251      rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
105252      assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
105253      if( rc==SQLITE_OK
105254       && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
105255      ){
105256        iLower = a[0];
105257        if( pLower->eOperator==WO_GT ) iLower += a[1];
105258      }
105259      sqlite3ValueFree(pRangeVal);
105260    }
105261    if( rc==SQLITE_OK && pUpper ){
105262      Expr *pExpr = pUpper->pExpr->pRight;
105263      rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
105264      assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
105265      if( rc==SQLITE_OK
105266       && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
105267      ){
105268        iUpper = a[0];
105269        if( pUpper->eOperator==WO_LE ) iUpper += a[1];
105270      }
105271      sqlite3ValueFree(pRangeVal);
105272    }
105273    if( rc==SQLITE_OK ){
105274      if( iUpper<=iLower ){
105275        *pRangeDiv = (double)p->aiRowEst[0];
105276      }else{
105277        *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
105278      }
105279      WHERETRACE(("range scan regions: %u..%u  div=%g\n",
105280                  (u32)iLower, (u32)iUpper, *pRangeDiv));
105281      return SQLITE_OK;
105282    }
105283  }
105284#else
105285  UNUSED_PARAMETER(pParse);
105286  UNUSED_PARAMETER(p);
105287  UNUSED_PARAMETER(nEq);
105288#endif
105289  assert( pLower || pUpper );
105290  *pRangeDiv = (double)1;
105291  if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
105292  if( pUpper ) *pRangeDiv *= (double)4;
105293  return rc;
105294}
105295
105296#ifdef SQLITE_ENABLE_STAT3
105297/*
105298** Estimate the number of rows that will be returned based on
105299** an equality constraint x=VALUE and where that VALUE occurs in
105300** the histogram data.  This only works when x is the left-most
105301** column of an index and sqlite_stat3 histogram data is available
105302** for that index.  When pExpr==NULL that means the constraint is
105303** "x IS NULL" instead of "x=VALUE".
105304**
105305** Write the estimated row count into *pnRow and return SQLITE_OK.
105306** If unable to make an estimate, leave *pnRow unchanged and return
105307** non-zero.
105308**
105309** This routine can fail if it is unable to load a collating sequence
105310** required for string comparison, or if unable to allocate memory
105311** for a UTF conversion required for comparison.  The error is stored
105312** in the pParse structure.
105313*/
105314static int whereEqualScanEst(
105315  Parse *pParse,       /* Parsing & code generating context */
105316  Index *p,            /* The index whose left-most column is pTerm */
105317  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
105318  double *pnRow        /* Write the revised row estimate here */
105319){
105320  sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
105321  u8 aff;                   /* Column affinity */
105322  int rc;                   /* Subfunction return code */
105323  tRowcnt a[2];             /* Statistics */
105324
105325  assert( p->aSample!=0 );
105326  assert( p->nSample>0 );
105327  aff = p->pTable->aCol[p->aiColumn[0]].affinity;
105328  if( pExpr ){
105329    rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
105330    if( rc ) goto whereEqualScanEst_cancel;
105331  }else{
105332    pRhs = sqlite3ValueNew(pParse->db);
105333  }
105334  if( pRhs==0 ) return SQLITE_NOTFOUND;
105335  rc = whereKeyStats(pParse, p, pRhs, 0, a);
105336  if( rc==SQLITE_OK ){
105337    WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
105338    *pnRow = a[1];
105339  }
105340whereEqualScanEst_cancel:
105341  sqlite3ValueFree(pRhs);
105342  return rc;
105343}
105344#endif /* defined(SQLITE_ENABLE_STAT3) */
105345
105346#ifdef SQLITE_ENABLE_STAT3
105347/*
105348** Estimate the number of rows that will be returned based on
105349** an IN constraint where the right-hand side of the IN operator
105350** is a list of values.  Example:
105351**
105352**        WHERE x IN (1,2,3,4)
105353**
105354** Write the estimated row count into *pnRow and return SQLITE_OK.
105355** If unable to make an estimate, leave *pnRow unchanged and return
105356** non-zero.
105357**
105358** This routine can fail if it is unable to load a collating sequence
105359** required for string comparison, or if unable to allocate memory
105360** for a UTF conversion required for comparison.  The error is stored
105361** in the pParse structure.
105362*/
105363static int whereInScanEst(
105364  Parse *pParse,       /* Parsing & code generating context */
105365  Index *p,            /* The index whose left-most column is pTerm */
105366  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
105367  double *pnRow        /* Write the revised row estimate here */
105368){
105369  int rc = SQLITE_OK;         /* Subfunction return code */
105370  double nEst;                /* Number of rows for a single term */
105371  double nRowEst = (double)0; /* New estimate of the number of rows */
105372  int i;                      /* Loop counter */
105373
105374  assert( p->aSample!=0 );
105375  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
105376    nEst = p->aiRowEst[0];
105377    rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
105378    nRowEst += nEst;
105379  }
105380  if( rc==SQLITE_OK ){
105381    if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
105382    *pnRow = nRowEst;
105383    WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
105384  }
105385  return rc;
105386}
105387#endif /* defined(SQLITE_ENABLE_STAT3) */
105388
105389
105390/*
105391** Find the best query plan for accessing a particular table.  Write the
105392** best query plan and its cost into the WhereCost object supplied as the
105393** last parameter.
105394**
105395** The lowest cost plan wins.  The cost is an estimate of the amount of
105396** CPU and disk I/O needed to process the requested result.
105397** Factors that influence cost include:
105398**
105399**    *  The estimated number of rows that will be retrieved.  (The
105400**       fewer the better.)
105401**
105402**    *  Whether or not sorting must occur.
105403**
105404**    *  Whether or not there must be separate lookups in the
105405**       index and in the main table.
105406**
105407** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
105408** the SQL statement, then this function only considers plans using the
105409** named index. If no such plan is found, then the returned cost is
105410** SQLITE_BIG_DBL. If a plan is found that uses the named index,
105411** then the cost is calculated in the usual way.
105412**
105413** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
105414** in the SELECT statement, then no indexes are considered. However, the
105415** selected plan may still take advantage of the built-in rowid primary key
105416** index.
105417*/
105418static void bestBtreeIndex(
105419  Parse *pParse,              /* The parsing context */
105420  WhereClause *pWC,           /* The WHERE clause */
105421  struct SrcList_item *pSrc,  /* The FROM clause term to search */
105422  Bitmask notReady,           /* Mask of cursors not available for indexing */
105423  Bitmask notValid,           /* Cursors not available for any purpose */
105424  ExprList *pOrderBy,         /* The ORDER BY clause */
105425  ExprList *pDistinct,        /* The select-list if query is DISTINCT */
105426  WhereCost *pCost            /* Lowest cost query plan */
105427){
105428  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
105429  Index *pProbe;              /* An index we are evaluating */
105430  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
105431  int eqTermMask;             /* Current mask of valid equality operators */
105432  int idxEqTermMask;          /* Index mask of valid equality operators */
105433  Index sPk;                  /* A fake index object for the primary key */
105434  tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
105435  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
105436  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
105437
105438  /* Initialize the cost to a worst-case value */
105439  memset(pCost, 0, sizeof(*pCost));
105440  pCost->rCost = SQLITE_BIG_DBL;
105441
105442  /* If the pSrc table is the right table of a LEFT JOIN then we may not
105443  ** use an index to satisfy IS NULL constraints on that table.  This is
105444  ** because columns might end up being NULL if the table does not match -
105445  ** a circumstance which the index cannot help us discover.  Ticket #2177.
105446  */
105447  if( pSrc->jointype & JT_LEFT ){
105448    idxEqTermMask = WO_EQ|WO_IN;
105449  }else{
105450    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
105451  }
105452
105453  if( pSrc->pIndex ){
105454    /* An INDEXED BY clause specifies a particular index to use */
105455    pIdx = pProbe = pSrc->pIndex;
105456    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
105457    eqTermMask = idxEqTermMask;
105458  }else{
105459    /* There is no INDEXED BY clause.  Create a fake Index object in local
105460    ** variable sPk to represent the rowid primary key index.  Make this
105461    ** fake index the first in a chain of Index objects with all of the real
105462    ** indices to follow */
105463    Index *pFirst;                  /* First of real indices on the table */
105464    memset(&sPk, 0, sizeof(Index));
105465    sPk.nColumn = 1;
105466    sPk.aiColumn = &aiColumnPk;
105467    sPk.aiRowEst = aiRowEstPk;
105468    sPk.onError = OE_Replace;
105469    sPk.pTable = pSrc->pTab;
105470    aiRowEstPk[0] = pSrc->pTab->nRowEst;
105471    aiRowEstPk[1] = 1;
105472    pFirst = pSrc->pTab->pIndex;
105473    if( pSrc->notIndexed==0 ){
105474      /* The real indices of the table are only considered if the
105475      ** NOT INDEXED qualifier is omitted from the FROM clause */
105476      sPk.pNext = pFirst;
105477    }
105478    pProbe = &sPk;
105479    wsFlagMask = ~(
105480        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
105481    );
105482    eqTermMask = WO_EQ|WO_IN;
105483    pIdx = 0;
105484  }
105485
105486  /* Loop over all indices looking for the best one to use
105487  */
105488  for(; pProbe; pIdx=pProbe=pProbe->pNext){
105489    const tRowcnt * const aiRowEst = pProbe->aiRowEst;
105490    double cost;                /* Cost of using pProbe */
105491    double nRow;                /* Estimated number of rows in result set */
105492    double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
105493    int rev;                    /* True to scan in reverse order */
105494    int wsFlags = 0;
105495    Bitmask used = 0;
105496
105497    /* The following variables are populated based on the properties of
105498    ** index being evaluated. They are then used to determine the expected
105499    ** cost and number of rows returned.
105500    **
105501    **  nEq:
105502    **    Number of equality terms that can be implemented using the index.
105503    **    In other words, the number of initial fields in the index that
105504    **    are used in == or IN or NOT NULL constraints of the WHERE clause.
105505    **
105506    **  nInMul:
105507    **    The "in-multiplier". This is an estimate of how many seek operations
105508    **    SQLite must perform on the index in question. For example, if the
105509    **    WHERE clause is:
105510    **
105511    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
105512    **
105513    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
105514    **    set to 9. Given the same schema and either of the following WHERE
105515    **    clauses:
105516    **
105517    **      WHERE a =  1
105518    **      WHERE a >= 2
105519    **
105520    **    nInMul is set to 1.
105521    **
105522    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
105523    **    the sub-select is assumed to return 25 rows for the purposes of
105524    **    determining nInMul.
105525    **
105526    **  bInEst:
105527    **    Set to true if there was at least one "x IN (SELECT ...)" term used
105528    **    in determining the value of nInMul.  Note that the RHS of the
105529    **    IN operator must be a SELECT, not a value list, for this variable
105530    **    to be true.
105531    **
105532    **  rangeDiv:
105533    **    An estimate of a divisor by which to reduce the search space due
105534    **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
105535    **    data, a single inequality reduces the search space to 1/4rd its
105536    **    original size (rangeDiv==4).  Two inequalities reduce the search
105537    **    space to 1/16th of its original size (rangeDiv==16).
105538    **
105539    **  bSort:
105540    **    Boolean. True if there is an ORDER BY clause that will require an
105541    **    external sort (i.e. scanning the index being evaluated will not
105542    **    correctly order records).
105543    **
105544    **  bLookup:
105545    **    Boolean. True if a table lookup is required for each index entry
105546    **    visited.  In other words, true if this is not a covering index.
105547    **    This is always false for the rowid primary key index of a table.
105548    **    For other indexes, it is true unless all the columns of the table
105549    **    used by the SELECT statement are present in the index (such an
105550    **    index is sometimes described as a covering index).
105551    **    For example, given the index on (a, b), the second of the following
105552    **    two queries requires table b-tree lookups in order to find the value
105553    **    of column c, but the first does not because columns a and b are
105554    **    both available in the index.
105555    **
105556    **             SELECT a, b    FROM tbl WHERE a = 1;
105557    **             SELECT a, b, c FROM tbl WHERE a = 1;
105558    */
105559    int nEq;                      /* Number of == or IN terms matching index */
105560    int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
105561    int nInMul = 1;               /* Number of distinct equalities to lookup */
105562    double rangeDiv = (double)1;  /* Estimated reduction in search space */
105563    int nBound = 0;               /* Number of range constraints seen */
105564    int bSort = !!pOrderBy;       /* True if external sort required */
105565    int bDist = !!pDistinct;      /* True if index cannot help with DISTINCT */
105566    int bLookup = 0;              /* True if not a covering index */
105567    WhereTerm *pTerm;             /* A single term of the WHERE clause */
105568#ifdef SQLITE_ENABLE_STAT3
105569    WhereTerm *pFirstTerm = 0;    /* First term matching the index */
105570#endif
105571
105572    /* Determine the values of nEq and nInMul */
105573    for(nEq=0; nEq<pProbe->nColumn; nEq++){
105574      int j = pProbe->aiColumn[nEq];
105575      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
105576      if( pTerm==0 ) break;
105577      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
105578      testcase( pTerm->pWC!=pWC );
105579      if( pTerm->eOperator & WO_IN ){
105580        Expr *pExpr = pTerm->pExpr;
105581        wsFlags |= WHERE_COLUMN_IN;
105582        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
105583          /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
105584          nInMul *= 25;
105585          bInEst = 1;
105586        }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
105587          /* "x IN (value, value, ...)" */
105588          nInMul *= pExpr->x.pList->nExpr;
105589        }
105590      }else if( pTerm->eOperator & WO_ISNULL ){
105591        wsFlags |= WHERE_COLUMN_NULL;
105592      }
105593#ifdef SQLITE_ENABLE_STAT3
105594      if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
105595#endif
105596      used |= pTerm->prereqRight;
105597    }
105598
105599    /* If the index being considered is UNIQUE, and there is an equality
105600    ** constraint for all columns in the index, then this search will find
105601    ** at most a single row. In this case set the WHERE_UNIQUE flag to
105602    ** indicate this to the caller.
105603    **
105604    ** Otherwise, if the search may find more than one row, test to see if
105605    ** there is a range constraint on indexed column (nEq+1) that can be
105606    ** optimized using the index.
105607    */
105608    if( nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
105609      testcase( wsFlags & WHERE_COLUMN_IN );
105610      testcase( wsFlags & WHERE_COLUMN_NULL );
105611      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
105612        wsFlags |= WHERE_UNIQUE;
105613      }
105614    }else if( pProbe->bUnordered==0 ){
105615      int j = (nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[nEq]);
105616      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
105617        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
105618        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
105619        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &rangeDiv);
105620        if( pTop ){
105621          nBound = 1;
105622          wsFlags |= WHERE_TOP_LIMIT;
105623          used |= pTop->prereqRight;
105624          testcase( pTop->pWC!=pWC );
105625        }
105626        if( pBtm ){
105627          nBound++;
105628          wsFlags |= WHERE_BTM_LIMIT;
105629          used |= pBtm->prereqRight;
105630          testcase( pBtm->pWC!=pWC );
105631        }
105632        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
105633      }
105634    }
105635
105636    /* If there is an ORDER BY clause and the index being considered will
105637    ** naturally scan rows in the required order, set the appropriate flags
105638    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
105639    ** will scan rows in a different order, set the bSort variable.  */
105640    if( isSortingIndex(
105641          pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy, nEq, wsFlags, &rev)
105642    ){
105643      bSort = 0;
105644      wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
105645      wsFlags |= (rev ? WHERE_REVERSE : 0);
105646    }
105647
105648    /* If there is a DISTINCT qualifier and this index will scan rows in
105649    ** order of the DISTINCT expressions, clear bDist and set the appropriate
105650    ** flags in wsFlags. */
105651    if( isDistinctIndex(pParse, pWC, pProbe, iCur, pDistinct, nEq)
105652     && (wsFlags & WHERE_COLUMN_IN)==0
105653    ){
105654      bDist = 0;
105655      wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
105656    }
105657
105658    /* If currently calculating the cost of using an index (not the IPK
105659    ** index), determine if all required column data may be obtained without
105660    ** using the main table (i.e. if the index is a covering
105661    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
105662    ** wsFlags. Otherwise, set the bLookup variable to true.  */
105663    if( pIdx && wsFlags ){
105664      Bitmask m = pSrc->colUsed;
105665      int j;
105666      for(j=0; j<pIdx->nColumn; j++){
105667        int x = pIdx->aiColumn[j];
105668        if( x<BMS-1 ){
105669          m &= ~(((Bitmask)1)<<x);
105670        }
105671      }
105672      if( m==0 ){
105673        wsFlags |= WHERE_IDX_ONLY;
105674      }else{
105675        bLookup = 1;
105676      }
105677    }
105678
105679    /*
105680    ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
105681    ** constraint, do not let the estimate exceed half the rows in the table.
105682    */
105683    nRow = (double)(aiRowEst[nEq] * nInMul);
105684    if( bInEst && nRow*2>aiRowEst[0] ){
105685      nRow = aiRowEst[0]/2;
105686      nInMul = (int)(nRow / aiRowEst[nEq]);
105687    }
105688
105689#ifdef SQLITE_ENABLE_STAT3
105690    /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
105691    ** and we do not think that values of x are unique and if histogram
105692    ** data is available for column x, then it might be possible
105693    ** to get a better estimate on the number of rows based on
105694    ** VALUE and how common that value is according to the histogram.
105695    */
105696    if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 && aiRowEst[1]>1 ){
105697      assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
105698      if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
105699        testcase( pFirstTerm->eOperator==WO_EQ );
105700        testcase( pFirstTerm->eOperator==WO_ISNULL );
105701        whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
105702      }else if( bInEst==0 ){
105703        assert( pFirstTerm->eOperator==WO_IN );
105704        whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
105705      }
105706    }
105707#endif /* SQLITE_ENABLE_STAT3 */
105708
105709    /* Adjust the number of output rows and downward to reflect rows
105710    ** that are excluded by range constraints.
105711    */
105712    nRow = nRow/rangeDiv;
105713    if( nRow<1 ) nRow = 1;
105714
105715    /* Experiments run on real SQLite databases show that the time needed
105716    ** to do a binary search to locate a row in a table or index is roughly
105717    ** log10(N) times the time to move from one row to the next row within
105718    ** a table or index.  The actual times can vary, with the size of
105719    ** records being an important factor.  Both moves and searches are
105720    ** slower with larger records, presumably because fewer records fit
105721    ** on one page and hence more pages have to be fetched.
105722    **
105723    ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
105724    ** not give us data on the relative sizes of table and index records.
105725    ** So this computation assumes table records are about twice as big
105726    ** as index records
105727    */
105728    if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
105729      /* The cost of a full table scan is a number of move operations equal
105730      ** to the number of rows in the table.
105731      **
105732      ** We add an additional 4x penalty to full table scans.  This causes
105733      ** the cost function to err on the side of choosing an index over
105734      ** choosing a full scan.  This 4x full-scan penalty is an arguable
105735      ** decision and one which we expect to revisit in the future.  But
105736      ** it seems to be working well enough at the moment.
105737      */
105738      cost = aiRowEst[0]*4;
105739    }else{
105740      log10N = estLog(aiRowEst[0]);
105741      cost = nRow;
105742      if( pIdx ){
105743        if( bLookup ){
105744          /* For an index lookup followed by a table lookup:
105745          **    nInMul index searches to find the start of each index range
105746          **  + nRow steps through the index
105747          **  + nRow table searches to lookup the table entry using the rowid
105748          */
105749          cost += (nInMul + nRow)*log10N;
105750        }else{
105751          /* For a covering index:
105752          **     nInMul index searches to find the initial entry
105753          **   + nRow steps through the index
105754          */
105755          cost += nInMul*log10N;
105756        }
105757      }else{
105758        /* For a rowid primary key lookup:
105759        **    nInMult table searches to find the initial entry for each range
105760        **  + nRow steps through the table
105761        */
105762        cost += nInMul*log10N;
105763      }
105764    }
105765
105766    /* Add in the estimated cost of sorting the result.  Actual experimental
105767    ** measurements of sorting performance in SQLite show that sorting time
105768    ** adds C*N*log10(N) to the cost, where N is the number of rows to be
105769    ** sorted and C is a factor between 1.95 and 4.3.  We will split the
105770    ** difference and select C of 3.0.
105771    */
105772    if( bSort ){
105773      cost += nRow*estLog(nRow)*3;
105774    }
105775    if( bDist ){
105776      cost += nRow*estLog(nRow)*3;
105777    }
105778
105779    /**** Cost of using this index has now been computed ****/
105780
105781    /* If there are additional constraints on this table that cannot
105782    ** be used with the current index, but which might lower the number
105783    ** of output rows, adjust the nRow value accordingly.  This only
105784    ** matters if the current index is the least costly, so do not bother
105785    ** with this step if we already know this index will not be chosen.
105786    ** Also, never reduce the output row count below 2 using this step.
105787    **
105788    ** It is critical that the notValid mask be used here instead of
105789    ** the notReady mask.  When computing an "optimal" index, the notReady
105790    ** mask will only have one bit set - the bit for the current table.
105791    ** The notValid mask, on the other hand, always has all bits set for
105792    ** tables that are not in outer loops.  If notReady is used here instead
105793    ** of notValid, then a optimal index that depends on inner joins loops
105794    ** might be selected even when there exists an optimal index that has
105795    ** no such dependency.
105796    */
105797    if( nRow>2 && cost<=pCost->rCost ){
105798      int k;                       /* Loop counter */
105799      int nSkipEq = nEq;           /* Number of == constraints to skip */
105800      int nSkipRange = nBound;     /* Number of < constraints to skip */
105801      Bitmask thisTab;             /* Bitmap for pSrc */
105802
105803      thisTab = getMask(pWC->pMaskSet, iCur);
105804      for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
105805        if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
105806        if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
105807        if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
105808          if( nSkipEq ){
105809            /* Ignore the first nEq equality matches since the index
105810            ** has already accounted for these */
105811            nSkipEq--;
105812          }else{
105813            /* Assume each additional equality match reduces the result
105814            ** set size by a factor of 10 */
105815            nRow /= 10;
105816          }
105817        }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
105818          if( nSkipRange ){
105819            /* Ignore the first nSkipRange range constraints since the index
105820            ** has already accounted for these */
105821            nSkipRange--;
105822          }else{
105823            /* Assume each additional range constraint reduces the result
105824            ** set size by a factor of 3.  Indexed range constraints reduce
105825            ** the search space by a larger factor: 4.  We make indexed range
105826            ** more selective intentionally because of the subjective
105827            ** observation that indexed range constraints really are more
105828            ** selective in practice, on average. */
105829            nRow /= 3;
105830          }
105831        }else if( pTerm->eOperator!=WO_NOOP ){
105832          /* Any other expression lowers the output row count by half */
105833          nRow /= 2;
105834        }
105835      }
105836      if( nRow<2 ) nRow = 2;
105837    }
105838
105839
105840    WHERETRACE((
105841      "%s(%s): nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
105842      "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
105843      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
105844      nEq, nInMul, (int)rangeDiv, bSort, bLookup, wsFlags,
105845      notReady, log10N, nRow, cost, used
105846    ));
105847
105848    /* If this index is the best we have seen so far, then record this
105849    ** index and its cost in the pCost structure.
105850    */
105851    if( (!pIdx || wsFlags)
105852     && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
105853    ){
105854      pCost->rCost = cost;
105855      pCost->used = used;
105856      pCost->plan.nRow = nRow;
105857      pCost->plan.wsFlags = (wsFlags&wsFlagMask);
105858      pCost->plan.nEq = nEq;
105859      pCost->plan.u.pIdx = pIdx;
105860    }
105861
105862    /* If there was an INDEXED BY clause, then only that one index is
105863    ** considered. */
105864    if( pSrc->pIndex ) break;
105865
105866    /* Reset masks for the next index in the loop */
105867    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
105868    eqTermMask = idxEqTermMask;
105869  }
105870
105871  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
105872  ** is set, then reverse the order that the index will be scanned
105873  ** in. This is used for application testing, to help find cases
105874  ** where application behaviour depends on the (undefined) order that
105875  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
105876  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
105877    pCost->plan.wsFlags |= WHERE_REVERSE;
105878  }
105879
105880  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
105881  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
105882  assert( pSrc->pIndex==0
105883       || pCost->plan.u.pIdx==0
105884       || pCost->plan.u.pIdx==pSrc->pIndex
105885  );
105886
105887  WHERETRACE(("best index is: %s\n",
105888    ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
105889         pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
105890  ));
105891
105892  bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
105893  bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
105894  pCost->plan.wsFlags |= eqTermMask;
105895}
105896
105897/*
105898** Find the query plan for accessing table pSrc->pTab. Write the
105899** best query plan and its cost into the WhereCost object supplied
105900** as the last parameter. This function may calculate the cost of
105901** both real and virtual table scans.
105902*/
105903static void bestIndex(
105904  Parse *pParse,              /* The parsing context */
105905  WhereClause *pWC,           /* The WHERE clause */
105906  struct SrcList_item *pSrc,  /* The FROM clause term to search */
105907  Bitmask notReady,           /* Mask of cursors not available for indexing */
105908  Bitmask notValid,           /* Cursors not available for any purpose */
105909  ExprList *pOrderBy,         /* The ORDER BY clause */
105910  WhereCost *pCost            /* Lowest cost query plan */
105911){
105912#ifndef SQLITE_OMIT_VIRTUALTABLE
105913  if( IsVirtual(pSrc->pTab) ){
105914    sqlite3_index_info *p = 0;
105915    bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
105916    if( p->needToFreeIdxStr ){
105917      sqlite3_free(p->idxStr);
105918    }
105919    sqlite3DbFree(pParse->db, p);
105920  }else
105921#endif
105922  {
105923    bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, 0, pCost);
105924  }
105925}
105926
105927/*
105928** Disable a term in the WHERE clause.  Except, do not disable the term
105929** if it controls a LEFT OUTER JOIN and it did not originate in the ON
105930** or USING clause of that join.
105931**
105932** Consider the term t2.z='ok' in the following queries:
105933**
105934**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
105935**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
105936**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
105937**
105938** The t2.z='ok' is disabled in the in (2) because it originates
105939** in the ON clause.  The term is disabled in (3) because it is not part
105940** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
105941**
105942** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
105943** completely satisfied by indices.
105944**
105945** Disabling a term causes that term to not be tested in the inner loop
105946** of the join.  Disabling is an optimization.  When terms are satisfied
105947** by indices, we disable them to prevent redundant tests in the inner
105948** loop.  We would get the correct results if nothing were ever disabled,
105949** but joins might run a little slower.  The trick is to disable as much
105950** as we can without disabling too much.  If we disabled in (1), we'd get
105951** the wrong answer.  See ticket #813.
105952*/
105953static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
105954  if( pTerm
105955      && (pTerm->wtFlags & TERM_CODED)==0
105956      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
105957  ){
105958    pTerm->wtFlags |= TERM_CODED;
105959    if( pTerm->iParent>=0 ){
105960      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
105961      if( (--pOther->nChild)==0 ){
105962        disableTerm(pLevel, pOther);
105963      }
105964    }
105965  }
105966}
105967
105968/*
105969** Code an OP_Affinity opcode to apply the column affinity string zAff
105970** to the n registers starting at base.
105971**
105972** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
105973** beginning and end of zAff are ignored.  If all entries in zAff are
105974** SQLITE_AFF_NONE, then no code gets generated.
105975**
105976** This routine makes its own copy of zAff so that the caller is free
105977** to modify zAff after this routine returns.
105978*/
105979static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
105980  Vdbe *v = pParse->pVdbe;
105981  if( zAff==0 ){
105982    assert( pParse->db->mallocFailed );
105983    return;
105984  }
105985  assert( v!=0 );
105986
105987  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
105988  ** and end of the affinity string.
105989  */
105990  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
105991    n--;
105992    base++;
105993    zAff++;
105994  }
105995  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
105996    n--;
105997  }
105998
105999  /* Code the OP_Affinity opcode if there is anything left to do. */
106000  if( n>0 ){
106001    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
106002    sqlite3VdbeChangeP4(v, -1, zAff, n);
106003    sqlite3ExprCacheAffinityChange(pParse, base, n);
106004  }
106005}
106006
106007
106008/*
106009** Generate code for a single equality term of the WHERE clause.  An equality
106010** term can be either X=expr or X IN (...).   pTerm is the term to be
106011** coded.
106012**
106013** The current value for the constraint is left in register iReg.
106014**
106015** For a constraint of the form X=expr, the expression is evaluated and its
106016** result is left on the stack.  For constraints of the form X IN (...)
106017** this routine sets up a loop that will iterate over all values of X.
106018*/
106019static int codeEqualityTerm(
106020  Parse *pParse,      /* The parsing context */
106021  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
106022  WhereLevel *pLevel, /* When level of the FROM clause we are working on */
106023  int iTarget         /* Attempt to leave results in this register */
106024){
106025  Expr *pX = pTerm->pExpr;
106026  Vdbe *v = pParse->pVdbe;
106027  int iReg;                  /* Register holding results */
106028
106029  assert( iTarget>0 );
106030  if( pX->op==TK_EQ ){
106031    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
106032  }else if( pX->op==TK_ISNULL ){
106033    iReg = iTarget;
106034    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
106035#ifndef SQLITE_OMIT_SUBQUERY
106036  }else{
106037    int eType;
106038    int iTab;
106039    struct InLoop *pIn;
106040
106041    assert( pX->op==TK_IN );
106042    iReg = iTarget;
106043    eType = sqlite3FindInIndex(pParse, pX, 0);
106044    iTab = pX->iTable;
106045    sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
106046    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
106047    if( pLevel->u.in.nIn==0 ){
106048      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
106049    }
106050    pLevel->u.in.nIn++;
106051    pLevel->u.in.aInLoop =
106052       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
106053                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
106054    pIn = pLevel->u.in.aInLoop;
106055    if( pIn ){
106056      pIn += pLevel->u.in.nIn - 1;
106057      pIn->iCur = iTab;
106058      if( eType==IN_INDEX_ROWID ){
106059        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
106060      }else{
106061        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
106062      }
106063      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
106064    }else{
106065      pLevel->u.in.nIn = 0;
106066    }
106067#endif
106068  }
106069  disableTerm(pLevel, pTerm);
106070  return iReg;
106071}
106072
106073/*
106074** Generate code that will evaluate all == and IN constraints for an
106075** index.
106076**
106077** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
106078** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
106079** The index has as many as three equality constraints, but in this
106080** example, the third "c" value is an inequality.  So only two
106081** constraints are coded.  This routine will generate code to evaluate
106082** a==5 and b IN (1,2,3).  The current values for a and b will be stored
106083** in consecutive registers and the index of the first register is returned.
106084**
106085** In the example above nEq==2.  But this subroutine works for any value
106086** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
106087** The only thing it does is allocate the pLevel->iMem memory cell and
106088** compute the affinity string.
106089**
106090** This routine always allocates at least one memory cell and returns
106091** the index of that memory cell. The code that
106092** calls this routine will use that memory cell to store the termination
106093** key value of the loop.  If one or more IN operators appear, then
106094** this routine allocates an additional nEq memory cells for internal
106095** use.
106096**
106097** Before returning, *pzAff is set to point to a buffer containing a
106098** copy of the column affinity string of the index allocated using
106099** sqlite3DbMalloc(). Except, entries in the copy of the string associated
106100** with equality constraints that use NONE affinity are set to
106101** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
106102**
106103**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
106104**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
106105**
106106** In the example above, the index on t1(a) has TEXT affinity. But since
106107** the right hand side of the equality constraint (t2.b) has NONE affinity,
106108** no conversion should be attempted before using a t2.b value as part of
106109** a key to search the index. Hence the first byte in the returned affinity
106110** string in this example would be set to SQLITE_AFF_NONE.
106111*/
106112static int codeAllEqualityTerms(
106113  Parse *pParse,        /* Parsing context */
106114  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
106115  WhereClause *pWC,     /* The WHERE clause */
106116  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
106117  int nExtraReg,        /* Number of extra registers to allocate */
106118  char **pzAff          /* OUT: Set to point to affinity string */
106119){
106120  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
106121  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
106122  Index *pIdx;                  /* The index being used for this loop */
106123  int iCur = pLevel->iTabCur;   /* The cursor of the table */
106124  WhereTerm *pTerm;             /* A single constraint term */
106125  int j;                        /* Loop counter */
106126  int regBase;                  /* Base register */
106127  int nReg;                     /* Number of registers to allocate */
106128  char *zAff;                   /* Affinity string to return */
106129
106130  /* This module is only called on query plans that use an index. */
106131  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
106132  pIdx = pLevel->plan.u.pIdx;
106133
106134  /* Figure out how many memory cells we will need then allocate them.
106135  */
106136  regBase = pParse->nMem + 1;
106137  nReg = pLevel->plan.nEq + nExtraReg;
106138  pParse->nMem += nReg;
106139
106140  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
106141  if( !zAff ){
106142    pParse->db->mallocFailed = 1;
106143  }
106144
106145  /* Evaluate the equality constraints
106146  */
106147  assert( pIdx->nColumn>=nEq );
106148  for(j=0; j<nEq; j++){
106149    int r1;
106150    int k = pIdx->aiColumn[j];
106151    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
106152    if( NEVER(pTerm==0) ) break;
106153    /* The following true for indices with redundant columns.
106154    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
106155    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
106156    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106157    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
106158    if( r1!=regBase+j ){
106159      if( nReg==1 ){
106160        sqlite3ReleaseTempReg(pParse, regBase);
106161        regBase = r1;
106162      }else{
106163        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
106164      }
106165    }
106166    testcase( pTerm->eOperator & WO_ISNULL );
106167    testcase( pTerm->eOperator & WO_IN );
106168    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
106169      Expr *pRight = pTerm->pExpr->pRight;
106170      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
106171      if( zAff ){
106172        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
106173          zAff[j] = SQLITE_AFF_NONE;
106174        }
106175        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
106176          zAff[j] = SQLITE_AFF_NONE;
106177        }
106178      }
106179    }
106180  }
106181  *pzAff = zAff;
106182  return regBase;
106183}
106184
106185#ifndef SQLITE_OMIT_EXPLAIN
106186/*
106187** This routine is a helper for explainIndexRange() below
106188**
106189** pStr holds the text of an expression that we are building up one term
106190** at a time.  This routine adds a new term to the end of the expression.
106191** Terms are separated by AND so add the "AND" text for second and subsequent
106192** terms only.
106193*/
106194static void explainAppendTerm(
106195  StrAccum *pStr,             /* The text expression being built */
106196  int iTerm,                  /* Index of this term.  First is zero */
106197  const char *zColumn,        /* Name of the column */
106198  const char *zOp             /* Name of the operator */
106199){
106200  if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
106201  sqlite3StrAccumAppend(pStr, zColumn, -1);
106202  sqlite3StrAccumAppend(pStr, zOp, 1);
106203  sqlite3StrAccumAppend(pStr, "?", 1);
106204}
106205
106206/*
106207** Argument pLevel describes a strategy for scanning table pTab. This
106208** function returns a pointer to a string buffer containing a description
106209** of the subset of table rows scanned by the strategy in the form of an
106210** SQL expression. Or, if all rows are scanned, NULL is returned.
106211**
106212** For example, if the query:
106213**
106214**   SELECT * FROM t1 WHERE a=1 AND b>2;
106215**
106216** is run and there is an index on (a, b), then this function returns a
106217** string similar to:
106218**
106219**   "a=? AND b>?"
106220**
106221** The returned pointer points to memory obtained from sqlite3DbMalloc().
106222** It is the responsibility of the caller to free the buffer when it is
106223** no longer required.
106224*/
106225static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
106226  WherePlan *pPlan = &pLevel->plan;
106227  Index *pIndex = pPlan->u.pIdx;
106228  int nEq = pPlan->nEq;
106229  int i, j;
106230  Column *aCol = pTab->aCol;
106231  int *aiColumn = pIndex->aiColumn;
106232  StrAccum txt;
106233
106234  if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
106235    return 0;
106236  }
106237  sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
106238  txt.db = db;
106239  sqlite3StrAccumAppend(&txt, " (", 2);
106240  for(i=0; i<nEq; i++){
106241    explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
106242  }
106243
106244  j = i;
106245  if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
106246    char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
106247    explainAppendTerm(&txt, i++, z, ">");
106248  }
106249  if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
106250    char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
106251    explainAppendTerm(&txt, i, z, "<");
106252  }
106253  sqlite3StrAccumAppend(&txt, ")", 1);
106254  return sqlite3StrAccumFinish(&txt);
106255}
106256
106257/*
106258** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
106259** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
106260** record is added to the output to describe the table scan strategy in
106261** pLevel.
106262*/
106263static void explainOneScan(
106264  Parse *pParse,                  /* Parse context */
106265  SrcList *pTabList,              /* Table list this loop refers to */
106266  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
106267  int iLevel,                     /* Value for "level" column of output */
106268  int iFrom,                      /* Value for "from" column of output */
106269  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
106270){
106271  if( pParse->explain==2 ){
106272    u32 flags = pLevel->plan.wsFlags;
106273    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
106274    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
106275    sqlite3 *db = pParse->db;     /* Database handle */
106276    char *zMsg;                   /* Text to add to EQP output */
106277    sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
106278    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
106279    int isSearch;                 /* True for a SEARCH. False for SCAN. */
106280
106281    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
106282
106283    isSearch = (pLevel->plan.nEq>0)
106284             || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
106285             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
106286
106287    zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
106288    if( pItem->pSelect ){
106289      zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
106290    }else{
106291      zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
106292    }
106293
106294    if( pItem->zAlias ){
106295      zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
106296    }
106297    if( (flags & WHERE_INDEXED)!=0 ){
106298      char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
106299      zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
106300          ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
106301          ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
106302          ((flags & WHERE_TEMP_INDEX)?"":" "),
106303          ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
106304          zWhere
106305      );
106306      sqlite3DbFree(db, zWhere);
106307    }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
106308      zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
106309
106310      if( flags&WHERE_ROWID_EQ ){
106311        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
106312      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
106313        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
106314      }else if( flags&WHERE_BTM_LIMIT ){
106315        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
106316      }else if( flags&WHERE_TOP_LIMIT ){
106317        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
106318      }
106319    }
106320#ifndef SQLITE_OMIT_VIRTUALTABLE
106321    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
106322      sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
106323      zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
106324                  pVtabIdx->idxNum, pVtabIdx->idxStr);
106325    }
106326#endif
106327    if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
106328      testcase( wctrlFlags & WHERE_ORDERBY_MIN );
106329      nRow = 1;
106330    }else{
106331      nRow = (sqlite3_int64)pLevel->plan.nRow;
106332    }
106333    zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
106334    sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
106335  }
106336}
106337#else
106338# define explainOneScan(u,v,w,x,y,z)
106339#endif /* SQLITE_OMIT_EXPLAIN */
106340
106341
106342/*
106343** Generate code for the start of the iLevel-th loop in the WHERE clause
106344** implementation described by pWInfo.
106345*/
106346static Bitmask codeOneLoopStart(
106347  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
106348  int iLevel,          /* Which level of pWInfo->a[] should be coded */
106349  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
106350  Bitmask notReady     /* Which tables are currently available */
106351){
106352  int j, k;            /* Loop counters */
106353  int iCur;            /* The VDBE cursor for the table */
106354  int addrNxt;         /* Where to jump to continue with the next IN case */
106355  int omitTable;       /* True if we use the index only */
106356  int bRev;            /* True if we need to scan in reverse order */
106357  WhereLevel *pLevel;  /* The where level to be coded */
106358  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
106359  WhereTerm *pTerm;               /* A WHERE clause term */
106360  Parse *pParse;                  /* Parsing context */
106361  Vdbe *v;                        /* The prepared stmt under constructions */
106362  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
106363  int addrBrk;                    /* Jump here to break out of the loop */
106364  int addrCont;                   /* Jump here to continue with next cycle */
106365  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
106366  int iReleaseReg = 0;      /* Temp register to free before returning */
106367
106368  pParse = pWInfo->pParse;
106369  v = pParse->pVdbe;
106370  pWC = pWInfo->pWC;
106371  pLevel = &pWInfo->a[iLevel];
106372  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
106373  iCur = pTabItem->iCursor;
106374  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
106375  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
106376           && (wctrlFlags & WHERE_FORCE_TABLE)==0;
106377
106378  /* Create labels for the "break" and "continue" instructions
106379  ** for the current loop.  Jump to addrBrk to break out of a loop.
106380  ** Jump to cont to go immediately to the next iteration of the
106381  ** loop.
106382  **
106383  ** When there is an IN operator, we also have a "addrNxt" label that
106384  ** means to continue with the next IN value combination.  When
106385  ** there are no IN operators in the constraints, the "addrNxt" label
106386  ** is the same as "addrBrk".
106387  */
106388  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
106389  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
106390
106391  /* If this is the right table of a LEFT OUTER JOIN, allocate and
106392  ** initialize a memory cell that records if this table matches any
106393  ** row of the left table of the join.
106394  */
106395  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
106396    pLevel->iLeftJoin = ++pParse->nMem;
106397    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
106398    VdbeComment((v, "init LEFT JOIN no-match flag"));
106399  }
106400
106401#ifndef SQLITE_OMIT_VIRTUALTABLE
106402  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
106403    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
106404    **          to access the data.
106405    */
106406    int iReg;   /* P3 Value for OP_VFilter */
106407    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
106408    int nConstraint = pVtabIdx->nConstraint;
106409    struct sqlite3_index_constraint_usage *aUsage =
106410                                                pVtabIdx->aConstraintUsage;
106411    const struct sqlite3_index_constraint *aConstraint =
106412                                                pVtabIdx->aConstraint;
106413
106414    sqlite3ExprCachePush(pParse);
106415    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
106416    for(j=1; j<=nConstraint; j++){
106417      for(k=0; k<nConstraint; k++){
106418        if( aUsage[k].argvIndex==j ){
106419          int iTerm = aConstraint[k].iTermOffset;
106420          sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
106421          break;
106422        }
106423      }
106424      if( k==nConstraint ) break;
106425    }
106426    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
106427    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
106428    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
106429                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
106430    pVtabIdx->needToFreeIdxStr = 0;
106431    for(j=0; j<nConstraint; j++){
106432      if( aUsage[j].omit ){
106433        int iTerm = aConstraint[j].iTermOffset;
106434        disableTerm(pLevel, &pWC->a[iTerm]);
106435      }
106436    }
106437    pLevel->op = OP_VNext;
106438    pLevel->p1 = iCur;
106439    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
106440    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
106441    sqlite3ExprCachePop(pParse, 1);
106442  }else
106443#endif /* SQLITE_OMIT_VIRTUALTABLE */
106444
106445  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
106446    /* Case 1:  We can directly reference a single row using an
106447    **          equality comparison against the ROWID field.  Or
106448    **          we reference multiple rows using a "rowid IN (...)"
106449    **          construct.
106450    */
106451    iReleaseReg = sqlite3GetTempReg(pParse);
106452    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
106453    assert( pTerm!=0 );
106454    assert( pTerm->pExpr!=0 );
106455    assert( pTerm->leftCursor==iCur );
106456    assert( omitTable==0 );
106457    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106458    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
106459    addrNxt = pLevel->addrNxt;
106460    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
106461    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
106462    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106463    VdbeComment((v, "pk"));
106464    pLevel->op = OP_Noop;
106465  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
106466    /* Case 2:  We have an inequality comparison against the ROWID field.
106467    */
106468    int testOp = OP_Noop;
106469    int start;
106470    int memEndValue = 0;
106471    WhereTerm *pStart, *pEnd;
106472
106473    assert( omitTable==0 );
106474    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
106475    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
106476    if( bRev ){
106477      pTerm = pStart;
106478      pStart = pEnd;
106479      pEnd = pTerm;
106480    }
106481    if( pStart ){
106482      Expr *pX;             /* The expression that defines the start bound */
106483      int r1, rTemp;        /* Registers for holding the start boundary */
106484
106485      /* The following constant maps TK_xx codes into corresponding
106486      ** seek opcodes.  It depends on a particular ordering of TK_xx
106487      */
106488      const u8 aMoveOp[] = {
106489           /* TK_GT */  OP_SeekGt,
106490           /* TK_LE */  OP_SeekLe,
106491           /* TK_LT */  OP_SeekLt,
106492           /* TK_GE */  OP_SeekGe
106493      };
106494      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
106495      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
106496      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
106497
106498      testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106499      pX = pStart->pExpr;
106500      assert( pX!=0 );
106501      assert( pStart->leftCursor==iCur );
106502      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
106503      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
106504      VdbeComment((v, "pk"));
106505      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
106506      sqlite3ReleaseTempReg(pParse, rTemp);
106507      disableTerm(pLevel, pStart);
106508    }else{
106509      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
106510    }
106511    if( pEnd ){
106512      Expr *pX;
106513      pX = pEnd->pExpr;
106514      assert( pX!=0 );
106515      assert( pEnd->leftCursor==iCur );
106516      testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106517      memEndValue = ++pParse->nMem;
106518      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
106519      if( pX->op==TK_LT || pX->op==TK_GT ){
106520        testOp = bRev ? OP_Le : OP_Ge;
106521      }else{
106522        testOp = bRev ? OP_Lt : OP_Gt;
106523      }
106524      disableTerm(pLevel, pEnd);
106525    }
106526    start = sqlite3VdbeCurrentAddr(v);
106527    pLevel->op = bRev ? OP_Prev : OP_Next;
106528    pLevel->p1 = iCur;
106529    pLevel->p2 = start;
106530    if( pStart==0 && pEnd==0 ){
106531      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
106532    }else{
106533      assert( pLevel->p5==0 );
106534    }
106535    if( testOp!=OP_Noop ){
106536      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
106537      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
106538      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106539      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
106540      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
106541    }
106542  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
106543    /* Case 3: A scan using an index.
106544    **
106545    **         The WHERE clause may contain zero or more equality
106546    **         terms ("==" or "IN" operators) that refer to the N
106547    **         left-most columns of the index. It may also contain
106548    **         inequality constraints (>, <, >= or <=) on the indexed
106549    **         column that immediately follows the N equalities. Only
106550    **         the right-most column can be an inequality - the rest must
106551    **         use the "==" and "IN" operators. For example, if the
106552    **         index is on (x,y,z), then the following clauses are all
106553    **         optimized:
106554    **
106555    **            x=5
106556    **            x=5 AND y=10
106557    **            x=5 AND y<10
106558    **            x=5 AND y>5 AND y<10
106559    **            x=5 AND y=5 AND z<=10
106560    **
106561    **         The z<10 term of the following cannot be used, only
106562    **         the x=5 term:
106563    **
106564    **            x=5 AND z<10
106565    **
106566    **         N may be zero if there are inequality constraints.
106567    **         If there are no inequality constraints, then N is at
106568    **         least one.
106569    **
106570    **         This case is also used when there are no WHERE clause
106571    **         constraints but an index is selected anyway, in order
106572    **         to force the output order to conform to an ORDER BY.
106573    */
106574    static const u8 aStartOp[] = {
106575      0,
106576      0,
106577      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
106578      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
106579      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
106580      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
106581      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
106582      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
106583    };
106584    static const u8 aEndOp[] = {
106585      OP_Noop,             /* 0: (!end_constraints) */
106586      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
106587      OP_IdxLT             /* 2: (end_constraints && bRev) */
106588    };
106589    int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
106590    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
106591    int regBase;                 /* Base register holding constraint values */
106592    int r1;                      /* Temp register */
106593    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
106594    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
106595    int startEq;                 /* True if range start uses ==, >= or <= */
106596    int endEq;                   /* True if range end uses ==, >= or <= */
106597    int start_constraints;       /* Start of range is constrained */
106598    int nConstraint;             /* Number of constraint terms */
106599    Index *pIdx;                 /* The index we will be using */
106600    int iIdxCur;                 /* The VDBE cursor for the index */
106601    int nExtraReg = 0;           /* Number of extra registers needed */
106602    int op;                      /* Instruction opcode */
106603    char *zStartAff;             /* Affinity for start of range constraint */
106604    char *zEndAff;               /* Affinity for end of range constraint */
106605
106606    pIdx = pLevel->plan.u.pIdx;
106607    iIdxCur = pLevel->iIdxCur;
106608    k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
106609
106610    /* If this loop satisfies a sort order (pOrderBy) request that
106611    ** was passed to this function to implement a "SELECT min(x) ..."
106612    ** query, then the caller will only allow the loop to run for
106613    ** a single iteration. This means that the first row returned
106614    ** should not have a NULL value stored in 'x'. If column 'x' is
106615    ** the first one after the nEq equality constraints in the index,
106616    ** this requires some special handling.
106617    */
106618    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
106619     && (pLevel->plan.wsFlags&WHERE_ORDERBY)
106620     && (pIdx->nColumn>nEq)
106621    ){
106622      /* assert( pOrderBy->nExpr==1 ); */
106623      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
106624      isMinQuery = 1;
106625      nExtraReg = 1;
106626    }
106627
106628    /* Find any inequality constraint terms for the start and end
106629    ** of the range.
106630    */
106631    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
106632      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
106633      nExtraReg = 1;
106634    }
106635    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
106636      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
106637      nExtraReg = 1;
106638    }
106639
106640    /* Generate code to evaluate all constraint terms using == or IN
106641    ** and store the values of those terms in an array of registers
106642    ** starting at regBase.
106643    */
106644    regBase = codeAllEqualityTerms(
106645        pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
106646    );
106647    zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
106648    addrNxt = pLevel->addrNxt;
106649
106650    /* If we are doing a reverse order scan on an ascending index, or
106651    ** a forward order scan on a descending index, interchange the
106652    ** start and end terms (pRangeStart and pRangeEnd).
106653    */
106654    if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
106655     || (bRev && pIdx->nColumn==nEq)
106656    ){
106657      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
106658    }
106659
106660    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
106661    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
106662    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
106663    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
106664    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
106665    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
106666    start_constraints = pRangeStart || nEq>0;
106667
106668    /* Seek the index cursor to the start of the range. */
106669    nConstraint = nEq;
106670    if( pRangeStart ){
106671      Expr *pRight = pRangeStart->pExpr->pRight;
106672      sqlite3ExprCode(pParse, pRight, regBase+nEq);
106673      if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
106674        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
106675      }
106676      if( zStartAff ){
106677        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
106678          /* Since the comparison is to be performed with no conversions
106679          ** applied to the operands, set the affinity to apply to pRight to
106680          ** SQLITE_AFF_NONE.  */
106681          zStartAff[nEq] = SQLITE_AFF_NONE;
106682        }
106683        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
106684          zStartAff[nEq] = SQLITE_AFF_NONE;
106685        }
106686      }
106687      nConstraint++;
106688      testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106689    }else if( isMinQuery ){
106690      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
106691      nConstraint++;
106692      startEq = 0;
106693      start_constraints = 1;
106694    }
106695    codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
106696    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
106697    assert( op!=0 );
106698    testcase( op==OP_Rewind );
106699    testcase( op==OP_Last );
106700    testcase( op==OP_SeekGt );
106701    testcase( op==OP_SeekGe );
106702    testcase( op==OP_SeekLe );
106703    testcase( op==OP_SeekLt );
106704    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
106705
106706    /* Load the value for the inequality constraint at the end of the
106707    ** range (if any).
106708    */
106709    nConstraint = nEq;
106710    if( pRangeEnd ){
106711      Expr *pRight = pRangeEnd->pExpr->pRight;
106712      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
106713      sqlite3ExprCode(pParse, pRight, regBase+nEq);
106714      if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
106715        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
106716      }
106717      if( zEndAff ){
106718        if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
106719          /* Since the comparison is to be performed with no conversions
106720          ** applied to the operands, set the affinity to apply to pRight to
106721          ** SQLITE_AFF_NONE.  */
106722          zEndAff[nEq] = SQLITE_AFF_NONE;
106723        }
106724        if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
106725          zEndAff[nEq] = SQLITE_AFF_NONE;
106726        }
106727      }
106728      codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
106729      nConstraint++;
106730      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106731    }
106732    sqlite3DbFree(pParse->db, zStartAff);
106733    sqlite3DbFree(pParse->db, zEndAff);
106734
106735    /* Top of the loop body */
106736    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
106737
106738    /* Check if the index cursor is past the end of the range. */
106739    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
106740    testcase( op==OP_Noop );
106741    testcase( op==OP_IdxGE );
106742    testcase( op==OP_IdxLT );
106743    if( op!=OP_Noop ){
106744      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
106745      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
106746    }
106747
106748    /* If there are inequality constraints, check that the value
106749    ** of the table column that the inequality contrains is not NULL.
106750    ** If it is, jump to the next iteration of the loop.
106751    */
106752    r1 = sqlite3GetTempReg(pParse);
106753    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
106754    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
106755    if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
106756      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
106757      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
106758    }
106759    sqlite3ReleaseTempReg(pParse, r1);
106760
106761    /* Seek the table cursor, if required */
106762    disableTerm(pLevel, pRangeStart);
106763    disableTerm(pLevel, pRangeEnd);
106764    if( !omitTable ){
106765      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
106766      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
106767      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106768      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
106769    }
106770
106771    /* Record the instruction used to terminate the loop. Disable
106772    ** WHERE clause terms made redundant by the index range scan.
106773    */
106774    if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
106775      pLevel->op = OP_Noop;
106776    }else if( bRev ){
106777      pLevel->op = OP_Prev;
106778    }else{
106779      pLevel->op = OP_Next;
106780    }
106781    pLevel->p1 = iIdxCur;
106782  }else
106783
106784#ifndef SQLITE_OMIT_OR_OPTIMIZATION
106785  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
106786    /* Case 4:  Two or more separately indexed terms connected by OR
106787    **
106788    ** Example:
106789    **
106790    **   CREATE TABLE t1(a,b,c,d);
106791    **   CREATE INDEX i1 ON t1(a);
106792    **   CREATE INDEX i2 ON t1(b);
106793    **   CREATE INDEX i3 ON t1(c);
106794    **
106795    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
106796    **
106797    ** In the example, there are three indexed terms connected by OR.
106798    ** The top of the loop looks like this:
106799    **
106800    **          Null       1                # Zero the rowset in reg 1
106801    **
106802    ** Then, for each indexed term, the following. The arguments to
106803    ** RowSetTest are such that the rowid of the current row is inserted
106804    ** into the RowSet. If it is already present, control skips the
106805    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
106806    **
106807    **        sqlite3WhereBegin(<term>)
106808    **          RowSetTest                  # Insert rowid into rowset
106809    **          Gosub      2 A
106810    **        sqlite3WhereEnd()
106811    **
106812    ** Following the above, code to terminate the loop. Label A, the target
106813    ** of the Gosub above, jumps to the instruction right after the Goto.
106814    **
106815    **          Null       1                # Zero the rowset in reg 1
106816    **          Goto       B                # The loop is finished.
106817    **
106818    **       A: <loop body>                 # Return data, whatever.
106819    **
106820    **          Return     2                # Jump back to the Gosub
106821    **
106822    **       B: <after the loop>
106823    **
106824    */
106825    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
106826    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
106827
106828    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
106829    int regRowset = 0;                        /* Register for RowSet object */
106830    int regRowid = 0;                         /* Register holding rowid */
106831    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
106832    int iRetInit;                             /* Address of regReturn init */
106833    int untestedTerms = 0;             /* Some terms not completely tested */
106834    int ii;                            /* Loop counter */
106835    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
106836
106837    pTerm = pLevel->plan.u.pTerm;
106838    assert( pTerm!=0 );
106839    assert( pTerm->eOperator==WO_OR );
106840    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
106841    pOrWc = &pTerm->u.pOrInfo->wc;
106842    pLevel->op = OP_Return;
106843    pLevel->p1 = regReturn;
106844
106845    /* Set up a new SrcList ni pOrTab containing the table being scanned
106846    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
106847    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
106848    */
106849    if( pWInfo->nLevel>1 ){
106850      int nNotReady;                 /* The number of notReady tables */
106851      struct SrcList_item *origSrc;     /* Original list of tables */
106852      nNotReady = pWInfo->nLevel - iLevel - 1;
106853      pOrTab = sqlite3StackAllocRaw(pParse->db,
106854                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
106855      if( pOrTab==0 ) return notReady;
106856      pOrTab->nAlloc = (i16)(nNotReady + 1);
106857      pOrTab->nSrc = pOrTab->nAlloc;
106858      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
106859      origSrc = pWInfo->pTabList->a;
106860      for(k=1; k<=nNotReady; k++){
106861        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
106862      }
106863    }else{
106864      pOrTab = pWInfo->pTabList;
106865    }
106866
106867    /* Initialize the rowset register to contain NULL. An SQL NULL is
106868    ** equivalent to an empty rowset.
106869    **
106870    ** Also initialize regReturn to contain the address of the instruction
106871    ** immediately following the OP_Return at the bottom of the loop. This
106872    ** is required in a few obscure LEFT JOIN cases where control jumps
106873    ** over the top of the loop into the body of it. In this case the
106874    ** correct response for the end-of-loop code (the OP_Return) is to
106875    ** fall through to the next instruction, just as an OP_Next does if
106876    ** called on an uninitialized cursor.
106877    */
106878    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
106879      regRowset = ++pParse->nMem;
106880      regRowid = ++pParse->nMem;
106881      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
106882    }
106883    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
106884
106885    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
106886    ** Then for every term xN, evaluate as the subexpression: xN AND z
106887    ** That way, terms in y that are factored into the disjunction will
106888    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
106889    **
106890    ** Actually, each subexpression is converted to "xN AND w" where w is
106891    ** the "interesting" terms of z - terms that did not originate in the
106892    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
106893    ** indices.
106894    */
106895    if( pWC->nTerm>1 ){
106896      int iTerm;
106897      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
106898        Expr *pExpr = pWC->a[iTerm].pExpr;
106899        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
106900        if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
106901        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
106902        pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
106903        pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
106904      }
106905      if( pAndExpr ){
106906        pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
106907      }
106908    }
106909
106910    for(ii=0; ii<pOrWc->nTerm; ii++){
106911      WhereTerm *pOrTerm = &pOrWc->a[ii];
106912      if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
106913        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
106914        Expr *pOrExpr = pOrTerm->pExpr;
106915        if( pAndExpr ){
106916          pAndExpr->pLeft = pOrExpr;
106917          pOrExpr = pAndExpr;
106918        }
106919        /* Loop through table entries that match term pOrTerm. */
106920        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
106921                        WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
106922                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
106923        if( pSubWInfo ){
106924          explainOneScan(
106925              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
106926          );
106927          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
106928            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
106929            int r;
106930            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
106931                                         regRowid);
106932            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
106933                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
106934          }
106935          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
106936
106937          /* The pSubWInfo->untestedTerms flag means that this OR term
106938          ** contained one or more AND term from a notReady table.  The
106939          ** terms from the notReady table could not be tested and will
106940          ** need to be tested later.
106941          */
106942          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
106943
106944          /* Finish the loop through table entries that match term pOrTerm. */
106945          sqlite3WhereEnd(pSubWInfo);
106946        }
106947      }
106948    }
106949    if( pAndExpr ){
106950      pAndExpr->pLeft = 0;
106951      sqlite3ExprDelete(pParse->db, pAndExpr);
106952    }
106953    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
106954    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
106955    sqlite3VdbeResolveLabel(v, iLoopBody);
106956
106957    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
106958    if( !untestedTerms ) disableTerm(pLevel, pTerm);
106959  }else
106960#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
106961
106962  {
106963    /* Case 5:  There is no usable index.  We must do a complete
106964    **          scan of the entire table.
106965    */
106966    static const u8 aStep[] = { OP_Next, OP_Prev };
106967    static const u8 aStart[] = { OP_Rewind, OP_Last };
106968    assert( bRev==0 || bRev==1 );
106969    assert( omitTable==0 );
106970    pLevel->op = aStep[bRev];
106971    pLevel->p1 = iCur;
106972    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
106973    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
106974  }
106975  notReady &= ~getMask(pWC->pMaskSet, iCur);
106976
106977  /* Insert code to test every subexpression that can be completely
106978  ** computed using the current set of tables.
106979  **
106980  ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
106981  ** the use of indices become tests that are evaluated against each row of
106982  ** the relevant input tables.
106983  */
106984  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
106985    Expr *pE;
106986    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
106987    testcase( pTerm->wtFlags & TERM_CODED );
106988    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
106989    if( (pTerm->prereqAll & notReady)!=0 ){
106990      testcase( pWInfo->untestedTerms==0
106991               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
106992      pWInfo->untestedTerms = 1;
106993      continue;
106994    }
106995    pE = pTerm->pExpr;
106996    assert( pE!=0 );
106997    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
106998      continue;
106999    }
107000    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
107001    pTerm->wtFlags |= TERM_CODED;
107002  }
107003
107004  /* For a LEFT OUTER JOIN, generate code that will record the fact that
107005  ** at least one row of the right table has matched the left table.
107006  */
107007  if( pLevel->iLeftJoin ){
107008    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
107009    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
107010    VdbeComment((v, "record LEFT JOIN hit"));
107011    sqlite3ExprCacheClear(pParse);
107012    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
107013      testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
107014      testcase( pTerm->wtFlags & TERM_CODED );
107015      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
107016      if( (pTerm->prereqAll & notReady)!=0 ){
107017        assert( pWInfo->untestedTerms );
107018        continue;
107019      }
107020      assert( pTerm->pExpr );
107021      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
107022      pTerm->wtFlags |= TERM_CODED;
107023    }
107024  }
107025  sqlite3ReleaseTempReg(pParse, iReleaseReg);
107026
107027  return notReady;
107028}
107029
107030#if defined(SQLITE_TEST)
107031/*
107032** The following variable holds a text description of query plan generated
107033** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
107034** overwrites the previous.  This information is used for testing and
107035** analysis only.
107036*/
107037SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
107038static int nQPlan = 0;              /* Next free slow in _query_plan[] */
107039
107040#endif /* SQLITE_TEST */
107041
107042
107043/*
107044** Free a WhereInfo structure
107045*/
107046static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
107047  if( ALWAYS(pWInfo) ){
107048    int i;
107049    for(i=0; i<pWInfo->nLevel; i++){
107050      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
107051      if( pInfo ){
107052        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
107053        if( pInfo->needToFreeIdxStr ){
107054          sqlite3_free(pInfo->idxStr);
107055        }
107056        sqlite3DbFree(db, pInfo);
107057      }
107058      if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
107059        Index *pIdx = pWInfo->a[i].plan.u.pIdx;
107060        if( pIdx ){
107061          sqlite3DbFree(db, pIdx->zColAff);
107062          sqlite3DbFree(db, pIdx);
107063        }
107064      }
107065    }
107066    whereClauseClear(pWInfo->pWC);
107067    sqlite3DbFree(db, pWInfo);
107068  }
107069}
107070
107071
107072/*
107073** Generate the beginning of the loop used for WHERE clause processing.
107074** The return value is a pointer to an opaque structure that contains
107075** information needed to terminate the loop.  Later, the calling routine
107076** should invoke sqlite3WhereEnd() with the return value of this function
107077** in order to complete the WHERE clause processing.
107078**
107079** If an error occurs, this routine returns NULL.
107080**
107081** The basic idea is to do a nested loop, one loop for each table in
107082** the FROM clause of a select.  (INSERT and UPDATE statements are the
107083** same as a SELECT with only a single table in the FROM clause.)  For
107084** example, if the SQL is this:
107085**
107086**       SELECT * FROM t1, t2, t3 WHERE ...;
107087**
107088** Then the code generated is conceptually like the following:
107089**
107090**      foreach row1 in t1 do       \    Code generated
107091**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
107092**          foreach row3 in t3 do   /
107093**            ...
107094**          end                     \    Code generated
107095**        end                        |-- by sqlite3WhereEnd()
107096**      end                         /
107097**
107098** Note that the loops might not be nested in the order in which they
107099** appear in the FROM clause if a different order is better able to make
107100** use of indices.  Note also that when the IN operator appears in
107101** the WHERE clause, it might result in additional nested loops for
107102** scanning through all values on the right-hand side of the IN.
107103**
107104** There are Btree cursors associated with each table.  t1 uses cursor
107105** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
107106** And so forth.  This routine generates code to open those VDBE cursors
107107** and sqlite3WhereEnd() generates the code to close them.
107108**
107109** The code that sqlite3WhereBegin() generates leaves the cursors named
107110** in pTabList pointing at their appropriate entries.  The [...] code
107111** can use OP_Column and OP_Rowid opcodes on these cursors to extract
107112** data from the various tables of the loop.
107113**
107114** If the WHERE clause is empty, the foreach loops must each scan their
107115** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
107116** the tables have indices and there are terms in the WHERE clause that
107117** refer to those indices, a complete table scan can be avoided and the
107118** code will run much faster.  Most of the work of this routine is checking
107119** to see if there are indices that can be used to speed up the loop.
107120**
107121** Terms of the WHERE clause are also used to limit which rows actually
107122** make it to the "..." in the middle of the loop.  After each "foreach",
107123** terms of the WHERE clause that use only terms in that loop and outer
107124** loops are evaluated and if false a jump is made around all subsequent
107125** inner loops (or around the "..." if the test occurs within the inner-
107126** most loop)
107127**
107128** OUTER JOINS
107129**
107130** An outer join of tables t1 and t2 is conceptally coded as follows:
107131**
107132**    foreach row1 in t1 do
107133**      flag = 0
107134**      foreach row2 in t2 do
107135**        start:
107136**          ...
107137**          flag = 1
107138**      end
107139**      if flag==0 then
107140**        move the row2 cursor to a null row
107141**        goto start
107142**      fi
107143**    end
107144**
107145** ORDER BY CLAUSE PROCESSING
107146**
107147** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
107148** if there is one.  If there is no ORDER BY clause or if this routine
107149** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
107150**
107151** If an index can be used so that the natural output order of the table
107152** scan is correct for the ORDER BY clause, then that index is used and
107153** *ppOrderBy is set to NULL.  This is an optimization that prevents an
107154** unnecessary sort of the result set if an index appropriate for the
107155** ORDER BY clause already exists.
107156**
107157** If the where clause loops cannot be arranged to provide the correct
107158** output order, then the *ppOrderBy is unchanged.
107159*/
107160SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
107161  Parse *pParse,        /* The parser context */
107162  SrcList *pTabList,    /* A list of all tables to be scanned */
107163  Expr *pWhere,         /* The WHERE clause */
107164  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
107165  ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
107166  u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
107167){
107168  int i;                     /* Loop counter */
107169  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
107170  int nTabList;              /* Number of elements in pTabList */
107171  WhereInfo *pWInfo;         /* Will become the return value of this function */
107172  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
107173  Bitmask notReady;          /* Cursors that are not yet positioned */
107174  WhereMaskSet *pMaskSet;    /* The expression mask set */
107175  WhereClause *pWC;               /* Decomposition of the WHERE clause */
107176  struct SrcList_item *pTabItem;  /* A single entry from pTabList */
107177  WhereLevel *pLevel;             /* A single level in the pWInfo list */
107178  int iFrom;                      /* First unused FROM clause element */
107179  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
107180  sqlite3 *db;               /* Database connection */
107181
107182  /* The number of tables in the FROM clause is limited by the number of
107183  ** bits in a Bitmask
107184  */
107185  testcase( pTabList->nSrc==BMS );
107186  if( pTabList->nSrc>BMS ){
107187    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
107188    return 0;
107189  }
107190
107191  /* This function normally generates a nested loop for all tables in
107192  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
107193  ** only generate code for the first table in pTabList and assume that
107194  ** any cursors associated with subsequent tables are uninitialized.
107195  */
107196  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
107197
107198  /* Allocate and initialize the WhereInfo structure that will become the
107199  ** return value. A single allocation is used to store the WhereInfo
107200  ** struct, the contents of WhereInfo.a[], the WhereClause structure
107201  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
107202  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
107203  ** some architectures. Hence the ROUND8() below.
107204  */
107205  db = pParse->db;
107206  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
107207  pWInfo = sqlite3DbMallocZero(db,
107208      nByteWInfo +
107209      sizeof(WhereClause) +
107210      sizeof(WhereMaskSet)
107211  );
107212  if( db->mallocFailed ){
107213    sqlite3DbFree(db, pWInfo);
107214    pWInfo = 0;
107215    goto whereBeginError;
107216  }
107217  pWInfo->nLevel = nTabList;
107218  pWInfo->pParse = pParse;
107219  pWInfo->pTabList = pTabList;
107220  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
107221  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
107222  pWInfo->wctrlFlags = wctrlFlags;
107223  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
107224  pMaskSet = (WhereMaskSet*)&pWC[1];
107225
107226  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
107227  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
107228  if( db->flags & SQLITE_DistinctOpt ) pDistinct = 0;
107229
107230  /* Split the WHERE clause into separate subexpressions where each
107231  ** subexpression is separated by an AND operator.
107232  */
107233  initMaskSet(pMaskSet);
107234  whereClauseInit(pWC, pParse, pMaskSet, wctrlFlags);
107235  sqlite3ExprCodeConstants(pParse, pWhere);
107236  whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
107237
107238  /* Special case: a WHERE clause that is constant.  Evaluate the
107239  ** expression and either jump over all of the code or fall thru.
107240  */
107241  if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
107242    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
107243    pWhere = 0;
107244  }
107245
107246  /* Assign a bit from the bitmask to every term in the FROM clause.
107247  **
107248  ** When assigning bitmask values to FROM clause cursors, it must be
107249  ** the case that if X is the bitmask for the N-th FROM clause term then
107250  ** the bitmask for all FROM clause terms to the left of the N-th term
107251  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
107252  ** its Expr.iRightJoinTable value to find the bitmask of the right table
107253  ** of the join.  Subtracting one from the right table bitmask gives a
107254  ** bitmask for all tables to the left of the join.  Knowing the bitmask
107255  ** for all tables to the left of a left join is important.  Ticket #3015.
107256  **
107257  ** Configure the WhereClause.vmask variable so that bits that correspond
107258  ** to virtual table cursors are set. This is used to selectively disable
107259  ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
107260  ** with virtual tables.
107261  **
107262  ** Note that bitmasks are created for all pTabList->nSrc tables in
107263  ** pTabList, not just the first nTabList tables.  nTabList is normally
107264  ** equal to pTabList->nSrc but might be shortened to 1 if the
107265  ** WHERE_ONETABLE_ONLY flag is set.
107266  */
107267  assert( pWC->vmask==0 && pMaskSet->n==0 );
107268  for(i=0; i<pTabList->nSrc; i++){
107269    createMask(pMaskSet, pTabList->a[i].iCursor);
107270#ifndef SQLITE_OMIT_VIRTUALTABLE
107271    if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
107272      pWC->vmask |= ((Bitmask)1 << i);
107273    }
107274#endif
107275  }
107276#ifndef NDEBUG
107277  {
107278    Bitmask toTheLeft = 0;
107279    for(i=0; i<pTabList->nSrc; i++){
107280      Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
107281      assert( (m-1)==toTheLeft );
107282      toTheLeft |= m;
107283    }
107284  }
107285#endif
107286
107287  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
107288  ** add new virtual terms onto the end of the WHERE clause.  We do not
107289  ** want to analyze these virtual terms, so start analyzing at the end
107290  ** and work forward so that the added virtual terms are never processed.
107291  */
107292  exprAnalyzeAll(pTabList, pWC);
107293  if( db->mallocFailed ){
107294    goto whereBeginError;
107295  }
107296
107297  /* Check if the DISTINCT qualifier, if there is one, is redundant.
107298  ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
107299  ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
107300  */
107301  if( pDistinct && isDistinctRedundant(pParse, pTabList, pWC, pDistinct) ){
107302    pDistinct = 0;
107303    pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
107304  }
107305
107306  /* Chose the best index to use for each table in the FROM clause.
107307  **
107308  ** This loop fills in the following fields:
107309  **
107310  **   pWInfo->a[].pIdx      The index to use for this level of the loop.
107311  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
107312  **   pWInfo->a[].nEq       The number of == and IN constraints
107313  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
107314  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
107315  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
107316  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
107317  **
107318  ** This loop also figures out the nesting order of tables in the FROM
107319  ** clause.
107320  */
107321  notReady = ~(Bitmask)0;
107322  andFlags = ~0;
107323  WHERETRACE(("*** Optimizer Start ***\n"));
107324  for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
107325    WhereCost bestPlan;         /* Most efficient plan seen so far */
107326    Index *pIdx;                /* Index for FROM table at pTabItem */
107327    int j;                      /* For looping over FROM tables */
107328    int bestJ = -1;             /* The value of j */
107329    Bitmask m;                  /* Bitmask value for j or bestJ */
107330    int isOptimal;              /* Iterator for optimal/non-optimal search */
107331    int nUnconstrained;         /* Number tables without INDEXED BY */
107332    Bitmask notIndexed;         /* Mask of tables that cannot use an index */
107333
107334    memset(&bestPlan, 0, sizeof(bestPlan));
107335    bestPlan.rCost = SQLITE_BIG_DBL;
107336    WHERETRACE(("*** Begin search for loop %d ***\n", i));
107337
107338    /* Loop through the remaining entries in the FROM clause to find the
107339    ** next nested loop. The loop tests all FROM clause entries
107340    ** either once or twice.
107341    **
107342    ** The first test is always performed if there are two or more entries
107343    ** remaining and never performed if there is only one FROM clause entry
107344    ** to choose from.  The first test looks for an "optimal" scan.  In
107345    ** this context an optimal scan is one that uses the same strategy
107346    ** for the given FROM clause entry as would be selected if the entry
107347    ** were used as the innermost nested loop.  In other words, a table
107348    ** is chosen such that the cost of running that table cannot be reduced
107349    ** by waiting for other tables to run first.  This "optimal" test works
107350    ** by first assuming that the FROM clause is on the inner loop and finding
107351    ** its query plan, then checking to see if that query plan uses any
107352    ** other FROM clause terms that are notReady.  If no notReady terms are
107353    ** used then the "optimal" query plan works.
107354    **
107355    ** Note that the WhereCost.nRow parameter for an optimal scan might
107356    ** not be as small as it would be if the table really were the innermost
107357    ** join.  The nRow value can be reduced by WHERE clause constraints
107358    ** that do not use indices.  But this nRow reduction only happens if the
107359    ** table really is the innermost join.
107360    **
107361    ** The second loop iteration is only performed if no optimal scan
107362    ** strategies were found by the first iteration. This second iteration
107363    ** is used to search for the lowest cost scan overall.
107364    **
107365    ** Previous versions of SQLite performed only the second iteration -
107366    ** the next outermost loop was always that with the lowest overall
107367    ** cost. However, this meant that SQLite could select the wrong plan
107368    ** for scripts such as the following:
107369    **
107370    **   CREATE TABLE t1(a, b);
107371    **   CREATE TABLE t2(c, d);
107372    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
107373    **
107374    ** The best strategy is to iterate through table t1 first. However it
107375    ** is not possible to determine this with a simple greedy algorithm.
107376    ** Since the cost of a linear scan through table t2 is the same
107377    ** as the cost of a linear scan through table t1, a simple greedy
107378    ** algorithm may choose to use t2 for the outer loop, which is a much
107379    ** costlier approach.
107380    */
107381    nUnconstrained = 0;
107382    notIndexed = 0;
107383    for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
107384      Bitmask mask;             /* Mask of tables not yet ready */
107385      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
107386        int doNotReorder;    /* True if this table should not be reordered */
107387        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
107388        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
107389        ExprList *pDist;     /* DISTINCT clause for index to optimize */
107390
107391        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
107392        if( j!=iFrom && doNotReorder ) break;
107393        m = getMask(pMaskSet, pTabItem->iCursor);
107394        if( (m & notReady)==0 ){
107395          if( j==iFrom ) iFrom++;
107396          continue;
107397        }
107398        mask = (isOptimal ? m : notReady);
107399        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
107400        pDist = (i==0 ? pDistinct : 0);
107401        if( pTabItem->pIndex==0 ) nUnconstrained++;
107402
107403        WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
107404                    j, isOptimal));
107405        assert( pTabItem->pTab );
107406#ifndef SQLITE_OMIT_VIRTUALTABLE
107407        if( IsVirtual(pTabItem->pTab) ){
107408          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
107409          bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
107410                           &sCost, pp);
107411        }else
107412#endif
107413        {
107414          bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
107415              pDist, &sCost);
107416        }
107417        assert( isOptimal || (sCost.used&notReady)==0 );
107418
107419        /* If an INDEXED BY clause is present, then the plan must use that
107420        ** index if it uses any index at all */
107421        assert( pTabItem->pIndex==0
107422                  || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
107423                  || sCost.plan.u.pIdx==pTabItem->pIndex );
107424
107425        if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
107426          notIndexed |= m;
107427        }
107428
107429        /* Conditions under which this table becomes the best so far:
107430        **
107431        **   (1) The table must not depend on other tables that have not
107432        **       yet run.
107433        **
107434        **   (2) A full-table-scan plan cannot supercede indexed plan unless
107435        **       the full-table-scan is an "optimal" plan as defined above.
107436        **
107437        **   (3) All tables have an INDEXED BY clause or this table lacks an
107438        **       INDEXED BY clause or this table uses the specific
107439        **       index specified by its INDEXED BY clause.  This rule ensures
107440        **       that a best-so-far is always selected even if an impossible
107441        **       combination of INDEXED BY clauses are given.  The error
107442        **       will be detected and relayed back to the application later.
107443        **       The NEVER() comes about because rule (2) above prevents
107444        **       An indexable full-table-scan from reaching rule (3).
107445        **
107446        **   (4) The plan cost must be lower than prior plans or else the
107447        **       cost must be the same and the number of rows must be lower.
107448        */
107449        if( (sCost.used&notReady)==0                       /* (1) */
107450            && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
107451                || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
107452                || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
107453            && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
107454                || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
107455            && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
107456                || (sCost.rCost<=bestPlan.rCost
107457                 && sCost.plan.nRow<bestPlan.plan.nRow))
107458        ){
107459          WHERETRACE(("=== table %d is best so far"
107460                      " with cost=%g and nRow=%g\n",
107461                      j, sCost.rCost, sCost.plan.nRow));
107462          bestPlan = sCost;
107463          bestJ = j;
107464        }
107465        if( doNotReorder ) break;
107466      }
107467    }
107468    assert( bestJ>=0 );
107469    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
107470    WHERETRACE(("*** Optimizer selects table %d for loop %d"
107471                " with cost=%g and nRow=%g\n",
107472                bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
107473    /* The ALWAYS() that follows was added to hush up clang scan-build */
107474    if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 && ALWAYS(ppOrderBy) ){
107475      *ppOrderBy = 0;
107476    }
107477    if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
107478      assert( pWInfo->eDistinct==0 );
107479      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
107480    }
107481    andFlags &= bestPlan.plan.wsFlags;
107482    pLevel->plan = bestPlan.plan;
107483    testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
107484    testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
107485    if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
107486      pLevel->iIdxCur = pParse->nTab++;
107487    }else{
107488      pLevel->iIdxCur = -1;
107489    }
107490    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
107491    pLevel->iFrom = (u8)bestJ;
107492    if( bestPlan.plan.nRow>=(double)1 ){
107493      pParse->nQueryLoop *= bestPlan.plan.nRow;
107494    }
107495
107496    /* Check that if the table scanned by this loop iteration had an
107497    ** INDEXED BY clause attached to it, that the named index is being
107498    ** used for the scan. If not, then query compilation has failed.
107499    ** Return an error.
107500    */
107501    pIdx = pTabList->a[bestJ].pIndex;
107502    if( pIdx ){
107503      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
107504        sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
107505        goto whereBeginError;
107506      }else{
107507        /* If an INDEXED BY clause is used, the bestIndex() function is
107508        ** guaranteed to find the index specified in the INDEXED BY clause
107509        ** if it find an index at all. */
107510        assert( bestPlan.plan.u.pIdx==pIdx );
107511      }
107512    }
107513  }
107514  WHERETRACE(("*** Optimizer Finished ***\n"));
107515  if( pParse->nErr || db->mallocFailed ){
107516    goto whereBeginError;
107517  }
107518
107519  /* If the total query only selects a single row, then the ORDER BY
107520  ** clause is irrelevant.
107521  */
107522  if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
107523    *ppOrderBy = 0;
107524  }
107525
107526  /* If the caller is an UPDATE or DELETE statement that is requesting
107527  ** to use a one-pass algorithm, determine if this is appropriate.
107528  ** The one-pass algorithm only works if the WHERE clause constraints
107529  ** the statement to update a single row.
107530  */
107531  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
107532  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
107533    pWInfo->okOnePass = 1;
107534    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
107535  }
107536
107537  /* Open all tables in the pTabList and any indices selected for
107538  ** searching those tables.
107539  */
107540  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
107541  notReady = ~(Bitmask)0;
107542  pWInfo->nRowOut = (double)1;
107543  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
107544    Table *pTab;     /* Table to open */
107545    int iDb;         /* Index of database containing table/index */
107546
107547    pTabItem = &pTabList->a[pLevel->iFrom];
107548    pTab = pTabItem->pTab;
107549    pLevel->iTabCur = pTabItem->iCursor;
107550    pWInfo->nRowOut *= pLevel->plan.nRow;
107551    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
107552    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
107553      /* Do nothing */
107554    }else
107555#ifndef SQLITE_OMIT_VIRTUALTABLE
107556    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107557      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
107558      int iCur = pTabItem->iCursor;
107559      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
107560    }else
107561#endif
107562    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107563         && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
107564      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
107565      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
107566      testcase( pTab->nCol==BMS-1 );
107567      testcase( pTab->nCol==BMS );
107568      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
107569        Bitmask b = pTabItem->colUsed;
107570        int n = 0;
107571        for(; b; b=b>>1, n++){}
107572        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
107573                            SQLITE_INT_TO_PTR(n), P4_INT32);
107574        assert( n<=pTab->nCol );
107575      }
107576    }else{
107577      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
107578    }
107579#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
107580    if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
107581      constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
107582    }else
107583#endif
107584    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
107585      Index *pIx = pLevel->plan.u.pIdx;
107586      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
107587      int iIdxCur = pLevel->iIdxCur;
107588      assert( pIx->pSchema==pTab->pSchema );
107589      assert( iIdxCur>=0 );
107590      sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
107591                        (char*)pKey, P4_KEYINFO_HANDOFF);
107592      VdbeComment((v, "%s", pIx->zName));
107593    }
107594    sqlite3CodeVerifySchema(pParse, iDb);
107595    notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
107596  }
107597  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
107598  if( db->mallocFailed ) goto whereBeginError;
107599
107600  /* Generate the code to do the search.  Each iteration of the for
107601  ** loop below generates code for a single nested loop of the VM
107602  ** program.
107603  */
107604  notReady = ~(Bitmask)0;
107605  for(i=0; i<nTabList; i++){
107606    pLevel = &pWInfo->a[i];
107607    explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
107608    notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
107609    pWInfo->iContinue = pLevel->addrCont;
107610  }
107611
107612#ifdef SQLITE_TEST  /* For testing and debugging use only */
107613  /* Record in the query plan information about the current table
107614  ** and the index used to access it (if any).  If the table itself
107615  ** is not used, its name is just '{}'.  If no index is used
107616  ** the index is listed as "{}".  If the primary key is used the
107617  ** index name is '*'.
107618  */
107619  for(i=0; i<nTabList; i++){
107620    char *z;
107621    int n;
107622    pLevel = &pWInfo->a[i];
107623    pTabItem = &pTabList->a[pLevel->iFrom];
107624    z = pTabItem->zAlias;
107625    if( z==0 ) z = pTabItem->pTab->zName;
107626    n = sqlite3Strlen30(z);
107627    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
107628      if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
107629        memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
107630        nQPlan += 2;
107631      }else{
107632        memcpy(&sqlite3_query_plan[nQPlan], z, n);
107633        nQPlan += n;
107634      }
107635      sqlite3_query_plan[nQPlan++] = ' ';
107636    }
107637    testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
107638    testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
107639    if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
107640      memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
107641      nQPlan += 2;
107642    }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
107643      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
107644      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
107645        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
107646        nQPlan += n;
107647        sqlite3_query_plan[nQPlan++] = ' ';
107648      }
107649    }else{
107650      memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
107651      nQPlan += 3;
107652    }
107653  }
107654  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
107655    sqlite3_query_plan[--nQPlan] = 0;
107656  }
107657  sqlite3_query_plan[nQPlan] = 0;
107658  nQPlan = 0;
107659#endif /* SQLITE_TEST // Testing and debugging use only */
107660
107661  /* Record the continuation address in the WhereInfo structure.  Then
107662  ** clean up and return.
107663  */
107664  return pWInfo;
107665
107666  /* Jump here if malloc fails */
107667whereBeginError:
107668  if( pWInfo ){
107669    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
107670    whereInfoFree(db, pWInfo);
107671  }
107672  return 0;
107673}
107674
107675/*
107676** Generate the end of the WHERE loop.  See comments on
107677** sqlite3WhereBegin() for additional information.
107678*/
107679SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
107680  Parse *pParse = pWInfo->pParse;
107681  Vdbe *v = pParse->pVdbe;
107682  int i;
107683  WhereLevel *pLevel;
107684  SrcList *pTabList = pWInfo->pTabList;
107685  sqlite3 *db = pParse->db;
107686
107687  /* Generate loop termination code.
107688  */
107689  sqlite3ExprCacheClear(pParse);
107690  for(i=pWInfo->nLevel-1; i>=0; i--){
107691    pLevel = &pWInfo->a[i];
107692    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
107693    if( pLevel->op!=OP_Noop ){
107694      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
107695      sqlite3VdbeChangeP5(v, pLevel->p5);
107696    }
107697    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
107698      struct InLoop *pIn;
107699      int j;
107700      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
107701      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
107702        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
107703        sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
107704        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
107705      }
107706      sqlite3DbFree(db, pLevel->u.in.aInLoop);
107707    }
107708    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
107709    if( pLevel->iLeftJoin ){
107710      int addr;
107711      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
107712      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107713           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
107714      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
107715        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
107716      }
107717      if( pLevel->iIdxCur>=0 ){
107718        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
107719      }
107720      if( pLevel->op==OP_Return ){
107721        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
107722      }else{
107723        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
107724      }
107725      sqlite3VdbeJumpHere(v, addr);
107726    }
107727  }
107728
107729  /* The "break" point is here, just past the end of the outer loop.
107730  ** Set it.
107731  */
107732  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
107733
107734  /* Close all of the cursors that were opened by sqlite3WhereBegin.
107735  */
107736  assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
107737  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
107738    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
107739    Table *pTab = pTabItem->pTab;
107740    assert( pTab!=0 );
107741    if( (pTab->tabFlags & TF_Ephemeral)==0
107742     && pTab->pSelect==0
107743     && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
107744    ){
107745      int ws = pLevel->plan.wsFlags;
107746      if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
107747        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
107748      }
107749      if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
107750        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
107751      }
107752    }
107753
107754    /* If this scan uses an index, make code substitutions to read data
107755    ** from the index in preference to the table. Sometimes, this means
107756    ** the table need never be read from. This is a performance boost,
107757    ** as the vdbe level waits until the table is read before actually
107758    ** seeking the table cursor to the record corresponding to the current
107759    ** position in the index.
107760    **
107761    ** Calls to the code generator in between sqlite3WhereBegin and
107762    ** sqlite3WhereEnd will have created code that references the table
107763    ** directly.  This loop scans all that code looking for opcodes
107764    ** that reference the table and converts them into opcodes that
107765    ** reference the index.
107766    */
107767    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
107768      int k, j, last;
107769      VdbeOp *pOp;
107770      Index *pIdx = pLevel->plan.u.pIdx;
107771
107772      assert( pIdx!=0 );
107773      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
107774      last = sqlite3VdbeCurrentAddr(v);
107775      for(k=pWInfo->iTop; k<last; k++, pOp++){
107776        if( pOp->p1!=pLevel->iTabCur ) continue;
107777        if( pOp->opcode==OP_Column ){
107778          for(j=0; j<pIdx->nColumn; j++){
107779            if( pOp->p2==pIdx->aiColumn[j] ){
107780              pOp->p2 = j;
107781              pOp->p1 = pLevel->iIdxCur;
107782              break;
107783            }
107784          }
107785          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107786               || j<pIdx->nColumn );
107787        }else if( pOp->opcode==OP_Rowid ){
107788          pOp->p1 = pLevel->iIdxCur;
107789          pOp->opcode = OP_IdxRowid;
107790        }
107791      }
107792    }
107793  }
107794
107795  /* Final cleanup
107796  */
107797  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
107798  whereInfoFree(db, pWInfo);
107799  return;
107800}
107801
107802/************** End of where.c ***********************************************/
107803/************** Begin file parse.c *******************************************/
107804/* Driver template for the LEMON parser generator.
107805** The author disclaims copyright to this source code.
107806**
107807** This version of "lempar.c" is modified, slightly, for use by SQLite.
107808** The only modifications are the addition of a couple of NEVER()
107809** macros to disable tests that are needed in the case of a general
107810** LALR(1) grammar but which are always false in the
107811** specific grammar used by SQLite.
107812*/
107813/* First off, code is included that follows the "include" declaration
107814** in the input grammar file. */
107815/* #include <stdio.h> */
107816
107817
107818/*
107819** Disable all error recovery processing in the parser push-down
107820** automaton.
107821*/
107822#define YYNOERRORRECOVERY 1
107823
107824/*
107825** Make yytestcase() the same as testcase()
107826*/
107827#define yytestcase(X) testcase(X)
107828
107829/*
107830** An instance of this structure holds information about the
107831** LIMIT clause of a SELECT statement.
107832*/
107833struct LimitVal {
107834  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
107835  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
107836};
107837
107838/*
107839** An instance of this structure is used to store the LIKE,
107840** GLOB, NOT LIKE, and NOT GLOB operators.
107841*/
107842struct LikeOp {
107843  Token eOperator;  /* "like" or "glob" or "regexp" */
107844  int not;         /* True if the NOT keyword is present */
107845};
107846
107847/*
107848** An instance of the following structure describes the event of a
107849** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
107850** TK_DELETE, or TK_INSTEAD.  If the event is of the form
107851**
107852**      UPDATE ON (a,b,c)
107853**
107854** Then the "b" IdList records the list "a,b,c".
107855*/
107856struct TrigEvent { int a; IdList * b; };
107857
107858/*
107859** An instance of this structure holds the ATTACH key and the key type.
107860*/
107861struct AttachKey { int type;  Token key; };
107862
107863/*
107864** One or more VALUES claues
107865*/
107866struct ValueList {
107867  ExprList *pList;
107868  Select *pSelect;
107869};
107870
107871
107872  /* This is a utility routine used to set the ExprSpan.zStart and
107873  ** ExprSpan.zEnd values of pOut so that the span covers the complete
107874  ** range of text beginning with pStart and going to the end of pEnd.
107875  */
107876  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
107877    pOut->zStart = pStart->z;
107878    pOut->zEnd = &pEnd->z[pEnd->n];
107879  }
107880
107881  /* Construct a new Expr object from a single identifier.  Use the
107882  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
107883  ** that created the expression.
107884  */
107885  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
107886    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
107887    pOut->zStart = pValue->z;
107888    pOut->zEnd = &pValue->z[pValue->n];
107889  }
107890
107891  /* This routine constructs a binary expression node out of two ExprSpan
107892  ** objects and uses the result to populate a new ExprSpan object.
107893  */
107894  static void spanBinaryExpr(
107895    ExprSpan *pOut,     /* Write the result here */
107896    Parse *pParse,      /* The parsing context.  Errors accumulate here */
107897    int op,             /* The binary operation */
107898    ExprSpan *pLeft,    /* The left operand */
107899    ExprSpan *pRight    /* The right operand */
107900  ){
107901    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
107902    pOut->zStart = pLeft->zStart;
107903    pOut->zEnd = pRight->zEnd;
107904  }
107905
107906  /* Construct an expression node for a unary postfix operator
107907  */
107908  static void spanUnaryPostfix(
107909    ExprSpan *pOut,        /* Write the new expression node here */
107910    Parse *pParse,         /* Parsing context to record errors */
107911    int op,                /* The operator */
107912    ExprSpan *pOperand,    /* The operand */
107913    Token *pPostOp         /* The operand token for setting the span */
107914  ){
107915    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
107916    pOut->zStart = pOperand->zStart;
107917    pOut->zEnd = &pPostOp->z[pPostOp->n];
107918  }
107919
107920  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
107921  ** unary TK_ISNULL or TK_NOTNULL expression. */
107922  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
107923    sqlite3 *db = pParse->db;
107924    if( db->mallocFailed==0 && pY->op==TK_NULL ){
107925      pA->op = (u8)op;
107926      sqlite3ExprDelete(db, pA->pRight);
107927      pA->pRight = 0;
107928    }
107929  }
107930
107931  /* Construct an expression node for a unary prefix operator
107932  */
107933  static void spanUnaryPrefix(
107934    ExprSpan *pOut,        /* Write the new expression node here */
107935    Parse *pParse,         /* Parsing context to record errors */
107936    int op,                /* The operator */
107937    ExprSpan *pOperand,    /* The operand */
107938    Token *pPreOp         /* The operand token for setting the span */
107939  ){
107940    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
107941    pOut->zStart = pPreOp->z;
107942    pOut->zEnd = pOperand->zEnd;
107943  }
107944/* Next is all token values, in a form suitable for use by makeheaders.
107945** This section will be null unless lemon is run with the -m switch.
107946*/
107947/*
107948** These constants (all generated automatically by the parser generator)
107949** specify the various kinds of tokens (terminals) that the parser
107950** understands.
107951**
107952** Each symbol here is a terminal symbol in the grammar.
107953*/
107954/* Make sure the INTERFACE macro is defined.
107955*/
107956#ifndef INTERFACE
107957# define INTERFACE 1
107958#endif
107959/* The next thing included is series of defines which control
107960** various aspects of the generated parser.
107961**    YYCODETYPE         is the data type used for storing terminal
107962**                       and nonterminal numbers.  "unsigned char" is
107963**                       used if there are fewer than 250 terminals
107964**                       and nonterminals.  "int" is used otherwise.
107965**    YYNOCODE           is a number of type YYCODETYPE which corresponds
107966**                       to no legal terminal or nonterminal number.  This
107967**                       number is used to fill in empty slots of the hash
107968**                       table.
107969**    YYFALLBACK         If defined, this indicates that one or more tokens
107970**                       have fall-back values which should be used if the
107971**                       original value of the token will not parse.
107972**    YYACTIONTYPE       is the data type used for storing terminal
107973**                       and nonterminal numbers.  "unsigned char" is
107974**                       used if there are fewer than 250 rules and
107975**                       states combined.  "int" is used otherwise.
107976**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
107977**                       directly to the parser from the tokenizer.
107978**    YYMINORTYPE        is the data type used for all minor tokens.
107979**                       This is typically a union of many types, one of
107980**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
107981**                       for base tokens is called "yy0".
107982**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
107983**                       zero the stack is dynamically sized using realloc()
107984**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
107985**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
107986**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
107987**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
107988**    YYNSTATE           the combined number of states.
107989**    YYNRULE            the number of rules in the grammar
107990**    YYERRORSYMBOL      is the code number of the error symbol.  If not
107991**                       defined, then do no error processing.
107992*/
107993#define YYCODETYPE unsigned char
107994#define YYNOCODE 251
107995#define YYACTIONTYPE unsigned short int
107996#define YYWILDCARD 67
107997#define sqlite3ParserTOKENTYPE Token
107998typedef union {
107999  int yyinit;
108000  sqlite3ParserTOKENTYPE yy0;
108001  struct LimitVal yy64;
108002  Expr* yy122;
108003  Select* yy159;
108004  IdList* yy180;
108005  struct {int value; int mask;} yy207;
108006  u8 yy258;
108007  struct LikeOp yy318;
108008  TriggerStep* yy327;
108009  ExprSpan yy342;
108010  SrcList* yy347;
108011  int yy392;
108012  struct TrigEvent yy410;
108013  ExprList* yy442;
108014  struct ValueList yy487;
108015} YYMINORTYPE;
108016#ifndef YYSTACKDEPTH
108017#define YYSTACKDEPTH 100
108018#endif
108019#define sqlite3ParserARG_SDECL Parse *pParse;
108020#define sqlite3ParserARG_PDECL ,Parse *pParse
108021#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
108022#define sqlite3ParserARG_STORE yypParser->pParse = pParse
108023#define YYNSTATE 629
108024#define YYNRULE 327
108025#define YYFALLBACK 1
108026#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
108027#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
108028#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
108029
108030/* The yyzerominor constant is used to initialize instances of
108031** YYMINORTYPE objects to zero. */
108032static const YYMINORTYPE yyzerominor = { 0 };
108033
108034/* Define the yytestcase() macro to be a no-op if is not already defined
108035** otherwise.
108036**
108037** Applications can choose to define yytestcase() in the %include section
108038** to a macro that can assist in verifying code coverage.  For production
108039** code the yytestcase() macro should be turned off.  But it is useful
108040** for testing.
108041*/
108042#ifndef yytestcase
108043# define yytestcase(X)
108044#endif
108045
108046
108047/* Next are the tables used to determine what action to take based on the
108048** current state and lookahead token.  These tables are used to implement
108049** functions that take a state number and lookahead value and return an
108050** action integer.
108051**
108052** Suppose the action integer is N.  Then the action is determined as
108053** follows
108054**
108055**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
108056**                                      token onto the stack and goto state N.
108057**
108058**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
108059**
108060**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
108061**
108062**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
108063**
108064**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
108065**                                      slots in the yy_action[] table.
108066**
108067** The action table is constructed as a single large table named yy_action[].
108068** Given state S and lookahead X, the action is computed as
108069**
108070**      yy_action[ yy_shift_ofst[S] + X ]
108071**
108072** If the index value yy_shift_ofst[S]+X is out of range or if the value
108073** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
108074** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
108075** and that yy_default[S] should be used instead.
108076**
108077** The formula above is for computing the action when the lookahead is
108078** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
108079** a reduce action) then the yy_reduce_ofst[] array is used in place of
108080** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
108081** YY_SHIFT_USE_DFLT.
108082**
108083** The following are the tables generated in this section:
108084**
108085**  yy_action[]        A single table containing all actions.
108086**  yy_lookahead[]     A table containing the lookahead for each entry in
108087**                     yy_action.  Used to detect hash collisions.
108088**  yy_shift_ofst[]    For each state, the offset into yy_action for
108089**                     shifting terminals.
108090**  yy_reduce_ofst[]   For each state, the offset into yy_action for
108091**                     shifting non-terminals after a reduce.
108092**  yy_default[]       Default action for each state.
108093*/
108094#define YY_ACTTAB_COUNT (1580)
108095static const YYACTIONTYPE yy_action[] = {
108096 /*     0 */   310,  328,  574,  573,   15,  172,  187,  596,   56,   56,
108097 /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
108098 /*    20 */    52,   52,   51,  234,  622,  621,  626,  622,  621,  299,
108099 /*    30 */   589,  583,   56,   56,   56,   56,  236,   54,   54,   54,
108100 /*    40 */    54,   53,   53,   52,   52,   52,   51,  234,  351,   57,
108101 /*    50 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
108102 /*    60 */    56,   56,  570,   54,   54,   54,   54,   53,   53,   52,
108103 /*    70 */    52,   52,   51,  234,  310,  596,  326,  607,  233,  232,
108104 /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108105 /*    90 */    51,  234,  619,  618,  326,  619,  618,  166,  605,  492,
108106 /*   100 */   381,  378,  377,  235,  589,  583,  554,  495,    1,   59,
108107 /*   110 */    19,  376,  622,  621,   53,   53,   52,   52,   52,   51,
108108 /*   120 */   234,  571,  571,   57,   58,   48,  581,  580,  582,  582,
108109 /*   130 */    55,   55,   56,   56,   56,   56,  215,   54,   54,   54,
108110 /*   140 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  224,
108111 /*   150 */    50,   47,  147,  177,  139,  281,  384,  276,  383,  169,
108112 /*   160 */   408,  553,  578,  578,  622,  621,  272,  224,  439,  550,
108113 /*   170 */   552,  410,  139,  281,  384,  276,  383,  169,  589,  583,
108114 /*   180 */   619,  618,  280,  620,  272,  195,  413,  309,  440,  441,
108115 /*   190 */   567,  491,  214,  279,  560,  600,   92,   57,   58,   48,
108116 /*   200 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
108117 /*   210 */   559,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108118 /*   220 */    51,  234,  310,  464,  233,  232,  558,  133,  519,   50,
108119 /*   230 */    47,  147,  619,  618,  565,  436,  397,  515,  514,  518,
108120 /*   240 */   410,  387,  438,  389,  437,  622,  621,  442,  570,  433,
108121 /*   250 */   203,  390,  589,  583,    6,  413,  166,  670,  250,  381,
108122 /*   260 */   378,  377,  525,  190,  600,   92,  594,  571,  571,  465,
108123 /*   270 */   376,   57,   58,   48,  581,  580,  582,  582,   55,   55,
108124 /*   280 */    56,   56,   56,   56,  599,   54,   54,   54,   54,   53,
108125 /*   290 */    53,   52,   52,   52,   51,  234,  310,  592,  592,  592,
108126 /*   300 */   490,  182,  247,  548,  249,  397,  273,  410,    7,  439,
108127 /*   310 */   398,  606,   67,  619,  618,  620,  472,  256,  347,  255,
108128 /*   320 */   473,  620,  413,  576,  620,   65,  589,  583,  236,  440,
108129 /*   330 */   336,  600,   92,   68,  364,  192,  481,  622,  621,  547,
108130 /*   340 */   622,  621,  560,  323,  207,   57,   58,   48,  581,  580,
108131 /*   350 */   582,  582,   55,   55,   56,   56,   56,   56,  559,   54,
108132 /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
108133 /*   370 */   310,  410,  397,  146,  558,  531,  401,  348,  599,  166,
108134 /*   380 */   248,  204,  381,  378,  377,  541,  413,  171,  337,  570,
108135 /*   390 */   622,  621,   40,  376,   38,  600,   74,  465,  548,  490,
108136 /*   400 */   589,  583,  532,  350,  579,  619,  618,  297,  619,  618,
108137 /*   410 */   480,   67,  470,   39,  620,  599,  406,  574,  573,   57,
108138 /*   420 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
108139 /*   430 */    56,   56,  577,   54,   54,   54,   54,   53,   53,   52,
108140 /*   440 */    52,   52,   51,  234,  310,  256,  347,  255,  530,   52,
108141 /*   450 */    52,   52,   51,  234,  345,  564,  236,  386,  619,  618,
108142 /*   460 */   957,  185,  418,    2,  408,  410,  578,  578,  198,  197,
108143 /*   470 */   196,  499,  183,  167,  589,  583,  671,  570,  505,  506,
108144 /*   480 */   413,  267,  601,  672,  546,  208,  602,   36,  601,  600,
108145 /*   490 */    91,  468,  602,   57,   58,   48,  581,  580,  582,  582,
108146 /*   500 */    55,   55,   56,   56,   56,   56,  202,   54,   54,   54,
108147 /*   510 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  599,
108148 /*   520 */   157,  408,  527,  578,  578,  263,  490,  265,  410,  873,
108149 /*   530 */   410,  474,  474,  366,  373,  410,  504,  428,   67,  290,
108150 /*   540 */   599,  620,  352,  413,  408,  413,  578,  578,  589,  583,
108151 /*   550 */   413,  382,  600,   92,  600,   16,  543,   62,  503,  600,
108152 /*   560 */    92,  408,  346,  578,  578,  168,   45,   57,   58,   48,
108153 /*   570 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
108154 /*   580 */   200,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108155 /*   590 */    51,  234,  310,  393,  395,  534,  510,  617,  616,  615,
108156 /*   600 */   318,  314,  172,   66,  596,  410,  338,  596,  324,  571,
108157 /*   610 */   571,   50,   47,  147,  599,  629,  627,  330,  539,  315,
108158 /*   620 */   413,   30,  589,  583,  272,  236,  199,  144,  176,  600,
108159 /*   630 */    73,  420,  947,  620,  947,  420,  946,  351,  946,  175,
108160 /*   640 */   596,   57,   58,   48,  581,  580,  582,  582,   55,   55,
108161 /*   650 */    56,   56,   56,   56,  410,   54,   54,   54,   54,   53,
108162 /*   660 */    53,   52,   52,   52,   51,  234,  310,  261,  410,  413,
108163 /*   670 */   269,  208,  596,  363,  410,  596,  424,  360,  600,   69,
108164 /*   680 */   424,  327,  620,  413,   50,   47,  147,  410,  358,  413,
108165 /*   690 */   575,  553,  600,   94,  483,  509,  589,  583,  600,   97,
108166 /*   700 */   552,  484,  413,  620,  188,  599,  551,  563,  596,  566,
108167 /*   710 */   334,  600,   95,  205,  201,   57,   58,   48,  581,  580,
108168 /*   720 */   582,  582,   55,   55,   56,   56,   56,   56,  352,   54,
108169 /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
108170 /*   740 */   310,  410,  261,  410,  167,   22,  356,  599,  359,  623,
108171 /*   750 */    50,   47,  147,  548,  357,  562,  413,  620,  413,  332,
108172 /*   760 */   523,  270,  410,  167,  620,  600,  104,  600,  103,  603,
108173 /*   770 */   589,  583,  339,  539,  304,  423,  222,  413,  174,  304,
108174 /*   780 */   422,  561,  567,  405,  214,  260,  600,  106,  620,   57,
108175 /*   790 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
108176 /*   800 */    56,   56,  410,   54,   54,   54,   54,   53,   53,   52,
108177 /*   810 */    52,   52,   51,  234,  310,  410,  557,  413,  410,  421,
108178 /*   820 */   273,   35,  512,  146,  421,   12,  600,  107,  213,  144,
108179 /*   830 */   413,  410,   32,  413,  410,  620,  365,  353,  358,  600,
108180 /*   840 */   134,   11,  600,  135,  589,  583,  413,   21,  548,  413,
108181 /*   850 */   316,  148,  620,  620,  170,  600,   98,  223,  600,  102,
108182 /*   860 */   374,  168,  167,   57,   58,   48,  581,  580,  582,  582,
108183 /*   870 */    55,   55,   56,   56,   56,   56,  410,   54,   54,   54,
108184 /*   880 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  410,
108185 /*   890 */   273,  413,  410,  273,  212,  469,  410,  167,  628,    2,
108186 /*   900 */   600,  101,  545,  221,  413,  620,  130,  413,  620,  410,
108187 /*   910 */   539,  413,  537,  600,   93,  315,  600,  100,  589,  583,
108188 /*   920 */   600,   77,  425,  305,  413,  620,  254,  322,  599,  458,
108189 /*   930 */   320,  171,  543,  600,   96,  521,  520,   57,   58,   48,
108190 /*   940 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
108191 /*   950 */   410,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108192 /*   960 */    51,  234,  310,  410,  273,  413,  410,  457,  358,   35,
108193 /*   970 */   426,  230,  306,  319,  600,  138,  467,  520,  413,  620,
108194 /*   980 */   143,  413,  410,  620,  410,  353,  529,  600,  137,  142,
108195 /*   990 */   600,  136,  589,  583,  604,  261,  528,  413,  229,  413,
108196 /*  1000 */   620,  321,  495,   28,  543,  543,  600,   76,  600,   90,
108197 /*  1010 */   620,   57,   46,   48,  581,  580,  582,  582,   55,   55,
108198 /*  1020 */    56,   56,   56,   56,  410,   54,   54,   54,   54,   53,
108199 /*  1030 */    53,   52,   52,   52,   51,  234,  310,  261,  451,  413,
108200 /*  1040 */   410,  211,  611,  285,  283,  610,  609,  502,  600,   89,
108201 /*  1050 */   380,  217,  620,  128,  140,  413,  220,  620,  410,  409,
108202 /*  1060 */   620,  620,  588,  587,  600,   75,  589,  583,  271,  620,
108203 /*  1070 */    51,  234,  127,  413,  620,  599,  627,  330,   27,  375,
108204 /*  1080 */   449,  279,  600,   88,  585,  584,   58,   48,  581,  580,
108205 /*  1090 */   582,  582,   55,   55,   56,   56,   56,   56,  410,   54,
108206 /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
108207 /*  1110 */   310,  586,  410,  413,  410,  261,  593,  165,  399,  556,
108208 /*  1120 */   126,  371,  600,   87,  478,  186,  123,  413,  367,  413,
108209 /*  1130 */   620,  620,  410,  620,  620,  410,  600,   99,  600,   86,
108210 /*  1140 */   589,  583,  475,  122,  258,  171,  471,  413,  160,  121,
108211 /*  1150 */   413,   14,  159,  463,   25,   24,  600,   17,  448,  600,
108212 /*  1160 */    85,   48,  581,  580,  582,  582,   55,   55,   56,   56,
108213 /*  1170 */    56,   56,  158,   54,   54,   54,   54,   53,   53,   52,
108214 /*  1180 */    52,   52,   51,  234,   44,  404,  261,    3,  544,  261,
108215 /*  1190 */   540,  414,  621,  460,  119,  118,  538,  275,   10,  349,
108216 /*  1200 */     4,  620,  407,  620,  620,  620,  116,   44,  404,  410,
108217 /*  1210 */     3,  620,  620,  410,  414,  621,  456,  454,  252,  450,
108218 /*  1220 */   508,  402,  111,  109,  413,  407,  155,  444,  413,  447,
108219 /*  1230 */   435,  565,  219,  600,   84,  620,  108,  600,   83,   64,
108220 /*  1240 */   434,  417,  625,  150,  402,  333,  410,  237,  238,  124,
108221 /*  1250 */   274,   41,   42,  533,  565,  206,  189,  261,   43,  412,
108222 /*  1260 */   411,  413,  261,  594,  488,  620,  329,  149,  419,  268,
108223 /*  1270 */   600,   72,  620,  266,   41,   42,  181,  620,  410,  620,
108224 /*  1280 */   105,   43,  412,  411,  620,  624,  594,  614,  620,  599,
108225 /*  1290 */   228,  125,  313,  413,  592,  592,  592,  591,  590,   13,
108226 /*  1300 */   218,  410,  600,   71,  236,  244,   44,  404,  264,    3,
108227 /*  1310 */   312,  613,  340,  414,  621,  180,  413,  592,  592,  592,
108228 /*  1320 */   591,  590,   13,  620,  407,  600,   82,  410,  416,   34,
108229 /*  1330 */   404,  410,    3,  410,  262,  410,  414,  621,  612,  331,
108230 /*  1340 */   178,  415,  413,  402,    8,  236,  413,  407,  413,  620,
108231 /*  1350 */   413,  600,   81,  565,  257,  600,   80,  600,   70,  600,
108232 /*  1360 */    18,  598,  361,  462,  461,   30,  402,  294,   31,  620,
108233 /*  1370 */   293,  354,  251,   41,   42,  410,  565,  620,  620,  620,
108234 /*  1380 */    43,  412,  411,  453,  396,  594,  620,  620,  394,   61,
108235 /*  1390 */   413,  292,  443,  622,  621,  243,   41,   42,  620,  600,
108236 /*  1400 */    79,  597,  291,   43,  412,  411,   60,  620,  594,  240,
108237 /*  1410 */   620,  410,  231,   37,  555,  173,  592,  592,  592,  591,
108238 /*  1420 */   590,   13,  216,  239,  620,  184,  413,  302,  301,  300,
108239 /*  1430 */   179,  298,  388,  565,  452,  600,   78,  286,  620,  592,
108240 /*  1440 */   592,  592,  591,  590,   13,  429,   29,  413,  151,  289,
108241 /*  1450 */   242,  145,  392,  194,  193,  288,  600,    9,  542,  241,
108242 /*  1460 */   620,  525,  391,  284,  620,  594,  620,  620,  522,  536,
108243 /*  1470 */   620,  535,  153,  385,  465,  516,  282,  325,  154,  517,
108244 /*  1480 */   277,  152,  512,  511,  513,  129,  226,  308,  487,  486,
108245 /*  1490 */   485,  164,  372,  493,  307,  227,  592,  592,  592,  225,
108246 /*  1500 */   479,  163,  368,  370,  162,  476,  210,  477,   26,  259,
108247 /*  1510 */   161,  466,  362,  141,  132,  120,  117,  455,  156,  115,
108248 /*  1520 */   344,  343,  256,  342,  245,  114,  113,  446,  311,  112,
108249 /*  1530 */    23,  317,  432,  236,  131,  431,  110,  430,   20,  427,
108250 /*  1540 */   608,  595,  295,   63,  379,  287,  509,  191,  278,  403,
108251 /*  1550 */   572,  569,  497,  498,  496,  494,  335,  459,  445,  303,
108252 /*  1560 */   296,  246,  341,  355,    5,  568,  369,  507,  253,  549,
108253 /*  1570 */   526,  209,  400,  501,  500,  524,  234,  958,  489,  482,
108254};
108255static const YYCODETYPE yy_lookahead[] = {
108256 /*     0 */    19,  169,  170,  171,   22,   24,   24,   26,   77,   78,
108257 /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
108258 /*    20 */    89,   90,   91,   92,   26,   27,    1,   26,   27,   15,
108259 /*    30 */    49,   50,   77,   78,   79,   80,  116,   82,   83,   84,
108260 /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,  128,   68,
108261 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108262 /*    60 */    79,   80,  230,   82,   83,   84,   85,   86,   87,   88,
108263 /*    70 */    89,   90,   91,   92,   19,   94,   19,   23,   86,   87,
108264 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108265 /*    90 */    91,   92,   94,   95,   19,   94,   95,   96,  172,  173,
108266 /*   100 */    99,  100,  101,  197,   49,   50,  177,  181,   22,   54,
108267 /*   110 */   204,  110,   26,   27,   86,   87,   88,   89,   90,   91,
108268 /*   120 */    92,  129,  130,   68,   69,   70,   71,   72,   73,   74,
108269 /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
108270 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
108271 /*   150 */   221,  222,  223,   96,   97,   98,   99,  100,  101,  102,
108272 /*   160 */   112,   32,  114,  115,   26,   27,  109,   92,  150,   25,
108273 /*   170 */    41,  150,   97,   98,   99,  100,  101,  102,   49,   50,
108274 /*   180 */    94,   95,   98,  165,  109,   25,  165,  163,  170,  171,
108275 /*   190 */   166,  167,  168,  109,   12,  174,  175,   68,   69,   70,
108276 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
108277 /*   210 */    28,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108278 /*   220 */    91,   92,   19,   11,   86,   87,   44,   24,   46,  221,
108279 /*   230 */   222,  223,   94,   95,   66,   97,  215,    7,    8,   57,
108280 /*   240 */   150,  220,  104,   19,  106,   26,   27,  229,  230,  241,
108281 /*   250 */   160,   27,   49,   50,   22,  165,   96,  118,   16,   99,
108282 /*   260 */   100,  101,   94,  119,  174,  175,   98,  129,  130,   57,
108283 /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
108284 /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
108285 /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
108286 /*   300 */   150,   23,   60,   25,   62,  215,  150,  150,   76,  150,
108287 /*   310 */   220,  161,  162,   94,   95,  165,   30,  105,  106,  107,
108288 /*   320 */    34,  165,  165,   23,  165,   25,   49,   50,  116,  170,
108289 /*   330 */   171,  174,  175,   22,   48,  185,  186,   26,   27,  120,
108290 /*   340 */    26,   27,   12,  187,  160,   68,   69,   70,   71,   72,
108291 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   28,   82,
108292 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
108293 /*   370 */    19,  150,  215,   95,   44,   23,   46,  220,  194,   96,
108294 /*   380 */   138,  160,   99,  100,  101,   23,  165,   25,  229,  230,
108295 /*   390 */    26,   27,  135,  110,  137,  174,  175,   57,  120,  150,
108296 /*   400 */    49,   50,   88,  219,  113,   94,   95,  158,   94,   95,
108297 /*   410 */   161,  162,   21,  136,  165,  194,  169,  170,  171,   68,
108298 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108299 /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
108300 /*   440 */    89,   90,   91,   92,   19,  105,  106,  107,   23,   88,
108301 /*   450 */    89,   90,   91,   92,   63,   23,  116,   88,   94,   95,
108302 /*   460 */   142,  143,  144,  145,  112,  150,  114,  115,  105,  106,
108303 /*   470 */   107,   23,   23,   25,   49,   50,  118,  230,   97,   98,
108304 /*   480 */   165,   16,  113,  118,  120,  160,  117,  136,  113,  174,
108305 /*   490 */   175,  100,  117,   68,   69,   70,   71,   72,   73,   74,
108306 /*   500 */    75,   76,   77,   78,   79,   80,  160,   82,   83,   84,
108307 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
108308 /*   520 */    25,  112,   23,  114,  115,   60,  150,   62,  150,  138,
108309 /*   530 */   150,  105,  106,  107,   19,  150,   36,  161,  162,  224,
108310 /*   540 */   194,  165,  217,  165,  112,  165,  114,  115,   49,   50,
108311 /*   550 */   165,   51,  174,  175,  174,  175,  166,  232,   58,  174,
108312 /*   560 */   175,  112,  237,  114,  115,   50,   22,   68,   69,   70,
108313 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
108314 /*   580 */   160,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108315 /*   590 */    91,   92,   19,  215,  214,  205,   23,    7,    8,    9,
108316 /*   600 */   215,  155,   24,   22,   26,  150,   97,   26,  108,  129,
108317 /*   610 */   130,  221,  222,  223,  194,    0,    1,    2,  150,  104,
108318 /*   620 */   165,  126,   49,   50,  109,  116,  206,  207,  118,  174,
108319 /*   630 */   175,   22,   23,  165,   25,   22,   23,  128,   25,  118,
108320 /*   640 */    26,   68,   69,   70,   71,   72,   73,   74,   75,   76,
108321 /*   650 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
108322 /*   660 */    87,   88,   89,   90,   91,   92,   19,  150,  150,  165,
108323 /*   670 */    23,  160,   94,  227,  150,   94,   67,  231,  174,  175,
108324 /*   680 */    67,  213,  165,  165,  221,  222,  223,  150,  150,  165,
108325 /*   690 */    23,   32,  174,  175,  181,  182,   49,   50,  174,  175,
108326 /*   700 */    41,  188,  165,  165,   22,  194,  177,   11,   94,   23,
108327 /*   710 */   193,  174,  175,  160,   22,   68,   69,   70,   71,   72,
108328 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  217,   82,
108329 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
108330 /*   740 */    19,  150,  150,  150,   25,   24,   19,  194,  237,  150,
108331 /*   750 */   221,  222,  223,   25,   27,   23,  165,  165,  165,  242,
108332 /*   760 */   165,   23,  150,   25,  165,  174,  175,  174,  175,  174,
108333 /*   770 */    49,   50,  219,  150,   22,   23,  238,  165,   25,   22,
108334 /*   780 */    23,   23,  166,  167,  168,  193,  174,  175,  165,   68,
108335 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108336 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
108337 /*   810 */    89,   90,   91,   92,   19,  150,   23,  165,  150,   67,
108338 /*   820 */   150,   25,  103,   95,   67,   35,  174,  175,  206,  207,
108339 /*   830 */   165,  150,   25,  165,  150,  165,  213,  150,  150,  174,
108340 /*   840 */   175,   35,  174,  175,   49,   50,  165,   52,  120,  165,
108341 /*   850 */   245,  246,  165,  165,   35,  174,  175,  187,  174,  175,
108342 /*   860 */    23,   50,   25,   68,   69,   70,   71,   72,   73,   74,
108343 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
108344 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
108345 /*   890 */   150,  165,  150,  150,  160,   23,  150,   25,  144,  145,
108346 /*   900 */   174,  175,  120,  216,  165,  165,   22,  165,  165,  150,
108347 /*   910 */   150,  165,   27,  174,  175,  104,  174,  175,   49,   50,
108348 /*   920 */   174,  175,  247,  248,  165,  165,  238,  187,  194,   23,
108349 /*   930 */   187,   25,  166,  174,  175,  190,  191,   68,   69,   70,
108350 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
108351 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108352 /*   960 */    91,   92,   19,  150,  150,  165,  150,   23,  150,   25,
108353 /*   970 */    23,  205,   25,  213,  174,  175,  190,  191,  165,  165,
108354 /*   980 */   118,  165,  150,  165,  150,  150,   23,  174,  175,   39,
108355 /*   990 */   174,  175,   49,   50,  173,  150,   23,  165,   52,  165,
108356 /*  1000 */   165,  187,  181,   22,  166,  166,  174,  175,  174,  175,
108357 /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
108358 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
108359 /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
108360 /*  1040 */   150,  160,  150,  205,  205,  150,  150,   29,  174,  175,
108361 /*  1050 */    52,  216,  165,   22,  150,  165,  238,  165,  150,  150,
108362 /*  1060 */   165,  165,   49,   50,  174,  175,   49,   50,   23,  165,
108363 /*  1070 */    91,   92,   22,  165,  165,  194,    1,    2,   22,   52,
108364 /*  1080 */   193,  109,  174,  175,   71,   72,   69,   70,   71,   72,
108365 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
108366 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
108367 /*  1110 */    19,   98,  150,  165,  150,  150,  150,  102,  150,  150,
108368 /*  1120 */    22,   19,  174,  175,   20,   24,  104,  165,   43,  165,
108369 /*  1130 */   165,  165,  150,  165,  165,  150,  174,  175,  174,  175,
108370 /*  1140 */    49,   50,   59,   53,  138,   25,   53,  165,  104,   22,
108371 /*  1150 */   165,    5,  118,    1,   76,   76,  174,  175,  193,  174,
108372 /*  1160 */   175,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108373 /*  1170 */    79,   80,   35,   82,   83,   84,   85,   86,   87,   88,
108374 /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,  150,
108375 /*  1190 */   150,   26,   27,   27,  108,  127,  150,  150,   22,   25,
108376 /*  1200 */    22,  165,   37,  165,  165,  165,  119,   19,   20,  150,
108377 /*  1210 */    22,  165,  165,  150,   26,   27,   23,    1,   16,   20,
108378 /*  1220 */   150,   56,  119,  108,  165,   37,  121,  128,  165,  193,
108379 /*  1230 */    23,   66,  193,  174,  175,  165,  127,  174,  175,   16,
108380 /*  1240 */    23,  146,  147,   15,   56,   65,  150,  152,  140,  154,
108381 /*  1250 */   150,   86,   87,   88,   66,  160,   22,  150,   93,   94,
108382 /*  1260 */    95,  165,  150,   98,  150,  165,    3,  246,    4,  150,
108383 /*  1270 */   174,  175,  165,  150,   86,   87,    6,  165,  150,  165,
108384 /*  1280 */   164,   93,   94,   95,  165,  149,   98,  149,  165,  194,
108385 /*  1290 */   180,  180,  249,  165,  129,  130,  131,  132,  133,  134,
108386 /*  1300 */   193,  150,  174,  175,  116,  193,   19,   20,  150,   22,
108387 /*  1310 */   249,  149,  217,   26,   27,  151,  165,  129,  130,  131,
108388 /*  1320 */   132,  133,  134,  165,   37,  174,  175,  150,  149,   19,
108389 /*  1330 */    20,  150,   22,  150,  150,  150,   26,   27,   13,  244,
108390 /*  1340 */   151,  159,  165,   56,   25,  116,  165,   37,  165,  165,
108391 /*  1350 */   165,  174,  175,   66,  150,  174,  175,  174,  175,  174,
108392 /*  1360 */   175,  194,  150,  150,  150,  126,   56,  199,  124,  165,
108393 /*  1370 */   200,  150,  150,   86,   87,  150,   66,  165,  165,  165,
108394 /*  1380 */    93,   94,   95,  150,  122,   98,  165,  165,  123,   22,
108395 /*  1390 */   165,  201,  150,   26,   27,  150,   86,   87,  165,  174,
108396 /*  1400 */   175,  203,  202,   93,   94,   95,  125,  165,   98,  150,
108397 /*  1410 */   165,  150,  225,  135,  157,  118,  129,  130,  131,  132,
108398 /*  1420 */   133,  134,    5,  150,  165,  157,  165,   10,   11,   12,
108399 /*  1430 */    13,   14,  150,   66,   17,  174,  175,  210,  165,  129,
108400 /*  1440 */   130,  131,  132,  133,  134,  150,  104,  165,   31,  150,
108401 /*  1450 */    33,  150,  150,   86,   87,  150,  174,  175,  211,   42,
108402 /*  1460 */   165,   94,  121,  210,  165,   98,  165,  165,  176,  211,
108403 /*  1470 */   165,  211,   55,  104,   57,  184,  210,   47,   61,  176,
108404 /*  1480 */   176,   64,  103,  176,  178,   22,   92,  179,  176,  176,
108405 /*  1490 */   176,  156,   18,  184,  179,  228,  129,  130,  131,  228,
108406 /*  1500 */   157,  156,   45,  157,  156,  236,  157,  157,  135,  235,
108407 /*  1510 */   156,  189,  157,   68,  218,  189,   22,  199,  156,  192,
108408 /*  1520 */   157,   18,  105,  106,  107,  192,  192,  199,  111,  192,
108409 /*  1530 */   240,  157,   40,  116,  218,  157,  189,  157,  240,   38,
108410 /*  1540 */   153,  166,  198,  243,  178,  209,  182,  196,  177,  226,
108411 /*  1550 */   230,  230,  166,  177,  177,  166,  139,  199,  199,  148,
108412 /*  1560 */   195,  209,  209,  239,  196,  166,  234,  183,  239,  208,
108413 /*  1570 */   174,  233,  191,  183,  183,  174,   92,  250,  186,  186,
108414};
108415#define YY_SHIFT_USE_DFLT (-81)
108416#define YY_SHIFT_COUNT (417)
108417#define YY_SHIFT_MIN   (-80)
108418#define YY_SHIFT_MAX   (1503)
108419static const short yy_shift_ofst[] = {
108420 /*     0 */  1075, 1188, 1417, 1188, 1287, 1287,  138,  138,    1,  -19,
108421 /*    10 */  1287, 1287, 1287, 1287,  340,   -2,  129,  129,  795, 1165,
108422 /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
108423 /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
108424 /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
108425 /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
108426 /*    60 */  1287, 1287,  212,   -2,   -2,   -8,   -8,  614, 1229,   55,
108427 /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
108428 /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
108429 /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
108430 /*   100 */   -45,  -45,  -45,  -45,   -1,   57,   28,  361,   -2,   -2,
108431 /*   110 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
108432 /*   120 */    -2,   -2,   -2,   -2,  391,  515,   -2,   -2,   -2,   -2,
108433 /*   130 */    -2,  509,  -80,  614,  979, 1484,  -81,  -81,  -81, 1367,
108434 /*   140 */    75,  182,  182,  314,  311,  364,  219,   86,  613,  609,
108435 /*   150 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
108436 /*   160 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
108437 /*   170 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
108438 /*   180 */    -2,   -2,  578,  578,  578,  615, 1229, 1229, 1229,  -81,
108439 /*   190 */   -81,  -81,  160,  168,  168,  283,  500,  500,  500,  278,
108440 /*   200 */   449,  330,  432,  409,  352,   48,   48,   48,   48,  426,
108441 /*   210 */   286,   48,   48,  728,  581,  369,  590,  495,  224,  224,
108442 /*   220 */   727,  495,  727,  719,  614,  659,  614,  659,  811,  659,
108443 /*   230 */   224,  257,  480,  480,  614,  144,  375,  -18, 1501, 1297,
108444 /*   240 */  1297, 1492, 1492, 1297, 1494, 1445, 1239, 1503, 1503, 1503,
108445 /*   250 */  1503, 1297, 1474, 1239, 1494, 1445, 1445, 1297, 1474, 1373,
108446 /*   260 */  1457, 1297, 1297, 1474, 1297, 1474, 1297, 1474, 1463, 1369,
108447 /*   270 */  1369, 1369, 1430, 1394, 1394, 1463, 1369, 1379, 1369, 1430,
108448 /*   280 */  1369, 1369, 1341, 1342, 1341, 1342, 1341, 1342, 1297, 1297,
108449 /*   290 */  1278, 1281, 1262, 1244, 1265, 1239, 1229, 1319, 1325, 1325,
108450 /*   300 */  1270, 1270, 1270, 1270,  -81,  -81,  -81,  -81,  -81,  -81,
108451 /*   310 */  1013,  242,  757,  752,  465,  363,  947,  232,  944,  906,
108452 /*   320 */   872,  837,  738,  448,  381,  230,   84,  362,  300, 1264,
108453 /*   330 */  1263, 1234, 1108, 1228, 1180, 1223, 1217, 1207, 1099, 1174,
108454 /*   340 */  1109, 1115, 1103, 1199, 1105, 1202, 1216, 1087, 1193, 1178,
108455 /*   350 */  1174, 1176, 1068, 1079, 1078, 1086, 1166, 1137, 1034, 1152,
108456 /*   360 */  1146, 1127, 1044, 1006, 1093, 1120, 1090, 1083, 1085, 1022,
108457 /*   370 */  1101, 1104, 1102,  972, 1015, 1098, 1027, 1056, 1050, 1045,
108458 /*   380 */  1031,  998, 1018,  981,  946,  950,  973,  963,  862,  885,
108459 /*   390 */   819,  884,  782,  796,  806,  807,  790,  796,  793,  758,
108460 /*   400 */   753,  732,  692,  696,  682,  686,  667,  544,  291,  521,
108461 /*   410 */   510,  365,  358,  139,  114,   54,   14,   25,
108462};
108463#define YY_REDUCE_USE_DFLT (-169)
108464#define YY_REDUCE_COUNT (309)
108465#define YY_REDUCE_MIN   (-168)
108466#define YY_REDUCE_MAX   (1411)
108467static const short yy_reduce_ofst[] = {
108468 /*     0 */   318,   90, 1095,  221,  157,   21,  159,   18,  150,  390,
108469 /*    10 */   385,  378,  380,  315,  325,  249,  529,  -71,    8, 1282,
108470 /*    20 */  1261, 1225, 1185, 1183, 1181, 1177, 1151, 1128, 1096, 1063,
108471 /*    30 */  1059,  985,  982,  964,  962,  948,  908,  890,  874,  834,
108472 /*    40 */   832,  816,  813,  800,  759,  746,  742,  739,  726,  684,
108473 /*    50 */   681,  668,  665,  652,  612,  593,  591,  537,  524,  518,
108474 /*    60 */   504,  455,  511,  376,  517,  247, -168,   24,  420,  463,
108475 /*    70 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
108476 /*    80 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
108477 /*    90 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
108478 /*   100 */   463,  463,  463,  463,  463,  -74,  463,  463, 1112,  835,
108479 /*   110 */  1107, 1039, 1036,  965,  887,  845,  818,  760,  688,  687,
108480 /*   120 */   538,  743,  623,  592,  446,  513,  814,  740,  670,  156,
108481 /*   130 */   468,  553,  184,  616,  463,  463,  463,  463,  463,  595,
108482 /*   140 */   821,  786,  745,  909, 1305, 1302, 1301, 1299,  675,  675,
108483 /*   150 */  1295, 1273, 1259, 1245, 1242, 1233, 1222, 1221, 1214, 1213,
108484 /*   160 */  1212, 1204, 1184, 1158, 1123, 1119, 1114, 1100, 1070, 1047,
108485 /*   170 */  1046, 1040, 1038,  969,  968,  966,  909,  904,  896,  895,
108486 /*   180 */   892,  599,  839,  838,  766,  754,  881,  734,  346,  605,
108487 /*   190 */   622,  -94, 1393, 1401, 1396, 1392, 1391, 1390, 1384, 1361,
108488 /*   200 */  1365, 1381, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1332,
108489 /*   210 */  1338, 1365, 1365, 1361, 1399, 1368, 1411, 1359, 1353, 1352,
108490 /*   220 */  1329, 1358, 1324, 1366, 1389, 1377, 1386, 1376, 1364, 1371,
108491 /*   230 */  1336, 1323, 1321, 1320, 1375, 1344, 1351, 1387, 1300, 1380,
108492 /*   240 */  1378, 1298, 1290, 1374, 1316, 1347, 1328, 1337, 1334, 1333,
108493 /*   250 */  1327, 1363, 1362, 1318, 1296, 1326, 1322, 1355, 1354, 1269,
108494 /*   260 */  1274, 1350, 1349, 1348, 1346, 1345, 1343, 1335, 1315, 1314,
108495 /*   270 */  1313, 1312, 1309, 1271, 1267, 1308, 1307, 1306, 1304, 1291,
108496 /*   280 */  1303, 1292, 1260, 1266, 1258, 1253, 1247, 1227, 1268, 1257,
108497 /*   290 */  1187, 1198, 1200, 1190, 1170, 1168, 1167, 1182, 1189, 1164,
108498 /*   300 */  1179, 1162, 1138, 1136, 1061, 1043, 1021, 1111, 1110, 1116,
108499};
108500static const YYACTIONTYPE yy_default[] = {
108501 /*     0 */   634,  868,  956,  956,  868,  868,  956,  956,  956,  758,
108502 /*    10 */   956,  956,  956,  866,  956,  956,  786,  786,  930,  956,
108503 /*    20 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108504 /*    30 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108505 /*    40 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108506 /*    50 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108507 /*    60 */   956,  956,  956,  956,  956,  956,  956,  673,  762,  792,
108508 /*    70 */   956,  956,  956,  956,  956,  956,  956,  956,  929,  931,
108509 /*    80 */   800,  799,  909,  773,  797,  790,  794,  869,  862,  863,
108510 /*    90 */   861,  865,  870,  956,  793,  829,  846,  828,  840,  845,
108511 /*   100 */   852,  844,  841,  831,  830,  665,  832,  833,  956,  956,
108512 /*   110 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108513 /*   120 */   956,  956,  956,  956,  660,  727,  956,  956,  956,  956,
108514 /*   130 */   956,  956,  956,  956,  834,  835,  849,  848,  847,  956,
108515 /*   140 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108516 /*   150 */   956,  936,  934,  956,  881,  956,  956,  956,  956,  956,
108517 /*   160 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108518 /*   170 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108519 /*   180 */   956,  640,  758,  758,  758,  634,  956,  956,  956,  948,
108520 /*   190 */   762,  752,  718,  956,  956,  956,  956,  956,  956,  956,
108521 /*   200 */   956,  956,  956,  956,  956,  802,  741,  919,  921,  956,
108522 /*   210 */   902,  739,  662,  760,  675,  750,  642,  796,  775,  775,
108523 /*   220 */   914,  796,  914,  699,  956,  786,  956,  786,  696,  786,
108524 /*   230 */   775,  864,  956,  956,  956,  759,  750,  956,  941,  766,
108525 /*   240 */   766,  933,  933,  766,  808,  731,  796,  738,  738,  738,
108526 /*   250 */   738,  766,  657,  796,  808,  731,  731,  766,  657,  908,
108527 /*   260 */   906,  766,  766,  657,  766,  657,  766,  657,  874,  729,
108528 /*   270 */   729,  729,  714,  878,  878,  874,  729,  699,  729,  714,
108529 /*   280 */   729,  729,  779,  774,  779,  774,  779,  774,  766,  766,
108530 /*   290 */   956,  791,  780,  789,  787,  796,  956,  717,  650,  650,
108531 /*   300 */   639,  639,  639,  639,  953,  953,  948,  701,  701,  683,
108532 /*   310 */   956,  956,  956,  956,  956,  956,  956,  883,  956,  956,
108533 /*   320 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108534 /*   330 */   635,  943,  956,  956,  940,  956,  956,  956,  956,  801,
108535 /*   340 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108536 /*   350 */   918,  956,  956,  956,  956,  956,  956,  956,  912,  956,
108537 /*   360 */   956,  956,  956,  956,  956,  905,  904,  956,  956,  956,
108538 /*   370 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108539 /*   380 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108540 /*   390 */   956,  956,  956,  788,  956,  781,  956,  867,  956,  956,
108541 /*   400 */   956,  956,  956,  956,  956,  956,  956,  956,  744,  817,
108542 /*   410 */   956,  816,  820,  815,  667,  956,  648,  956,  631,  636,
108543 /*   420 */   952,  955,  954,  951,  950,  949,  944,  942,  939,  938,
108544 /*   430 */   937,  935,  932,  928,  887,  885,  892,  891,  890,  889,
108545 /*   440 */   888,  886,  884,  882,  803,  798,  795,  927,  880,  740,
108546 /*   450 */   737,  736,  656,  945,  911,  920,  807,  806,  809,  917,
108547 /*   460 */   916,  915,  913,  910,  897,  805,  804,  732,  872,  871,
108548 /*   470 */   659,  901,  900,  899,  903,  907,  898,  768,  658,  655,
108549 /*   480 */   664,  721,  720,  728,  726,  725,  724,  723,  722,  719,
108550 /*   490 */   666,  674,  685,  713,  698,  697,  877,  879,  876,  875,
108551 /*   500 */   706,  705,  711,  710,  709,  708,  707,  704,  703,  702,
108552 /*   510 */   695,  694,  700,  693,  716,  715,  712,  692,  735,  734,
108553 /*   520 */   733,  730,  691,  690,  689,  820,  688,  687,  826,  825,
108554 /*   530 */   813,  856,  755,  754,  753,  765,  764,  777,  776,  811,
108555 /*   540 */   810,  778,  763,  757,  756,  772,  771,  770,  769,  761,
108556 /*   550 */   751,  783,  785,  784,  782,  858,  767,  855,  926,  925,
108557 /*   560 */   924,  923,  922,  860,  859,  827,  824,  678,  679,  895,
108558 /*   570 */   894,  896,  893,  681,  680,  677,  676,  857,  746,  745,
108559 /*   580 */   853,  850,  842,  838,  854,  851,  843,  839,  837,  836,
108560 /*   590 */   822,  821,  819,  818,  814,  823,  669,  747,  743,  742,
108561 /*   600 */   812,  749,  748,  686,  684,  682,  663,  661,  654,  652,
108562 /*   610 */   651,  653,  649,  647,  646,  645,  644,  643,  672,  671,
108563 /*   620 */   670,  668,  667,  641,  638,  637,  633,  632,  630,
108564};
108565
108566/* The next table maps tokens into fallback tokens.  If a construct
108567** like the following:
108568**
108569**      %fallback ID X Y Z.
108570**
108571** appears in the grammar, then ID becomes a fallback token for X, Y,
108572** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
108573** but it does not parse, the type of the token is changed to ID and
108574** the parse is retried before an error is thrown.
108575*/
108576#ifdef YYFALLBACK
108577static const YYCODETYPE yyFallback[] = {
108578    0,  /*          $ => nothing */
108579    0,  /*       SEMI => nothing */
108580   26,  /*    EXPLAIN => ID */
108581   26,  /*      QUERY => ID */
108582   26,  /*       PLAN => ID */
108583   26,  /*      BEGIN => ID */
108584    0,  /* TRANSACTION => nothing */
108585   26,  /*   DEFERRED => ID */
108586   26,  /*  IMMEDIATE => ID */
108587   26,  /*  EXCLUSIVE => ID */
108588    0,  /*     COMMIT => nothing */
108589   26,  /*        END => ID */
108590   26,  /*   ROLLBACK => ID */
108591   26,  /*  SAVEPOINT => ID */
108592   26,  /*    RELEASE => ID */
108593    0,  /*         TO => nothing */
108594    0,  /*      TABLE => nothing */
108595    0,  /*     CREATE => nothing */
108596   26,  /*         IF => ID */
108597    0,  /*        NOT => nothing */
108598    0,  /*     EXISTS => nothing */
108599   26,  /*       TEMP => ID */
108600    0,  /*         LP => nothing */
108601    0,  /*         RP => nothing */
108602    0,  /*         AS => nothing */
108603    0,  /*      COMMA => nothing */
108604    0,  /*         ID => nothing */
108605    0,  /*    INDEXED => nothing */
108606   26,  /*      ABORT => ID */
108607   26,  /*     ACTION => ID */
108608   26,  /*      AFTER => ID */
108609   26,  /*    ANALYZE => ID */
108610   26,  /*        ASC => ID */
108611   26,  /*     ATTACH => ID */
108612   26,  /*     BEFORE => ID */
108613   26,  /*         BY => ID */
108614   26,  /*    CASCADE => ID */
108615   26,  /*       CAST => ID */
108616   26,  /*   COLUMNKW => ID */
108617   26,  /*   CONFLICT => ID */
108618   26,  /*   DATABASE => ID */
108619   26,  /*       DESC => ID */
108620   26,  /*     DETACH => ID */
108621   26,  /*       EACH => ID */
108622   26,  /*       FAIL => ID */
108623   26,  /*        FOR => ID */
108624   26,  /*     IGNORE => ID */
108625   26,  /*  INITIALLY => ID */
108626   26,  /*    INSTEAD => ID */
108627   26,  /*    LIKE_KW => ID */
108628   26,  /*      MATCH => ID */
108629   26,  /*         NO => ID */
108630   26,  /*        KEY => ID */
108631   26,  /*         OF => ID */
108632   26,  /*     OFFSET => ID */
108633   26,  /*     PRAGMA => ID */
108634   26,  /*      RAISE => ID */
108635   26,  /*    REPLACE => ID */
108636   26,  /*   RESTRICT => ID */
108637   26,  /*        ROW => ID */
108638   26,  /*    TRIGGER => ID */
108639   26,  /*     VACUUM => ID */
108640   26,  /*       VIEW => ID */
108641   26,  /*    VIRTUAL => ID */
108642   26,  /*    REINDEX => ID */
108643   26,  /*     RENAME => ID */
108644   26,  /*   CTIME_KW => ID */
108645};
108646#endif /* YYFALLBACK */
108647
108648/* The following structure represents a single element of the
108649** parser's stack.  Information stored includes:
108650**
108651**   +  The state number for the parser at this level of the stack.
108652**
108653**   +  The value of the token stored at this level of the stack.
108654**      (In other words, the "major" token.)
108655**
108656**   +  The semantic value stored at this level of the stack.  This is
108657**      the information used by the action routines in the grammar.
108658**      It is sometimes called the "minor" token.
108659*/
108660struct yyStackEntry {
108661  YYACTIONTYPE stateno;  /* The state-number */
108662  YYCODETYPE major;      /* The major token value.  This is the code
108663                         ** number for the token at this stack level */
108664  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
108665                         ** is the value of the token  */
108666};
108667typedef struct yyStackEntry yyStackEntry;
108668
108669/* The state of the parser is completely contained in an instance of
108670** the following structure */
108671struct yyParser {
108672  int yyidx;                    /* Index of top element in stack */
108673#ifdef YYTRACKMAXSTACKDEPTH
108674  int yyidxMax;                 /* Maximum value of yyidx */
108675#endif
108676  int yyerrcnt;                 /* Shifts left before out of the error */
108677  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
108678#if YYSTACKDEPTH<=0
108679  int yystksz;                  /* Current side of the stack */
108680  yyStackEntry *yystack;        /* The parser's stack */
108681#else
108682  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
108683#endif
108684};
108685typedef struct yyParser yyParser;
108686
108687#ifndef NDEBUG
108688/* #include <stdio.h> */
108689static FILE *yyTraceFILE = 0;
108690static char *yyTracePrompt = 0;
108691#endif /* NDEBUG */
108692
108693#ifndef NDEBUG
108694/*
108695** Turn parser tracing on by giving a stream to which to write the trace
108696** and a prompt to preface each trace message.  Tracing is turned off
108697** by making either argument NULL
108698**
108699** Inputs:
108700** <ul>
108701** <li> A FILE* to which trace output should be written.
108702**      If NULL, then tracing is turned off.
108703** <li> A prefix string written at the beginning of every
108704**      line of trace output.  If NULL, then tracing is
108705**      turned off.
108706** </ul>
108707**
108708** Outputs:
108709** None.
108710*/
108711SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
108712  yyTraceFILE = TraceFILE;
108713  yyTracePrompt = zTracePrompt;
108714  if( yyTraceFILE==0 ) yyTracePrompt = 0;
108715  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
108716}
108717#endif /* NDEBUG */
108718
108719#ifndef NDEBUG
108720/* For tracing shifts, the names of all terminals and nonterminals
108721** are required.  The following table supplies these names */
108722static const char *const yyTokenName[] = {
108723  "$",             "SEMI",          "EXPLAIN",       "QUERY",
108724  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
108725  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
108726  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
108727  "TABLE",         "CREATE",        "IF",            "NOT",
108728  "EXISTS",        "TEMP",          "LP",            "RP",
108729  "AS",            "COMMA",         "ID",            "INDEXED",
108730  "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
108731  "ASC",           "ATTACH",        "BEFORE",        "BY",
108732  "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
108733  "DATABASE",      "DESC",          "DETACH",        "EACH",
108734  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
108735  "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
108736  "KEY",           "OF",            "OFFSET",        "PRAGMA",
108737  "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
108738  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
108739  "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
108740  "OR",            "AND",           "IS",            "BETWEEN",
108741  "IN",            "ISNULL",        "NOTNULL",       "NE",
108742  "EQ",            "GT",            "LE",            "LT",
108743  "GE",            "ESCAPE",        "BITAND",        "BITOR",
108744  "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
108745  "STAR",          "SLASH",         "REM",           "CONCAT",
108746  "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
108747  "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
108748  "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
108749  "ON",            "INSERT",        "DELETE",        "UPDATE",
108750  "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
108751  "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
108752  "SELECT",        "DISTINCT",      "DOT",           "FROM",
108753  "JOIN",          "USING",         "ORDER",         "GROUP",
108754  "HAVING",        "LIMIT",         "WHERE",         "INTO",
108755  "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
108756  "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
108757  "THEN",          "ELSE",          "INDEX",         "ALTER",
108758  "ADD",           "error",         "input",         "cmdlist",
108759  "ecmd",          "explain",       "cmdx",          "cmd",
108760  "transtype",     "trans_opt",     "nm",            "savepoint_opt",
108761  "create_table",  "create_table_args",  "createkw",      "temp",
108762  "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
108763  "select",        "column",        "columnid",      "type",
108764  "carglist",      "id",            "ids",           "typetoken",
108765  "typename",      "signed",        "plus_num",      "minus_num",
108766  "carg",          "ccons",         "term",          "expr",
108767  "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
108768  "refargs",       "defer_subclause",  "refarg",        "refact",
108769  "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
108770  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
108771  "ifexists",      "fullname",      "oneselect",     "multiselect_op",
108772  "distinct",      "selcollist",    "from",          "where_opt",
108773  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
108774  "sclp",          "as",            "seltablist",    "stl_prefix",
108775  "joinop",        "indexed_opt",   "on_opt",        "using_opt",
108776  "joinop2",       "inscollist",    "sortlist",      "nexprlist",
108777  "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",
108778  "exprlist",      "likeop",        "between_op",    "in_op",
108779  "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",
108780  "collate",       "nmnum",         "number",        "trigger_decl",
108781  "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
108782  "when_clause",   "trigger_cmd",   "trnm",          "tridxby",
108783  "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
108784  "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
108785  "lp",            "anylist",
108786};
108787#endif /* NDEBUG */
108788
108789#ifndef NDEBUG
108790/* For tracing reduce actions, the names of all rules are required.
108791*/
108792static const char *const yyRuleName[] = {
108793 /*   0 */ "input ::= cmdlist",
108794 /*   1 */ "cmdlist ::= cmdlist ecmd",
108795 /*   2 */ "cmdlist ::= ecmd",
108796 /*   3 */ "ecmd ::= SEMI",
108797 /*   4 */ "ecmd ::= explain cmdx SEMI",
108798 /*   5 */ "explain ::=",
108799 /*   6 */ "explain ::= EXPLAIN",
108800 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
108801 /*   8 */ "cmdx ::= cmd",
108802 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
108803 /*  10 */ "trans_opt ::=",
108804 /*  11 */ "trans_opt ::= TRANSACTION",
108805 /*  12 */ "trans_opt ::= TRANSACTION nm",
108806 /*  13 */ "transtype ::=",
108807 /*  14 */ "transtype ::= DEFERRED",
108808 /*  15 */ "transtype ::= IMMEDIATE",
108809 /*  16 */ "transtype ::= EXCLUSIVE",
108810 /*  17 */ "cmd ::= COMMIT trans_opt",
108811 /*  18 */ "cmd ::= END trans_opt",
108812 /*  19 */ "cmd ::= ROLLBACK trans_opt",
108813 /*  20 */ "savepoint_opt ::= SAVEPOINT",
108814 /*  21 */ "savepoint_opt ::=",
108815 /*  22 */ "cmd ::= SAVEPOINT nm",
108816 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
108817 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
108818 /*  25 */ "cmd ::= create_table create_table_args",
108819 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
108820 /*  27 */ "createkw ::= CREATE",
108821 /*  28 */ "ifnotexists ::=",
108822 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
108823 /*  30 */ "temp ::= TEMP",
108824 /*  31 */ "temp ::=",
108825 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
108826 /*  33 */ "create_table_args ::= AS select",
108827 /*  34 */ "columnlist ::= columnlist COMMA column",
108828 /*  35 */ "columnlist ::= column",
108829 /*  36 */ "column ::= columnid type carglist",
108830 /*  37 */ "columnid ::= nm",
108831 /*  38 */ "id ::= ID",
108832 /*  39 */ "id ::= INDEXED",
108833 /*  40 */ "ids ::= ID|STRING",
108834 /*  41 */ "nm ::= id",
108835 /*  42 */ "nm ::= STRING",
108836 /*  43 */ "nm ::= JOIN_KW",
108837 /*  44 */ "type ::=",
108838 /*  45 */ "type ::= typetoken",
108839 /*  46 */ "typetoken ::= typename",
108840 /*  47 */ "typetoken ::= typename LP signed RP",
108841 /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
108842 /*  49 */ "typename ::= ids",
108843 /*  50 */ "typename ::= typename ids",
108844 /*  51 */ "signed ::= plus_num",
108845 /*  52 */ "signed ::= minus_num",
108846 /*  53 */ "carglist ::= carglist carg",
108847 /*  54 */ "carglist ::=",
108848 /*  55 */ "carg ::= CONSTRAINT nm ccons",
108849 /*  56 */ "carg ::= ccons",
108850 /*  57 */ "ccons ::= DEFAULT term",
108851 /*  58 */ "ccons ::= DEFAULT LP expr RP",
108852 /*  59 */ "ccons ::= DEFAULT PLUS term",
108853 /*  60 */ "ccons ::= DEFAULT MINUS term",
108854 /*  61 */ "ccons ::= DEFAULT id",
108855 /*  62 */ "ccons ::= NULL onconf",
108856 /*  63 */ "ccons ::= NOT NULL onconf",
108857 /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
108858 /*  65 */ "ccons ::= UNIQUE onconf",
108859 /*  66 */ "ccons ::= CHECK LP expr RP",
108860 /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
108861 /*  68 */ "ccons ::= defer_subclause",
108862 /*  69 */ "ccons ::= COLLATE ids",
108863 /*  70 */ "autoinc ::=",
108864 /*  71 */ "autoinc ::= AUTOINCR",
108865 /*  72 */ "refargs ::=",
108866 /*  73 */ "refargs ::= refargs refarg",
108867 /*  74 */ "refarg ::= MATCH nm",
108868 /*  75 */ "refarg ::= ON INSERT refact",
108869 /*  76 */ "refarg ::= ON DELETE refact",
108870 /*  77 */ "refarg ::= ON UPDATE refact",
108871 /*  78 */ "refact ::= SET NULL",
108872 /*  79 */ "refact ::= SET DEFAULT",
108873 /*  80 */ "refact ::= CASCADE",
108874 /*  81 */ "refact ::= RESTRICT",
108875 /*  82 */ "refact ::= NO ACTION",
108876 /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
108877 /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
108878 /*  85 */ "init_deferred_pred_opt ::=",
108879 /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
108880 /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
108881 /*  88 */ "conslist_opt ::=",
108882 /*  89 */ "conslist_opt ::= COMMA conslist",
108883 /*  90 */ "conslist ::= conslist COMMA tcons",
108884 /*  91 */ "conslist ::= conslist tcons",
108885 /*  92 */ "conslist ::= tcons",
108886 /*  93 */ "tcons ::= CONSTRAINT nm",
108887 /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
108888 /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
108889 /*  96 */ "tcons ::= CHECK LP expr RP onconf",
108890 /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
108891 /*  98 */ "defer_subclause_opt ::=",
108892 /*  99 */ "defer_subclause_opt ::= defer_subclause",
108893 /* 100 */ "onconf ::=",
108894 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
108895 /* 102 */ "orconf ::=",
108896 /* 103 */ "orconf ::= OR resolvetype",
108897 /* 104 */ "resolvetype ::= raisetype",
108898 /* 105 */ "resolvetype ::= IGNORE",
108899 /* 106 */ "resolvetype ::= REPLACE",
108900 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
108901 /* 108 */ "ifexists ::= IF EXISTS",
108902 /* 109 */ "ifexists ::=",
108903 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
108904 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
108905 /* 112 */ "cmd ::= select",
108906 /* 113 */ "select ::= oneselect",
108907 /* 114 */ "select ::= select multiselect_op oneselect",
108908 /* 115 */ "multiselect_op ::= UNION",
108909 /* 116 */ "multiselect_op ::= UNION ALL",
108910 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
108911 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
108912 /* 119 */ "distinct ::= DISTINCT",
108913 /* 120 */ "distinct ::= ALL",
108914 /* 121 */ "distinct ::=",
108915 /* 122 */ "sclp ::= selcollist COMMA",
108916 /* 123 */ "sclp ::=",
108917 /* 124 */ "selcollist ::= sclp expr as",
108918 /* 125 */ "selcollist ::= sclp STAR",
108919 /* 126 */ "selcollist ::= sclp nm DOT STAR",
108920 /* 127 */ "as ::= AS nm",
108921 /* 128 */ "as ::= ids",
108922 /* 129 */ "as ::=",
108923 /* 130 */ "from ::=",
108924 /* 131 */ "from ::= FROM seltablist",
108925 /* 132 */ "stl_prefix ::= seltablist joinop",
108926 /* 133 */ "stl_prefix ::=",
108927 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
108928 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
108929 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
108930 /* 137 */ "dbnm ::=",
108931 /* 138 */ "dbnm ::= DOT nm",
108932 /* 139 */ "fullname ::= nm dbnm",
108933 /* 140 */ "joinop ::= COMMA|JOIN",
108934 /* 141 */ "joinop ::= JOIN_KW JOIN",
108935 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
108936 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
108937 /* 144 */ "on_opt ::= ON expr",
108938 /* 145 */ "on_opt ::=",
108939 /* 146 */ "indexed_opt ::=",
108940 /* 147 */ "indexed_opt ::= INDEXED BY nm",
108941 /* 148 */ "indexed_opt ::= NOT INDEXED",
108942 /* 149 */ "using_opt ::= USING LP inscollist RP",
108943 /* 150 */ "using_opt ::=",
108944 /* 151 */ "orderby_opt ::=",
108945 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
108946 /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
108947 /* 154 */ "sortlist ::= expr sortorder",
108948 /* 155 */ "sortorder ::= ASC",
108949 /* 156 */ "sortorder ::= DESC",
108950 /* 157 */ "sortorder ::=",
108951 /* 158 */ "groupby_opt ::=",
108952 /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
108953 /* 160 */ "having_opt ::=",
108954 /* 161 */ "having_opt ::= HAVING expr",
108955 /* 162 */ "limit_opt ::=",
108956 /* 163 */ "limit_opt ::= LIMIT expr",
108957 /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
108958 /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
108959 /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
108960 /* 167 */ "where_opt ::=",
108961 /* 168 */ "where_opt ::= WHERE expr",
108962 /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
108963 /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
108964 /* 171 */ "setlist ::= nm EQ expr",
108965 /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
108966 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
108967 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
108968 /* 175 */ "insert_cmd ::= INSERT orconf",
108969 /* 176 */ "insert_cmd ::= REPLACE",
108970 /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
108971 /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
108972 /* 179 */ "inscollist_opt ::=",
108973 /* 180 */ "inscollist_opt ::= LP inscollist RP",
108974 /* 181 */ "inscollist ::= inscollist COMMA nm",
108975 /* 182 */ "inscollist ::= nm",
108976 /* 183 */ "expr ::= term",
108977 /* 184 */ "expr ::= LP expr RP",
108978 /* 185 */ "term ::= NULL",
108979 /* 186 */ "expr ::= id",
108980 /* 187 */ "expr ::= JOIN_KW",
108981 /* 188 */ "expr ::= nm DOT nm",
108982 /* 189 */ "expr ::= nm DOT nm DOT nm",
108983 /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
108984 /* 191 */ "term ::= STRING",
108985 /* 192 */ "expr ::= REGISTER",
108986 /* 193 */ "expr ::= VARIABLE",
108987 /* 194 */ "expr ::= expr COLLATE ids",
108988 /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
108989 /* 196 */ "expr ::= ID LP distinct exprlist RP",
108990 /* 197 */ "expr ::= ID LP STAR RP",
108991 /* 198 */ "term ::= CTIME_KW",
108992 /* 199 */ "expr ::= expr AND expr",
108993 /* 200 */ "expr ::= expr OR expr",
108994 /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
108995 /* 202 */ "expr ::= expr EQ|NE expr",
108996 /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
108997 /* 204 */ "expr ::= expr PLUS|MINUS expr",
108998 /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
108999 /* 206 */ "expr ::= expr CONCAT expr",
109000 /* 207 */ "likeop ::= LIKE_KW",
109001 /* 208 */ "likeop ::= NOT LIKE_KW",
109002 /* 209 */ "likeop ::= MATCH",
109003 /* 210 */ "likeop ::= NOT MATCH",
109004 /* 211 */ "expr ::= expr likeop expr",
109005 /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
109006 /* 213 */ "expr ::= expr ISNULL|NOTNULL",
109007 /* 214 */ "expr ::= expr NOT NULL",
109008 /* 215 */ "expr ::= expr IS expr",
109009 /* 216 */ "expr ::= expr IS NOT expr",
109010 /* 217 */ "expr ::= NOT expr",
109011 /* 218 */ "expr ::= BITNOT expr",
109012 /* 219 */ "expr ::= MINUS expr",
109013 /* 220 */ "expr ::= PLUS expr",
109014 /* 221 */ "between_op ::= BETWEEN",
109015 /* 222 */ "between_op ::= NOT BETWEEN",
109016 /* 223 */ "expr ::= expr between_op expr AND expr",
109017 /* 224 */ "in_op ::= IN",
109018 /* 225 */ "in_op ::= NOT IN",
109019 /* 226 */ "expr ::= expr in_op LP exprlist RP",
109020 /* 227 */ "expr ::= LP select RP",
109021 /* 228 */ "expr ::= expr in_op LP select RP",
109022 /* 229 */ "expr ::= expr in_op nm dbnm",
109023 /* 230 */ "expr ::= EXISTS LP select RP",
109024 /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
109025 /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
109026 /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
109027 /* 234 */ "case_else ::= ELSE expr",
109028 /* 235 */ "case_else ::=",
109029 /* 236 */ "case_operand ::= expr",
109030 /* 237 */ "case_operand ::=",
109031 /* 238 */ "exprlist ::= nexprlist",
109032 /* 239 */ "exprlist ::=",
109033 /* 240 */ "nexprlist ::= nexprlist COMMA expr",
109034 /* 241 */ "nexprlist ::= expr",
109035 /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
109036 /* 243 */ "uniqueflag ::= UNIQUE",
109037 /* 244 */ "uniqueflag ::=",
109038 /* 245 */ "idxlist_opt ::=",
109039 /* 246 */ "idxlist_opt ::= LP idxlist RP",
109040 /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
109041 /* 248 */ "idxlist ::= nm collate sortorder",
109042 /* 249 */ "collate ::=",
109043 /* 250 */ "collate ::= COLLATE ids",
109044 /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
109045 /* 252 */ "cmd ::= VACUUM",
109046 /* 253 */ "cmd ::= VACUUM nm",
109047 /* 254 */ "cmd ::= PRAGMA nm dbnm",
109048 /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
109049 /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
109050 /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
109051 /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
109052 /* 259 */ "nmnum ::= plus_num",
109053 /* 260 */ "nmnum ::= nm",
109054 /* 261 */ "nmnum ::= ON",
109055 /* 262 */ "nmnum ::= DELETE",
109056 /* 263 */ "nmnum ::= DEFAULT",
109057 /* 264 */ "plus_num ::= PLUS number",
109058 /* 265 */ "plus_num ::= number",
109059 /* 266 */ "minus_num ::= MINUS number",
109060 /* 267 */ "number ::= INTEGER|FLOAT",
109061 /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
109062 /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
109063 /* 270 */ "trigger_time ::= BEFORE",
109064 /* 271 */ "trigger_time ::= AFTER",
109065 /* 272 */ "trigger_time ::= INSTEAD OF",
109066 /* 273 */ "trigger_time ::=",
109067 /* 274 */ "trigger_event ::= DELETE|INSERT",
109068 /* 275 */ "trigger_event ::= UPDATE",
109069 /* 276 */ "trigger_event ::= UPDATE OF inscollist",
109070 /* 277 */ "foreach_clause ::=",
109071 /* 278 */ "foreach_clause ::= FOR EACH ROW",
109072 /* 279 */ "when_clause ::=",
109073 /* 280 */ "when_clause ::= WHEN expr",
109074 /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
109075 /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
109076 /* 283 */ "trnm ::= nm",
109077 /* 284 */ "trnm ::= nm DOT nm",
109078 /* 285 */ "tridxby ::=",
109079 /* 286 */ "tridxby ::= INDEXED BY nm",
109080 /* 287 */ "tridxby ::= NOT INDEXED",
109081 /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
109082 /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
109083 /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
109084 /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
109085 /* 292 */ "trigger_cmd ::= select",
109086 /* 293 */ "expr ::= RAISE LP IGNORE RP",
109087 /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
109088 /* 295 */ "raisetype ::= ROLLBACK",
109089 /* 296 */ "raisetype ::= ABORT",
109090 /* 297 */ "raisetype ::= FAIL",
109091 /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
109092 /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
109093 /* 300 */ "cmd ::= DETACH database_kw_opt expr",
109094 /* 301 */ "key_opt ::=",
109095 /* 302 */ "key_opt ::= KEY expr",
109096 /* 303 */ "database_kw_opt ::= DATABASE",
109097 /* 304 */ "database_kw_opt ::=",
109098 /* 305 */ "cmd ::= REINDEX",
109099 /* 306 */ "cmd ::= REINDEX nm dbnm",
109100 /* 307 */ "cmd ::= ANALYZE",
109101 /* 308 */ "cmd ::= ANALYZE nm dbnm",
109102 /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
109103 /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
109104 /* 311 */ "add_column_fullname ::= fullname",
109105 /* 312 */ "kwcolumn_opt ::=",
109106 /* 313 */ "kwcolumn_opt ::= COLUMNKW",
109107 /* 314 */ "cmd ::= create_vtab",
109108 /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
109109 /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
109110 /* 317 */ "vtabarglist ::= vtabarg",
109111 /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
109112 /* 319 */ "vtabarg ::=",
109113 /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
109114 /* 321 */ "vtabargtoken ::= ANY",
109115 /* 322 */ "vtabargtoken ::= lp anylist RP",
109116 /* 323 */ "lp ::= LP",
109117 /* 324 */ "anylist ::=",
109118 /* 325 */ "anylist ::= anylist LP anylist RP",
109119 /* 326 */ "anylist ::= anylist ANY",
109120};
109121#endif /* NDEBUG */
109122
109123
109124#if YYSTACKDEPTH<=0
109125/*
109126** Try to increase the size of the parser stack.
109127*/
109128static void yyGrowStack(yyParser *p){
109129  int newSize;
109130  yyStackEntry *pNew;
109131
109132  newSize = p->yystksz*2 + 100;
109133  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
109134  if( pNew ){
109135    p->yystack = pNew;
109136    p->yystksz = newSize;
109137#ifndef NDEBUG
109138    if( yyTraceFILE ){
109139      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
109140              yyTracePrompt, p->yystksz);
109141    }
109142#endif
109143  }
109144}
109145#endif
109146
109147/*
109148** This function allocates a new parser.
109149** The only argument is a pointer to a function which works like
109150** malloc.
109151**
109152** Inputs:
109153** A pointer to the function used to allocate memory.
109154**
109155** Outputs:
109156** A pointer to a parser.  This pointer is used in subsequent calls
109157** to sqlite3Parser and sqlite3ParserFree.
109158*/
109159SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
109160  yyParser *pParser;
109161  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
109162  if( pParser ){
109163    pParser->yyidx = -1;
109164#ifdef YYTRACKMAXSTACKDEPTH
109165    pParser->yyidxMax = 0;
109166#endif
109167#if YYSTACKDEPTH<=0
109168    pParser->yystack = NULL;
109169    pParser->yystksz = 0;
109170    yyGrowStack(pParser);
109171#endif
109172  }
109173  return pParser;
109174}
109175
109176/* The following function deletes the value associated with a
109177** symbol.  The symbol can be either a terminal or nonterminal.
109178** "yymajor" is the symbol code, and "yypminor" is a pointer to
109179** the value.
109180*/
109181static void yy_destructor(
109182  yyParser *yypParser,    /* The parser */
109183  YYCODETYPE yymajor,     /* Type code for object to destroy */
109184  YYMINORTYPE *yypminor   /* The object to be destroyed */
109185){
109186  sqlite3ParserARG_FETCH;
109187  switch( yymajor ){
109188    /* Here is inserted the actions which take place when a
109189    ** terminal or non-terminal is destroyed.  This can happen
109190    ** when the symbol is popped from the stack during a
109191    ** reduce or during error processing or when a parser is
109192    ** being destroyed before it is finished parsing.
109193    **
109194    ** Note: during a reduce, the only symbols destroyed are those
109195    ** which appear on the RHS of the rule, but which are not used
109196    ** inside the C code.
109197    */
109198    case 160: /* select */
109199    case 194: /* oneselect */
109200{
109201sqlite3SelectDelete(pParse->db, (yypminor->yy159));
109202}
109203      break;
109204    case 174: /* term */
109205    case 175: /* expr */
109206{
109207sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
109208}
109209      break;
109210    case 179: /* idxlist_opt */
109211    case 187: /* idxlist */
109212    case 197: /* selcollist */
109213    case 200: /* groupby_opt */
109214    case 202: /* orderby_opt */
109215    case 204: /* sclp */
109216    case 214: /* sortlist */
109217    case 215: /* nexprlist */
109218    case 216: /* setlist */
109219    case 220: /* exprlist */
109220    case 225: /* case_exprlist */
109221{
109222sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
109223}
109224      break;
109225    case 193: /* fullname */
109226    case 198: /* from */
109227    case 206: /* seltablist */
109228    case 207: /* stl_prefix */
109229{
109230sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
109231}
109232      break;
109233    case 199: /* where_opt */
109234    case 201: /* having_opt */
109235    case 210: /* on_opt */
109236    case 224: /* case_operand */
109237    case 226: /* case_else */
109238    case 236: /* when_clause */
109239    case 241: /* key_opt */
109240{
109241sqlite3ExprDelete(pParse->db, (yypminor->yy122));
109242}
109243      break;
109244    case 211: /* using_opt */
109245    case 213: /* inscollist */
109246    case 218: /* inscollist_opt */
109247{
109248sqlite3IdListDelete(pParse->db, (yypminor->yy180));
109249}
109250      break;
109251    case 219: /* valuelist */
109252{
109253
109254  sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
109255  sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
109256
109257}
109258      break;
109259    case 232: /* trigger_cmd_list */
109260    case 237: /* trigger_cmd */
109261{
109262sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
109263}
109264      break;
109265    case 234: /* trigger_event */
109266{
109267sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
109268}
109269      break;
109270    default:  break;   /* If no destructor action specified: do nothing */
109271  }
109272}
109273
109274/*
109275** Pop the parser's stack once.
109276**
109277** If there is a destructor routine associated with the token which
109278** is popped from the stack, then call it.
109279**
109280** Return the major token number for the symbol popped.
109281*/
109282static int yy_pop_parser_stack(yyParser *pParser){
109283  YYCODETYPE yymajor;
109284  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
109285
109286  /* There is no mechanism by which the parser stack can be popped below
109287  ** empty in SQLite.  */
109288  if( NEVER(pParser->yyidx<0) ) return 0;
109289#ifndef NDEBUG
109290  if( yyTraceFILE && pParser->yyidx>=0 ){
109291    fprintf(yyTraceFILE,"%sPopping %s\n",
109292      yyTracePrompt,
109293      yyTokenName[yytos->major]);
109294  }
109295#endif
109296  yymajor = yytos->major;
109297  yy_destructor(pParser, yymajor, &yytos->minor);
109298  pParser->yyidx--;
109299  return yymajor;
109300}
109301
109302/*
109303** Deallocate and destroy a parser.  Destructors are all called for
109304** all stack elements before shutting the parser down.
109305**
109306** Inputs:
109307** <ul>
109308** <li>  A pointer to the parser.  This should be a pointer
109309**       obtained from sqlite3ParserAlloc.
109310** <li>  A pointer to a function used to reclaim memory obtained
109311**       from malloc.
109312** </ul>
109313*/
109314SQLITE_PRIVATE void sqlite3ParserFree(
109315  void *p,                    /* The parser to be deleted */
109316  void (*freeProc)(void*)     /* Function used to reclaim memory */
109317){
109318  yyParser *pParser = (yyParser*)p;
109319  /* In SQLite, we never try to destroy a parser that was not successfully
109320  ** created in the first place. */
109321  if( NEVER(pParser==0) ) return;
109322  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
109323#if YYSTACKDEPTH<=0
109324  free(pParser->yystack);
109325#endif
109326  (*freeProc)((void*)pParser);
109327}
109328
109329/*
109330** Return the peak depth of the stack for a parser.
109331*/
109332#ifdef YYTRACKMAXSTACKDEPTH
109333SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
109334  yyParser *pParser = (yyParser*)p;
109335  return pParser->yyidxMax;
109336}
109337#endif
109338
109339/*
109340** Find the appropriate action for a parser given the terminal
109341** look-ahead token iLookAhead.
109342**
109343** If the look-ahead token is YYNOCODE, then check to see if the action is
109344** independent of the look-ahead.  If it is, return the action, otherwise
109345** return YY_NO_ACTION.
109346*/
109347static int yy_find_shift_action(
109348  yyParser *pParser,        /* The parser */
109349  YYCODETYPE iLookAhead     /* The look-ahead token */
109350){
109351  int i;
109352  int stateno = pParser->yystack[pParser->yyidx].stateno;
109353
109354  if( stateno>YY_SHIFT_COUNT
109355   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
109356    return yy_default[stateno];
109357  }
109358  assert( iLookAhead!=YYNOCODE );
109359  i += iLookAhead;
109360  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
109361    if( iLookAhead>0 ){
109362#ifdef YYFALLBACK
109363      YYCODETYPE iFallback;            /* Fallback token */
109364      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
109365             && (iFallback = yyFallback[iLookAhead])!=0 ){
109366#ifndef NDEBUG
109367        if( yyTraceFILE ){
109368          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
109369             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
109370        }
109371#endif
109372        return yy_find_shift_action(pParser, iFallback);
109373      }
109374#endif
109375#ifdef YYWILDCARD
109376      {
109377        int j = i - iLookAhead + YYWILDCARD;
109378        if(
109379#if YY_SHIFT_MIN+YYWILDCARD<0
109380          j>=0 &&
109381#endif
109382#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
109383          j<YY_ACTTAB_COUNT &&
109384#endif
109385          yy_lookahead[j]==YYWILDCARD
109386        ){
109387#ifndef NDEBUG
109388          if( yyTraceFILE ){
109389            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
109390               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
109391          }
109392#endif /* NDEBUG */
109393          return yy_action[j];
109394        }
109395      }
109396#endif /* YYWILDCARD */
109397    }
109398    return yy_default[stateno];
109399  }else{
109400    return yy_action[i];
109401  }
109402}
109403
109404/*
109405** Find the appropriate action for a parser given the non-terminal
109406** look-ahead token iLookAhead.
109407**
109408** If the look-ahead token is YYNOCODE, then check to see if the action is
109409** independent of the look-ahead.  If it is, return the action, otherwise
109410** return YY_NO_ACTION.
109411*/
109412static int yy_find_reduce_action(
109413  int stateno,              /* Current state number */
109414  YYCODETYPE iLookAhead     /* The look-ahead token */
109415){
109416  int i;
109417#ifdef YYERRORSYMBOL
109418  if( stateno>YY_REDUCE_COUNT ){
109419    return yy_default[stateno];
109420  }
109421#else
109422  assert( stateno<=YY_REDUCE_COUNT );
109423#endif
109424  i = yy_reduce_ofst[stateno];
109425  assert( i!=YY_REDUCE_USE_DFLT );
109426  assert( iLookAhead!=YYNOCODE );
109427  i += iLookAhead;
109428#ifdef YYERRORSYMBOL
109429  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
109430    return yy_default[stateno];
109431  }
109432#else
109433  assert( i>=0 && i<YY_ACTTAB_COUNT );
109434  assert( yy_lookahead[i]==iLookAhead );
109435#endif
109436  return yy_action[i];
109437}
109438
109439/*
109440** The following routine is called if the stack overflows.
109441*/
109442static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
109443   sqlite3ParserARG_FETCH;
109444   yypParser->yyidx--;
109445#ifndef NDEBUG
109446   if( yyTraceFILE ){
109447     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
109448   }
109449#endif
109450   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
109451   /* Here code is inserted which will execute if the parser
109452   ** stack every overflows */
109453
109454  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
109455  sqlite3ErrorMsg(pParse, "parser stack overflow");
109456   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
109457}
109458
109459/*
109460** Perform a shift action.
109461*/
109462static void yy_shift(
109463  yyParser *yypParser,          /* The parser to be shifted */
109464  int yyNewState,               /* The new state to shift in */
109465  int yyMajor,                  /* The major token to shift in */
109466  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
109467){
109468  yyStackEntry *yytos;
109469  yypParser->yyidx++;
109470#ifdef YYTRACKMAXSTACKDEPTH
109471  if( yypParser->yyidx>yypParser->yyidxMax ){
109472    yypParser->yyidxMax = yypParser->yyidx;
109473  }
109474#endif
109475#if YYSTACKDEPTH>0
109476  if( yypParser->yyidx>=YYSTACKDEPTH ){
109477    yyStackOverflow(yypParser, yypMinor);
109478    return;
109479  }
109480#else
109481  if( yypParser->yyidx>=yypParser->yystksz ){
109482    yyGrowStack(yypParser);
109483    if( yypParser->yyidx>=yypParser->yystksz ){
109484      yyStackOverflow(yypParser, yypMinor);
109485      return;
109486    }
109487  }
109488#endif
109489  yytos = &yypParser->yystack[yypParser->yyidx];
109490  yytos->stateno = (YYACTIONTYPE)yyNewState;
109491  yytos->major = (YYCODETYPE)yyMajor;
109492  yytos->minor = *yypMinor;
109493#ifndef NDEBUG
109494  if( yyTraceFILE && yypParser->yyidx>0 ){
109495    int i;
109496    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
109497    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
109498    for(i=1; i<=yypParser->yyidx; i++)
109499      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
109500    fprintf(yyTraceFILE,"\n");
109501  }
109502#endif
109503}
109504
109505/* The following table contains information about every rule that
109506** is used during the reduce.
109507*/
109508static const struct {
109509  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
109510  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
109511} yyRuleInfo[] = {
109512  { 142, 1 },
109513  { 143, 2 },
109514  { 143, 1 },
109515  { 144, 1 },
109516  { 144, 3 },
109517  { 145, 0 },
109518  { 145, 1 },
109519  { 145, 3 },
109520  { 146, 1 },
109521  { 147, 3 },
109522  { 149, 0 },
109523  { 149, 1 },
109524  { 149, 2 },
109525  { 148, 0 },
109526  { 148, 1 },
109527  { 148, 1 },
109528  { 148, 1 },
109529  { 147, 2 },
109530  { 147, 2 },
109531  { 147, 2 },
109532  { 151, 1 },
109533  { 151, 0 },
109534  { 147, 2 },
109535  { 147, 3 },
109536  { 147, 5 },
109537  { 147, 2 },
109538  { 152, 6 },
109539  { 154, 1 },
109540  { 156, 0 },
109541  { 156, 3 },
109542  { 155, 1 },
109543  { 155, 0 },
109544  { 153, 4 },
109545  { 153, 2 },
109546  { 158, 3 },
109547  { 158, 1 },
109548  { 161, 3 },
109549  { 162, 1 },
109550  { 165, 1 },
109551  { 165, 1 },
109552  { 166, 1 },
109553  { 150, 1 },
109554  { 150, 1 },
109555  { 150, 1 },
109556  { 163, 0 },
109557  { 163, 1 },
109558  { 167, 1 },
109559  { 167, 4 },
109560  { 167, 6 },
109561  { 168, 1 },
109562  { 168, 2 },
109563  { 169, 1 },
109564  { 169, 1 },
109565  { 164, 2 },
109566  { 164, 0 },
109567  { 172, 3 },
109568  { 172, 1 },
109569  { 173, 2 },
109570  { 173, 4 },
109571  { 173, 3 },
109572  { 173, 3 },
109573  { 173, 2 },
109574  { 173, 2 },
109575  { 173, 3 },
109576  { 173, 5 },
109577  { 173, 2 },
109578  { 173, 4 },
109579  { 173, 4 },
109580  { 173, 1 },
109581  { 173, 2 },
109582  { 178, 0 },
109583  { 178, 1 },
109584  { 180, 0 },
109585  { 180, 2 },
109586  { 182, 2 },
109587  { 182, 3 },
109588  { 182, 3 },
109589  { 182, 3 },
109590  { 183, 2 },
109591  { 183, 2 },
109592  { 183, 1 },
109593  { 183, 1 },
109594  { 183, 2 },
109595  { 181, 3 },
109596  { 181, 2 },
109597  { 184, 0 },
109598  { 184, 2 },
109599  { 184, 2 },
109600  { 159, 0 },
109601  { 159, 2 },
109602  { 185, 3 },
109603  { 185, 2 },
109604  { 185, 1 },
109605  { 186, 2 },
109606  { 186, 7 },
109607  { 186, 5 },
109608  { 186, 5 },
109609  { 186, 10 },
109610  { 188, 0 },
109611  { 188, 1 },
109612  { 176, 0 },
109613  { 176, 3 },
109614  { 189, 0 },
109615  { 189, 2 },
109616  { 190, 1 },
109617  { 190, 1 },
109618  { 190, 1 },
109619  { 147, 4 },
109620  { 192, 2 },
109621  { 192, 0 },
109622  { 147, 8 },
109623  { 147, 4 },
109624  { 147, 1 },
109625  { 160, 1 },
109626  { 160, 3 },
109627  { 195, 1 },
109628  { 195, 2 },
109629  { 195, 1 },
109630  { 194, 9 },
109631  { 196, 1 },
109632  { 196, 1 },
109633  { 196, 0 },
109634  { 204, 2 },
109635  { 204, 0 },
109636  { 197, 3 },
109637  { 197, 2 },
109638  { 197, 4 },
109639  { 205, 2 },
109640  { 205, 1 },
109641  { 205, 0 },
109642  { 198, 0 },
109643  { 198, 2 },
109644  { 207, 2 },
109645  { 207, 0 },
109646  { 206, 7 },
109647  { 206, 7 },
109648  { 206, 7 },
109649  { 157, 0 },
109650  { 157, 2 },
109651  { 193, 2 },
109652  { 208, 1 },
109653  { 208, 2 },
109654  { 208, 3 },
109655  { 208, 4 },
109656  { 210, 2 },
109657  { 210, 0 },
109658  { 209, 0 },
109659  { 209, 3 },
109660  { 209, 2 },
109661  { 211, 4 },
109662  { 211, 0 },
109663  { 202, 0 },
109664  { 202, 3 },
109665  { 214, 4 },
109666  { 214, 2 },
109667  { 177, 1 },
109668  { 177, 1 },
109669  { 177, 0 },
109670  { 200, 0 },
109671  { 200, 3 },
109672  { 201, 0 },
109673  { 201, 2 },
109674  { 203, 0 },
109675  { 203, 2 },
109676  { 203, 4 },
109677  { 203, 4 },
109678  { 147, 5 },
109679  { 199, 0 },
109680  { 199, 2 },
109681  { 147, 7 },
109682  { 216, 5 },
109683  { 216, 3 },
109684  { 147, 5 },
109685  { 147, 5 },
109686  { 147, 6 },
109687  { 217, 2 },
109688  { 217, 1 },
109689  { 219, 4 },
109690  { 219, 5 },
109691  { 218, 0 },
109692  { 218, 3 },
109693  { 213, 3 },
109694  { 213, 1 },
109695  { 175, 1 },
109696  { 175, 3 },
109697  { 174, 1 },
109698  { 175, 1 },
109699  { 175, 1 },
109700  { 175, 3 },
109701  { 175, 5 },
109702  { 174, 1 },
109703  { 174, 1 },
109704  { 175, 1 },
109705  { 175, 1 },
109706  { 175, 3 },
109707  { 175, 6 },
109708  { 175, 5 },
109709  { 175, 4 },
109710  { 174, 1 },
109711  { 175, 3 },
109712  { 175, 3 },
109713  { 175, 3 },
109714  { 175, 3 },
109715  { 175, 3 },
109716  { 175, 3 },
109717  { 175, 3 },
109718  { 175, 3 },
109719  { 221, 1 },
109720  { 221, 2 },
109721  { 221, 1 },
109722  { 221, 2 },
109723  { 175, 3 },
109724  { 175, 5 },
109725  { 175, 2 },
109726  { 175, 3 },
109727  { 175, 3 },
109728  { 175, 4 },
109729  { 175, 2 },
109730  { 175, 2 },
109731  { 175, 2 },
109732  { 175, 2 },
109733  { 222, 1 },
109734  { 222, 2 },
109735  { 175, 5 },
109736  { 223, 1 },
109737  { 223, 2 },
109738  { 175, 5 },
109739  { 175, 3 },
109740  { 175, 5 },
109741  { 175, 4 },
109742  { 175, 4 },
109743  { 175, 5 },
109744  { 225, 5 },
109745  { 225, 4 },
109746  { 226, 2 },
109747  { 226, 0 },
109748  { 224, 1 },
109749  { 224, 0 },
109750  { 220, 1 },
109751  { 220, 0 },
109752  { 215, 3 },
109753  { 215, 1 },
109754  { 147, 11 },
109755  { 227, 1 },
109756  { 227, 0 },
109757  { 179, 0 },
109758  { 179, 3 },
109759  { 187, 5 },
109760  { 187, 3 },
109761  { 228, 0 },
109762  { 228, 2 },
109763  { 147, 4 },
109764  { 147, 1 },
109765  { 147, 2 },
109766  { 147, 3 },
109767  { 147, 5 },
109768  { 147, 6 },
109769  { 147, 5 },
109770  { 147, 6 },
109771  { 229, 1 },
109772  { 229, 1 },
109773  { 229, 1 },
109774  { 229, 1 },
109775  { 229, 1 },
109776  { 170, 2 },
109777  { 170, 1 },
109778  { 171, 2 },
109779  { 230, 1 },
109780  { 147, 5 },
109781  { 231, 11 },
109782  { 233, 1 },
109783  { 233, 1 },
109784  { 233, 2 },
109785  { 233, 0 },
109786  { 234, 1 },
109787  { 234, 1 },
109788  { 234, 3 },
109789  { 235, 0 },
109790  { 235, 3 },
109791  { 236, 0 },
109792  { 236, 2 },
109793  { 232, 3 },
109794  { 232, 2 },
109795  { 238, 1 },
109796  { 238, 3 },
109797  { 239, 0 },
109798  { 239, 3 },
109799  { 239, 2 },
109800  { 237, 7 },
109801  { 237, 5 },
109802  { 237, 5 },
109803  { 237, 5 },
109804  { 237, 1 },
109805  { 175, 4 },
109806  { 175, 6 },
109807  { 191, 1 },
109808  { 191, 1 },
109809  { 191, 1 },
109810  { 147, 4 },
109811  { 147, 6 },
109812  { 147, 3 },
109813  { 241, 0 },
109814  { 241, 2 },
109815  { 240, 1 },
109816  { 240, 0 },
109817  { 147, 1 },
109818  { 147, 3 },
109819  { 147, 1 },
109820  { 147, 3 },
109821  { 147, 6 },
109822  { 147, 6 },
109823  { 242, 1 },
109824  { 243, 0 },
109825  { 243, 1 },
109826  { 147, 1 },
109827  { 147, 4 },
109828  { 244, 8 },
109829  { 245, 1 },
109830  { 245, 3 },
109831  { 246, 0 },
109832  { 246, 2 },
109833  { 247, 1 },
109834  { 247, 3 },
109835  { 248, 1 },
109836  { 249, 0 },
109837  { 249, 4 },
109838  { 249, 2 },
109839};
109840
109841static void yy_accept(yyParser*);  /* Forward Declaration */
109842
109843/*
109844** Perform a reduce action and the shift that must immediately
109845** follow the reduce.
109846*/
109847static void yy_reduce(
109848  yyParser *yypParser,         /* The parser */
109849  int yyruleno                 /* Number of the rule by which to reduce */
109850){
109851  int yygoto;                     /* The next state */
109852  int yyact;                      /* The next action */
109853  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
109854  yyStackEntry *yymsp;            /* The top of the parser's stack */
109855  int yysize;                     /* Amount to pop the stack */
109856  sqlite3ParserARG_FETCH;
109857  yymsp = &yypParser->yystack[yypParser->yyidx];
109858#ifndef NDEBUG
109859  if( yyTraceFILE && yyruleno>=0
109860        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
109861    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
109862      yyRuleName[yyruleno]);
109863  }
109864#endif /* NDEBUG */
109865
109866  /* Silence complaints from purify about yygotominor being uninitialized
109867  ** in some cases when it is copied into the stack after the following
109868  ** switch.  yygotominor is uninitialized when a rule reduces that does
109869  ** not set the value of its left-hand side nonterminal.  Leaving the
109870  ** value of the nonterminal uninitialized is utterly harmless as long
109871  ** as the value is never used.  So really the only thing this code
109872  ** accomplishes is to quieten purify.
109873  **
109874  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
109875  ** without this code, their parser segfaults.  I'm not sure what there
109876  ** parser is doing to make this happen.  This is the second bug report
109877  ** from wireshark this week.  Clearly they are stressing Lemon in ways
109878  ** that it has not been previously stressed...  (SQLite ticket #2172)
109879  */
109880  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
109881  yygotominor = yyzerominor;
109882
109883
109884  switch( yyruleno ){
109885  /* Beginning here are the reduction cases.  A typical example
109886  ** follows:
109887  **   case 0:
109888  **  #line <lineno> <grammarfile>
109889  **     { ... }           // User supplied code
109890  **  #line <lineno> <thisfile>
109891  **     break;
109892  */
109893      case 5: /* explain ::= */
109894{ sqlite3BeginParse(pParse, 0); }
109895        break;
109896      case 6: /* explain ::= EXPLAIN */
109897{ sqlite3BeginParse(pParse, 1); }
109898        break;
109899      case 7: /* explain ::= EXPLAIN QUERY PLAN */
109900{ sqlite3BeginParse(pParse, 2); }
109901        break;
109902      case 8: /* cmdx ::= cmd */
109903{ sqlite3FinishCoding(pParse); }
109904        break;
109905      case 9: /* cmd ::= BEGIN transtype trans_opt */
109906{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
109907        break;
109908      case 13: /* transtype ::= */
109909{yygotominor.yy392 = TK_DEFERRED;}
109910        break;
109911      case 14: /* transtype ::= DEFERRED */
109912      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
109913      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
109914      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
109915      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
109916{yygotominor.yy392 = yymsp[0].major;}
109917        break;
109918      case 17: /* cmd ::= COMMIT trans_opt */
109919      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
109920{sqlite3CommitTransaction(pParse);}
109921        break;
109922      case 19: /* cmd ::= ROLLBACK trans_opt */
109923{sqlite3RollbackTransaction(pParse);}
109924        break;
109925      case 22: /* cmd ::= SAVEPOINT nm */
109926{
109927  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
109928}
109929        break;
109930      case 23: /* cmd ::= RELEASE savepoint_opt nm */
109931{
109932  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
109933}
109934        break;
109935      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
109936{
109937  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
109938}
109939        break;
109940      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
109941{
109942   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
109943}
109944        break;
109945      case 27: /* createkw ::= CREATE */
109946{
109947  pParse->db->lookaside.bEnabled = 0;
109948  yygotominor.yy0 = yymsp[0].minor.yy0;
109949}
109950        break;
109951      case 28: /* ifnotexists ::= */
109952      case 31: /* temp ::= */ yytestcase(yyruleno==31);
109953      case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
109954      case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
109955      case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
109956      case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
109957      case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
109958      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
109959      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
109960      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
109961      case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
109962      case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
109963{yygotominor.yy392 = 0;}
109964        break;
109965      case 29: /* ifnotexists ::= IF NOT EXISTS */
109966      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
109967      case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
109968      case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
109969      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
109970      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
109971      case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
109972      case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
109973{yygotominor.yy392 = 1;}
109974        break;
109975      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
109976{
109977  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
109978}
109979        break;
109980      case 33: /* create_table_args ::= AS select */
109981{
109982  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
109983  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
109984}
109985        break;
109986      case 36: /* column ::= columnid type carglist */
109987{
109988  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
109989  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
109990}
109991        break;
109992      case 37: /* columnid ::= nm */
109993{
109994  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
109995  yygotominor.yy0 = yymsp[0].minor.yy0;
109996}
109997        break;
109998      case 38: /* id ::= ID */
109999      case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
110000      case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
110001      case 41: /* nm ::= id */ yytestcase(yyruleno==41);
110002      case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
110003      case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
110004      case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
110005      case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
110006      case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
110007      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
110008      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
110009      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
110010      case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
110011      case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
110012      case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
110013      case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
110014      case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
110015      case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
110016      case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
110017      case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
110018      case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
110019      case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
110020      case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
110021{yygotominor.yy0 = yymsp[0].minor.yy0;}
110022        break;
110023      case 45: /* type ::= typetoken */
110024{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
110025        break;
110026      case 47: /* typetoken ::= typename LP signed RP */
110027{
110028  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
110029  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
110030}
110031        break;
110032      case 48: /* typetoken ::= typename LP signed COMMA signed RP */
110033{
110034  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
110035  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
110036}
110037        break;
110038      case 50: /* typename ::= typename ids */
110039{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);}
110040        break;
110041      case 57: /* ccons ::= DEFAULT term */
110042      case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
110043{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
110044        break;
110045      case 58: /* ccons ::= DEFAULT LP expr RP */
110046{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
110047        break;
110048      case 60: /* ccons ::= DEFAULT MINUS term */
110049{
110050  ExprSpan v;
110051  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
110052  v.zStart = yymsp[-1].minor.yy0.z;
110053  v.zEnd = yymsp[0].minor.yy342.zEnd;
110054  sqlite3AddDefaultValue(pParse,&v);
110055}
110056        break;
110057      case 61: /* ccons ::= DEFAULT id */
110058{
110059  ExprSpan v;
110060  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
110061  sqlite3AddDefaultValue(pParse,&v);
110062}
110063        break;
110064      case 63: /* ccons ::= NOT NULL onconf */
110065{sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
110066        break;
110067      case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
110068{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
110069        break;
110070      case 65: /* ccons ::= UNIQUE onconf */
110071{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
110072        break;
110073      case 66: /* ccons ::= CHECK LP expr RP */
110074{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
110075        break;
110076      case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
110077{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
110078        break;
110079      case 68: /* ccons ::= defer_subclause */
110080{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
110081        break;
110082      case 69: /* ccons ::= COLLATE ids */
110083{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
110084        break;
110085      case 72: /* refargs ::= */
110086{ yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
110087        break;
110088      case 73: /* refargs ::= refargs refarg */
110089{ yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
110090        break;
110091      case 74: /* refarg ::= MATCH nm */
110092      case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
110093{ yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
110094        break;
110095      case 76: /* refarg ::= ON DELETE refact */
110096{ yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
110097        break;
110098      case 77: /* refarg ::= ON UPDATE refact */
110099{ yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
110100        break;
110101      case 78: /* refact ::= SET NULL */
110102{ yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
110103        break;
110104      case 79: /* refact ::= SET DEFAULT */
110105{ yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
110106        break;
110107      case 80: /* refact ::= CASCADE */
110108{ yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
110109        break;
110110      case 81: /* refact ::= RESTRICT */
110111{ yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
110112        break;
110113      case 82: /* refact ::= NO ACTION */
110114{ yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
110115        break;
110116      case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
110117      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
110118      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
110119      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
110120{yygotominor.yy392 = yymsp[0].minor.yy392;}
110121        break;
110122      case 88: /* conslist_opt ::= */
110123{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
110124        break;
110125      case 89: /* conslist_opt ::= COMMA conslist */
110126{yygotominor.yy0 = yymsp[-1].minor.yy0;}
110127        break;
110128      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
110129{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
110130        break;
110131      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
110132{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
110133        break;
110134      case 96: /* tcons ::= CHECK LP expr RP onconf */
110135{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
110136        break;
110137      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
110138{
110139    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
110140    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
110141}
110142        break;
110143      case 100: /* onconf ::= */
110144{yygotominor.yy392 = OE_Default;}
110145        break;
110146      case 102: /* orconf ::= */
110147{yygotominor.yy258 = OE_Default;}
110148        break;
110149      case 103: /* orconf ::= OR resolvetype */
110150{yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
110151        break;
110152      case 105: /* resolvetype ::= IGNORE */
110153{yygotominor.yy392 = OE_Ignore;}
110154        break;
110155      case 106: /* resolvetype ::= REPLACE */
110156{yygotominor.yy392 = OE_Replace;}
110157        break;
110158      case 107: /* cmd ::= DROP TABLE ifexists fullname */
110159{
110160  sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
110161}
110162        break;
110163      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
110164{
110165  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);
110166}
110167        break;
110168      case 111: /* cmd ::= DROP VIEW ifexists fullname */
110169{
110170  sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
110171}
110172        break;
110173      case 112: /* cmd ::= select */
110174{
110175  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
110176  sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
110177  sqlite3ExplainBegin(pParse->pVdbe);
110178  sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
110179  sqlite3ExplainFinish(pParse->pVdbe);
110180  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
110181}
110182        break;
110183      case 113: /* select ::= oneselect */
110184{yygotominor.yy159 = yymsp[0].minor.yy159;}
110185        break;
110186      case 114: /* select ::= select multiselect_op oneselect */
110187{
110188  if( yymsp[0].minor.yy159 ){
110189    yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
110190    yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
110191  }else{
110192    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
110193  }
110194  yygotominor.yy159 = yymsp[0].minor.yy159;
110195}
110196        break;
110197      case 116: /* multiselect_op ::= UNION ALL */
110198{yygotominor.yy392 = TK_ALL;}
110199        break;
110200      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
110201{
110202  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.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
110203}
110204        break;
110205      case 122: /* sclp ::= selcollist COMMA */
110206      case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
110207{yygotominor.yy442 = yymsp[-1].minor.yy442;}
110208        break;
110209      case 123: /* sclp ::= */
110210      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
110211      case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
110212      case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
110213      case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
110214{yygotominor.yy442 = 0;}
110215        break;
110216      case 124: /* selcollist ::= sclp expr as */
110217{
110218   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
110219   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
110220   sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
110221}
110222        break;
110223      case 125: /* selcollist ::= sclp STAR */
110224{
110225  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
110226  yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
110227}
110228        break;
110229      case 126: /* selcollist ::= sclp nm DOT STAR */
110230{
110231  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
110232  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
110233  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
110234  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
110235}
110236        break;
110237      case 129: /* as ::= */
110238{yygotominor.yy0.n = 0;}
110239        break;
110240      case 130: /* from ::= */
110241{yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
110242        break;
110243      case 131: /* from ::= FROM seltablist */
110244{
110245  yygotominor.yy347 = yymsp[0].minor.yy347;
110246  sqlite3SrcListShiftJoinType(yygotominor.yy347);
110247}
110248        break;
110249      case 132: /* stl_prefix ::= seltablist joinop */
110250{
110251   yygotominor.yy347 = yymsp[-1].minor.yy347;
110252   if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
110253}
110254        break;
110255      case 133: /* stl_prefix ::= */
110256{yygotominor.yy347 = 0;}
110257        break;
110258      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
110259{
110260  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);
110261  sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
110262}
110263        break;
110264      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
110265{
110266    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);
110267  }
110268        break;
110269      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
110270{
110271    if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
110272      yygotominor.yy347 = yymsp[-4].minor.yy347;
110273    }else{
110274      Select *pSubquery;
110275      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
110276      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);
110277      yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
110278    }
110279  }
110280        break;
110281      case 137: /* dbnm ::= */
110282      case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
110283{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
110284        break;
110285      case 139: /* fullname ::= nm dbnm */
110286{yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
110287        break;
110288      case 140: /* joinop ::= COMMA|JOIN */
110289{ yygotominor.yy392 = JT_INNER; }
110290        break;
110291      case 141: /* joinop ::= JOIN_KW JOIN */
110292{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
110293        break;
110294      case 142: /* joinop ::= JOIN_KW nm JOIN */
110295{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
110296        break;
110297      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
110298{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
110299        break;
110300      case 144: /* on_opt ::= ON expr */
110301      case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
110302      case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
110303      case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
110304      case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
110305{yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
110306        break;
110307      case 145: /* on_opt ::= */
110308      case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
110309      case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
110310      case 235: /* case_else ::= */ yytestcase(yyruleno==235);
110311      case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
110312{yygotominor.yy122 = 0;}
110313        break;
110314      case 148: /* indexed_opt ::= NOT INDEXED */
110315{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
110316        break;
110317      case 149: /* using_opt ::= USING LP inscollist RP */
110318      case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
110319{yygotominor.yy180 = yymsp[-1].minor.yy180;}
110320        break;
110321      case 150: /* using_opt ::= */
110322      case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
110323{yygotominor.yy180 = 0;}
110324        break;
110325      case 152: /* orderby_opt ::= ORDER BY sortlist */
110326      case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
110327      case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
110328{yygotominor.yy442 = yymsp[0].minor.yy442;}
110329        break;
110330      case 153: /* sortlist ::= sortlist COMMA expr sortorder */
110331{
110332  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
110333  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
110334}
110335        break;
110336      case 154: /* sortlist ::= expr sortorder */
110337{
110338  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
110339  if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
110340}
110341        break;
110342      case 155: /* sortorder ::= ASC */
110343      case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
110344{yygotominor.yy392 = SQLITE_SO_ASC;}
110345        break;
110346      case 156: /* sortorder ::= DESC */
110347{yygotominor.yy392 = SQLITE_SO_DESC;}
110348        break;
110349      case 162: /* limit_opt ::= */
110350{yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
110351        break;
110352      case 163: /* limit_opt ::= LIMIT expr */
110353{yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
110354        break;
110355      case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
110356{yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
110357        break;
110358      case 165: /* limit_opt ::= LIMIT expr COMMA expr */
110359{yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
110360        break;
110361      case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
110362{
110363  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
110364  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
110365}
110366        break;
110367      case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
110368{
110369  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
110370  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
110371  sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
110372}
110373        break;
110374      case 170: /* setlist ::= setlist COMMA nm EQ expr */
110375{
110376  yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
110377  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
110378}
110379        break;
110380      case 171: /* setlist ::= nm EQ expr */
110381{
110382  yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
110383  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
110384}
110385        break;
110386      case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
110387{sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
110388        break;
110389      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
110390{sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
110391        break;
110392      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
110393{sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
110394        break;
110395      case 175: /* insert_cmd ::= INSERT orconf */
110396{yygotominor.yy258 = yymsp[0].minor.yy258;}
110397        break;
110398      case 176: /* insert_cmd ::= REPLACE */
110399{yygotominor.yy258 = OE_Replace;}
110400        break;
110401      case 177: /* valuelist ::= VALUES LP nexprlist RP */
110402{
110403  yygotominor.yy487.pList = yymsp[-1].minor.yy442;
110404  yygotominor.yy487.pSelect = 0;
110405}
110406        break;
110407      case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
110408{
110409  Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
110410  if( yymsp[-4].minor.yy487.pList ){
110411    yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
110412    yymsp[-4].minor.yy487.pList = 0;
110413  }
110414  yygotominor.yy487.pList = 0;
110415  if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
110416    sqlite3SelectDelete(pParse->db, pRight);
110417    sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
110418    yygotominor.yy487.pSelect = 0;
110419  }else{
110420    pRight->op = TK_ALL;
110421    pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
110422    pRight->selFlags |= SF_Values;
110423    pRight->pPrior->selFlags |= SF_Values;
110424    yygotominor.yy487.pSelect = pRight;
110425  }
110426}
110427        break;
110428      case 181: /* inscollist ::= inscollist COMMA nm */
110429{yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
110430        break;
110431      case 182: /* inscollist ::= nm */
110432{yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
110433        break;
110434      case 183: /* expr ::= term */
110435{yygotominor.yy342 = yymsp[0].minor.yy342;}
110436        break;
110437      case 184: /* expr ::= LP expr RP */
110438{yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
110439        break;
110440      case 185: /* term ::= NULL */
110441      case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
110442      case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
110443{spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
110444        break;
110445      case 186: /* expr ::= id */
110446      case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
110447{spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
110448        break;
110449      case 188: /* expr ::= nm DOT nm */
110450{
110451  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
110452  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
110453  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
110454  spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
110455}
110456        break;
110457      case 189: /* expr ::= nm DOT nm DOT nm */
110458{
110459  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
110460  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
110461  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
110462  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
110463  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
110464  spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
110465}
110466        break;
110467      case 192: /* expr ::= REGISTER */
110468{
110469  /* When doing a nested parse, one can include terms in an expression
110470  ** that look like this:   #1 #2 ...  These terms refer to registers
110471  ** in the virtual machine.  #N is the N-th register. */
110472  if( pParse->nested==0 ){
110473    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
110474    yygotominor.yy342.pExpr = 0;
110475  }else{
110476    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
110477    if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
110478  }
110479  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110480}
110481        break;
110482      case 193: /* expr ::= VARIABLE */
110483{
110484  spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
110485  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
110486  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110487}
110488        break;
110489      case 194: /* expr ::= expr COLLATE ids */
110490{
110491  yygotominor.yy342.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
110492  yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
110493  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110494}
110495        break;
110496      case 195: /* expr ::= CAST LP expr AS typetoken RP */
110497{
110498  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
110499  spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
110500}
110501        break;
110502      case 196: /* expr ::= ID LP distinct exprlist RP */
110503{
110504  if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
110505    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
110506  }
110507  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
110508  spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
110509  if( yymsp[-2].minor.yy392 && yygotominor.yy342.pExpr ){
110510    yygotominor.yy342.pExpr->flags |= EP_Distinct;
110511  }
110512}
110513        break;
110514      case 197: /* expr ::= ID LP STAR RP */
110515{
110516  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
110517  spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
110518}
110519        break;
110520      case 198: /* term ::= CTIME_KW */
110521{
110522  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
110523  ** treated as functions that return constants */
110524  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
110525  if( yygotominor.yy342.pExpr ){
110526    yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
110527  }
110528  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110529}
110530        break;
110531      case 199: /* expr ::= expr AND expr */
110532      case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
110533      case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
110534      case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
110535      case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
110536      case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
110537      case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
110538      case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
110539{spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
110540        break;
110541      case 207: /* likeop ::= LIKE_KW */
110542      case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
110543{yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 0;}
110544        break;
110545      case 208: /* likeop ::= NOT LIKE_KW */
110546      case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
110547{yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 1;}
110548        break;
110549      case 211: /* expr ::= expr likeop expr */
110550{
110551  ExprList *pList;
110552  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
110553  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
110554  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
110555  if( yymsp[-1].minor.yy318.not ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110556  yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
110557  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
110558  if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
110559}
110560        break;
110561      case 212: /* expr ::= expr likeop expr ESCAPE expr */
110562{
110563  ExprList *pList;
110564  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
110565  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
110566  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
110567  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
110568  if( yymsp[-3].minor.yy318.not ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110569  yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110570  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
110571  if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
110572}
110573        break;
110574      case 213: /* expr ::= expr ISNULL|NOTNULL */
110575{spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
110576        break;
110577      case 214: /* expr ::= expr NOT NULL */
110578{spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
110579        break;
110580      case 215: /* expr ::= expr IS expr */
110581{
110582  spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
110583  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
110584}
110585        break;
110586      case 216: /* expr ::= expr IS NOT expr */
110587{
110588  spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
110589  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
110590}
110591        break;
110592      case 217: /* expr ::= NOT expr */
110593      case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
110594{spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
110595        break;
110596      case 219: /* expr ::= MINUS expr */
110597{spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
110598        break;
110599      case 220: /* expr ::= PLUS expr */
110600{spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
110601        break;
110602      case 223: /* expr ::= expr between_op expr AND expr */
110603{
110604  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
110605  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
110606  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
110607  if( yygotominor.yy342.pExpr ){
110608    yygotominor.yy342.pExpr->x.pList = pList;
110609  }else{
110610    sqlite3ExprListDelete(pParse->db, pList);
110611  }
110612  if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110613  yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110614  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
110615}
110616        break;
110617      case 226: /* expr ::= expr in_op LP exprlist RP */
110618{
110619    if( yymsp[-1].minor.yy442==0 ){
110620      /* Expressions of the form
110621      **
110622      **      expr1 IN ()
110623      **      expr1 NOT IN ()
110624      **
110625      ** simplify to constants 0 (false) and 1 (true), respectively,
110626      ** regardless of the value of expr1.
110627      */
110628      yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
110629      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
110630    }else{
110631      yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
110632      if( yygotominor.yy342.pExpr ){
110633        yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
110634        sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110635      }else{
110636        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
110637      }
110638      if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110639    }
110640    yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110641    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110642  }
110643        break;
110644      case 227: /* expr ::= LP select RP */
110645{
110646    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
110647    if( yygotominor.yy342.pExpr ){
110648      yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
110649      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
110650      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110651    }else{
110652      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
110653    }
110654    yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
110655    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110656  }
110657        break;
110658      case 228: /* expr ::= expr in_op LP select RP */
110659{
110660    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
110661    if( yygotominor.yy342.pExpr ){
110662      yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
110663      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
110664      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110665    }else{
110666      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
110667    }
110668    if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110669    yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110670    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110671  }
110672        break;
110673      case 229: /* expr ::= expr in_op nm dbnm */
110674{
110675    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
110676    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
110677    if( yygotominor.yy342.pExpr ){
110678      yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
110679      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
110680      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110681    }else{
110682      sqlite3SrcListDelete(pParse->db, pSrc);
110683    }
110684    if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110685    yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
110686    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];
110687  }
110688        break;
110689      case 230: /* expr ::= EXISTS LP select RP */
110690{
110691    Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
110692    if( p ){
110693      p->x.pSelect = yymsp[-1].minor.yy159;
110694      ExprSetProperty(p, EP_xIsSelect);
110695      sqlite3ExprSetHeight(pParse, p);
110696    }else{
110697      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
110698    }
110699    yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
110700    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110701  }
110702        break;
110703      case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
110704{
110705  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
110706  if( yygotominor.yy342.pExpr ){
110707    yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
110708    sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110709  }else{
110710    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
110711  }
110712  yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
110713  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110714}
110715        break;
110716      case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
110717{
110718  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
110719  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
110720}
110721        break;
110722      case 233: /* case_exprlist ::= WHEN expr THEN expr */
110723{
110724  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
110725  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
110726}
110727        break;
110728      case 240: /* nexprlist ::= nexprlist COMMA expr */
110729{yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
110730        break;
110731      case 241: /* nexprlist ::= expr */
110732{yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
110733        break;
110734      case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
110735{
110736  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
110737                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
110738                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
110739}
110740        break;
110741      case 243: /* uniqueflag ::= UNIQUE */
110742      case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
110743{yygotominor.yy392 = OE_Abort;}
110744        break;
110745      case 244: /* uniqueflag ::= */
110746{yygotominor.yy392 = OE_None;}
110747        break;
110748      case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
110749{
110750  Expr *p = 0;
110751  if( yymsp[-1].minor.yy0.n>0 ){
110752    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
110753    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
110754  }
110755  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
110756  sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
110757  sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
110758  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
110759}
110760        break;
110761      case 248: /* idxlist ::= nm collate sortorder */
110762{
110763  Expr *p = 0;
110764  if( yymsp[-1].minor.yy0.n>0 ){
110765    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
110766    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
110767  }
110768  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
110769  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
110770  sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
110771  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
110772}
110773        break;
110774      case 249: /* collate ::= */
110775{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
110776        break;
110777      case 251: /* cmd ::= DROP INDEX ifexists fullname */
110778{sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
110779        break;
110780      case 252: /* cmd ::= VACUUM */
110781      case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
110782{sqlite3Vacuum(pParse);}
110783        break;
110784      case 254: /* cmd ::= PRAGMA nm dbnm */
110785{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
110786        break;
110787      case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
110788{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
110789        break;
110790      case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
110791{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
110792        break;
110793      case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
110794{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
110795        break;
110796      case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
110797{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
110798        break;
110799      case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
110800{
110801  Token all;
110802  all.z = yymsp[-3].minor.yy0.z;
110803  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
110804  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
110805}
110806        break;
110807      case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
110808{
110809  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);
110810  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
110811}
110812        break;
110813      case 270: /* trigger_time ::= BEFORE */
110814      case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
110815{ yygotominor.yy392 = TK_BEFORE; }
110816        break;
110817      case 271: /* trigger_time ::= AFTER */
110818{ yygotominor.yy392 = TK_AFTER;  }
110819        break;
110820      case 272: /* trigger_time ::= INSTEAD OF */
110821{ yygotominor.yy392 = TK_INSTEAD;}
110822        break;
110823      case 274: /* trigger_event ::= DELETE|INSERT */
110824      case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
110825{yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
110826        break;
110827      case 276: /* trigger_event ::= UPDATE OF inscollist */
110828{yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
110829        break;
110830      case 279: /* when_clause ::= */
110831      case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
110832{ yygotominor.yy122 = 0; }
110833        break;
110834      case 280: /* when_clause ::= WHEN expr */
110835      case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
110836{ yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
110837        break;
110838      case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
110839{
110840  assert( yymsp[-2].minor.yy327!=0 );
110841  yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
110842  yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
110843  yygotominor.yy327 = yymsp[-2].minor.yy327;
110844}
110845        break;
110846      case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
110847{
110848  assert( yymsp[-1].minor.yy327!=0 );
110849  yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
110850  yygotominor.yy327 = yymsp[-1].minor.yy327;
110851}
110852        break;
110853      case 284: /* trnm ::= nm DOT nm */
110854{
110855  yygotominor.yy0 = yymsp[0].minor.yy0;
110856  sqlite3ErrorMsg(pParse,
110857        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
110858        "statements within triggers");
110859}
110860        break;
110861      case 286: /* tridxby ::= INDEXED BY nm */
110862{
110863  sqlite3ErrorMsg(pParse,
110864        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
110865        "within triggers");
110866}
110867        break;
110868      case 287: /* tridxby ::= NOT INDEXED */
110869{
110870  sqlite3ErrorMsg(pParse,
110871        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
110872        "within triggers");
110873}
110874        break;
110875      case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
110876{ yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
110877        break;
110878      case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
110879{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);}
110880        break;
110881      case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
110882{yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
110883        break;
110884      case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
110885{yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
110886        break;
110887      case 292: /* trigger_cmd ::= select */
110888{yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
110889        break;
110890      case 293: /* expr ::= RAISE LP IGNORE RP */
110891{
110892  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
110893  if( yygotominor.yy342.pExpr ){
110894    yygotominor.yy342.pExpr->affinity = OE_Ignore;
110895  }
110896  yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
110897  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110898}
110899        break;
110900      case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
110901{
110902  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
110903  if( yygotominor.yy342.pExpr ) {
110904    yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
110905  }
110906  yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
110907  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110908}
110909        break;
110910      case 295: /* raisetype ::= ROLLBACK */
110911{yygotominor.yy392 = OE_Rollback;}
110912        break;
110913      case 297: /* raisetype ::= FAIL */
110914{yygotominor.yy392 = OE_Fail;}
110915        break;
110916      case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
110917{
110918  sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
110919}
110920        break;
110921      case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
110922{
110923  sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
110924}
110925        break;
110926      case 300: /* cmd ::= DETACH database_kw_opt expr */
110927{
110928  sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
110929}
110930        break;
110931      case 305: /* cmd ::= REINDEX */
110932{sqlite3Reindex(pParse, 0, 0);}
110933        break;
110934      case 306: /* cmd ::= REINDEX nm dbnm */
110935{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
110936        break;
110937      case 307: /* cmd ::= ANALYZE */
110938{sqlite3Analyze(pParse, 0, 0);}
110939        break;
110940      case 308: /* cmd ::= ANALYZE nm dbnm */
110941{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
110942        break;
110943      case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
110944{
110945  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
110946}
110947        break;
110948      case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
110949{
110950  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
110951}
110952        break;
110953      case 311: /* add_column_fullname ::= fullname */
110954{
110955  pParse->db->lookaside.bEnabled = 0;
110956  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
110957}
110958        break;
110959      case 314: /* cmd ::= create_vtab */
110960{sqlite3VtabFinishParse(pParse,0);}
110961        break;
110962      case 315: /* cmd ::= create_vtab LP vtabarglist RP */
110963{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
110964        break;
110965      case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
110966{
110967    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
110968}
110969        break;
110970      case 319: /* vtabarg ::= */
110971{sqlite3VtabArgInit(pParse);}
110972        break;
110973      case 321: /* vtabargtoken ::= ANY */
110974      case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
110975      case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
110976{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
110977        break;
110978      default:
110979      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
110980      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
110981      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
110982      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
110983      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
110984      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
110985      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
110986      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
110987      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
110988      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
110989      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
110990      /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
110991      /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
110992      /* (44) type ::= */ yytestcase(yyruleno==44);
110993      /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
110994      /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
110995      /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
110996      /* (54) carglist ::= */ yytestcase(yyruleno==54);
110997      /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
110998      /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
110999      /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
111000      /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
111001      /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
111002      /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
111003      /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
111004      /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
111005      /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
111006      /* (285) tridxby ::= */ yytestcase(yyruleno==285);
111007      /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
111008      /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
111009      /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
111010      /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
111011      /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
111012      /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
111013      /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
111014      /* (324) anylist ::= */ yytestcase(yyruleno==324);
111015      /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
111016      /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
111017        break;
111018  };
111019  yygoto = yyRuleInfo[yyruleno].lhs;
111020  yysize = yyRuleInfo[yyruleno].nrhs;
111021  yypParser->yyidx -= yysize;
111022  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
111023  if( yyact < YYNSTATE ){
111024#ifdef NDEBUG
111025    /* If we are not debugging and the reduce action popped at least
111026    ** one element off the stack, then we can push the new element back
111027    ** onto the stack here, and skip the stack overflow test in yy_shift().
111028    ** That gives a significant speed improvement. */
111029    if( yysize ){
111030      yypParser->yyidx++;
111031      yymsp -= yysize-1;
111032      yymsp->stateno = (YYACTIONTYPE)yyact;
111033      yymsp->major = (YYCODETYPE)yygoto;
111034      yymsp->minor = yygotominor;
111035    }else
111036#endif
111037    {
111038      yy_shift(yypParser,yyact,yygoto,&yygotominor);
111039    }
111040  }else{
111041    assert( yyact == YYNSTATE + YYNRULE + 1 );
111042    yy_accept(yypParser);
111043  }
111044}
111045
111046/*
111047** The following code executes when the parse fails
111048*/
111049#ifndef YYNOERRORRECOVERY
111050static void yy_parse_failed(
111051  yyParser *yypParser           /* The parser */
111052){
111053  sqlite3ParserARG_FETCH;
111054#ifndef NDEBUG
111055  if( yyTraceFILE ){
111056    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
111057  }
111058#endif
111059  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111060  /* Here code is inserted which will be executed whenever the
111061  ** parser fails */
111062  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111063}
111064#endif /* YYNOERRORRECOVERY */
111065
111066/*
111067** The following code executes when a syntax error first occurs.
111068*/
111069static void yy_syntax_error(
111070  yyParser *yypParser,           /* The parser */
111071  int yymajor,                   /* The major type of the error token */
111072  YYMINORTYPE yyminor            /* The minor type of the error token */
111073){
111074  sqlite3ParserARG_FETCH;
111075#define TOKEN (yyminor.yy0)
111076
111077  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
111078  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
111079  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
111080  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111081}
111082
111083/*
111084** The following is executed when the parser accepts
111085*/
111086static void yy_accept(
111087  yyParser *yypParser           /* The parser */
111088){
111089  sqlite3ParserARG_FETCH;
111090#ifndef NDEBUG
111091  if( yyTraceFILE ){
111092    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
111093  }
111094#endif
111095  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111096  /* Here code is inserted which will be executed whenever the
111097  ** parser accepts */
111098  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111099}
111100
111101/* The main parser program.
111102** The first argument is a pointer to a structure obtained from
111103** "sqlite3ParserAlloc" which describes the current state of the parser.
111104** The second argument is the major token number.  The third is
111105** the minor token.  The fourth optional argument is whatever the
111106** user wants (and specified in the grammar) and is available for
111107** use by the action routines.
111108**
111109** Inputs:
111110** <ul>
111111** <li> A pointer to the parser (an opaque structure.)
111112** <li> The major token number.
111113** <li> The minor token number.
111114** <li> An option argument of a grammar-specified type.
111115** </ul>
111116**
111117** Outputs:
111118** None.
111119*/
111120SQLITE_PRIVATE void sqlite3Parser(
111121  void *yyp,                   /* The parser */
111122  int yymajor,                 /* The major token code number */
111123  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
111124  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
111125){
111126  YYMINORTYPE yyminorunion;
111127  int yyact;            /* The parser action. */
111128#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
111129  int yyendofinput;     /* True if we are at the end of input */
111130#endif
111131#ifdef YYERRORSYMBOL
111132  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
111133#endif
111134  yyParser *yypParser;  /* The parser */
111135
111136  /* (re)initialize the parser, if necessary */
111137  yypParser = (yyParser*)yyp;
111138  if( yypParser->yyidx<0 ){
111139#if YYSTACKDEPTH<=0
111140    if( yypParser->yystksz <=0 ){
111141      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
111142      yyminorunion = yyzerominor;
111143      yyStackOverflow(yypParser, &yyminorunion);
111144      return;
111145    }
111146#endif
111147    yypParser->yyidx = 0;
111148    yypParser->yyerrcnt = -1;
111149    yypParser->yystack[0].stateno = 0;
111150    yypParser->yystack[0].major = 0;
111151  }
111152  yyminorunion.yy0 = yyminor;
111153#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
111154  yyendofinput = (yymajor==0);
111155#endif
111156  sqlite3ParserARG_STORE;
111157
111158#ifndef NDEBUG
111159  if( yyTraceFILE ){
111160    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
111161  }
111162#endif
111163
111164  do{
111165    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
111166    if( yyact<YYNSTATE ){
111167      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
111168      yypParser->yyerrcnt--;
111169      yymajor = YYNOCODE;
111170    }else if( yyact < YYNSTATE + YYNRULE ){
111171      yy_reduce(yypParser,yyact-YYNSTATE);
111172    }else{
111173      assert( yyact == YY_ERROR_ACTION );
111174#ifdef YYERRORSYMBOL
111175      int yymx;
111176#endif
111177#ifndef NDEBUG
111178      if( yyTraceFILE ){
111179        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
111180      }
111181#endif
111182#ifdef YYERRORSYMBOL
111183      /* A syntax error has occurred.
111184      ** The response to an error depends upon whether or not the
111185      ** grammar defines an error token "ERROR".
111186      **
111187      ** This is what we do if the grammar does define ERROR:
111188      **
111189      **  * Call the %syntax_error function.
111190      **
111191      **  * Begin popping the stack until we enter a state where
111192      **    it is legal to shift the error symbol, then shift
111193      **    the error symbol.
111194      **
111195      **  * Set the error count to three.
111196      **
111197      **  * Begin accepting and shifting new tokens.  No new error
111198      **    processing will occur until three tokens have been
111199      **    shifted successfully.
111200      **
111201      */
111202      if( yypParser->yyerrcnt<0 ){
111203        yy_syntax_error(yypParser,yymajor,yyminorunion);
111204      }
111205      yymx = yypParser->yystack[yypParser->yyidx].major;
111206      if( yymx==YYERRORSYMBOL || yyerrorhit ){
111207#ifndef NDEBUG
111208        if( yyTraceFILE ){
111209          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
111210             yyTracePrompt,yyTokenName[yymajor]);
111211        }
111212#endif
111213        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
111214        yymajor = YYNOCODE;
111215      }else{
111216         while(
111217          yypParser->yyidx >= 0 &&
111218          yymx != YYERRORSYMBOL &&
111219          (yyact = yy_find_reduce_action(
111220                        yypParser->yystack[yypParser->yyidx].stateno,
111221                        YYERRORSYMBOL)) >= YYNSTATE
111222        ){
111223          yy_pop_parser_stack(yypParser);
111224        }
111225        if( yypParser->yyidx < 0 || yymajor==0 ){
111226          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
111227          yy_parse_failed(yypParser);
111228          yymajor = YYNOCODE;
111229        }else if( yymx!=YYERRORSYMBOL ){
111230          YYMINORTYPE u2;
111231          u2.YYERRSYMDT = 0;
111232          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
111233        }
111234      }
111235      yypParser->yyerrcnt = 3;
111236      yyerrorhit = 1;
111237#elif defined(YYNOERRORRECOVERY)
111238      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
111239      ** do any kind of error recovery.  Instead, simply invoke the syntax
111240      ** error routine and continue going as if nothing had happened.
111241      **
111242      ** Applications can set this macro (for example inside %include) if
111243      ** they intend to abandon the parse upon the first syntax error seen.
111244      */
111245      yy_syntax_error(yypParser,yymajor,yyminorunion);
111246      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
111247      yymajor = YYNOCODE;
111248
111249#else  /* YYERRORSYMBOL is not defined */
111250      /* This is what we do if the grammar does not define ERROR:
111251      **
111252      **  * Report an error message, and throw away the input token.
111253      **
111254      **  * If the input token is $, then fail the parse.
111255      **
111256      ** As before, subsequent error messages are suppressed until
111257      ** three input tokens have been successfully shifted.
111258      */
111259      if( yypParser->yyerrcnt<=0 ){
111260        yy_syntax_error(yypParser,yymajor,yyminorunion);
111261      }
111262      yypParser->yyerrcnt = 3;
111263      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
111264      if( yyendofinput ){
111265        yy_parse_failed(yypParser);
111266      }
111267      yymajor = YYNOCODE;
111268#endif
111269    }
111270  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
111271  return;
111272}
111273
111274/************** End of parse.c ***********************************************/
111275/************** Begin file tokenize.c ****************************************/
111276/*
111277** 2001 September 15
111278**
111279** The author disclaims copyright to this source code.  In place of
111280** a legal notice, here is a blessing:
111281**
111282**    May you do good and not evil.
111283**    May you find forgiveness for yourself and forgive others.
111284**    May you share freely, never taking more than you give.
111285**
111286*************************************************************************
111287** An tokenizer for SQL
111288**
111289** This file contains C code that splits an SQL input string up into
111290** individual tokens and sends those tokens one-by-one over to the
111291** parser for analysis.
111292*/
111293/* #include <stdlib.h> */
111294
111295/*
111296** The charMap() macro maps alphabetic characters into their
111297** lower-case ASCII equivalent.  On ASCII machines, this is just
111298** an upper-to-lower case map.  On EBCDIC machines we also need
111299** to adjust the encoding.  Only alphabetic characters and underscores
111300** need to be translated.
111301*/
111302#ifdef SQLITE_ASCII
111303# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
111304#endif
111305#ifdef SQLITE_EBCDIC
111306# define charMap(X) ebcdicToAscii[(unsigned char)X]
111307const unsigned char ebcdicToAscii[] = {
111308/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
111309   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
111310   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
111311   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
111312   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
111313   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
111314   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
111315   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
111316   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
111317   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
111318   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
111319   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
111320   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
111321   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
111322   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
111323   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
111324   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
111325};
111326#endif
111327
111328/*
111329** The sqlite3KeywordCode function looks up an identifier to determine if
111330** it is a keyword.  If it is a keyword, the token code of that keyword is
111331** returned.  If the input is not a keyword, TK_ID is returned.
111332**
111333** The implementation of this routine was generated by a program,
111334** mkkeywordhash.h, located in the tool subdirectory of the distribution.
111335** The output of the mkkeywordhash.c program is written into a file
111336** named keywordhash.h and then included into this source file by
111337** the #include below.
111338*/
111339/************** Include keywordhash.h in the middle of tokenize.c ************/
111340/************** Begin file keywordhash.h *************************************/
111341/***** This file contains automatically generated code ******
111342**
111343** The code in this file has been automatically generated by
111344**
111345**   sqlite/tool/mkkeywordhash.c
111346**
111347** The code in this file implements a function that determines whether
111348** or not a given identifier is really an SQL keyword.  The same thing
111349** might be implemented more directly using a hand-written hash table.
111350** But by using this automatically generated code, the size of the code
111351** is substantially reduced.  This is important for embedded applications
111352** on platforms with limited memory.
111353*/
111354/* Hash score: 175 */
111355static int keywordCode(const char *z, int n){
111356  /* zText[] encodes 811 bytes of keywords in 541 bytes */
111357  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
111358  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
111359  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
111360  /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
111361  /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
111362  /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
111363  /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
111364  /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
111365  /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
111366  /*   INITIALLY                                                          */
111367  static const char zText[540] = {
111368    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
111369    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
111370    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
111371    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
111372    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
111373    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
111374    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
111375    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
111376    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
111377    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
111378    'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
111379    'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
111380    'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
111381    'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
111382    'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
111383    'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
111384    'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
111385    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
111386    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
111387    'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
111388    'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
111389    'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
111390    'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
111391    'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
111392    'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
111393    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
111394    'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
111395    'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
111396    'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
111397    'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
111398  };
111399  static const unsigned char aHash[127] = {
111400      72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
111401      42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
111402     118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
111403       0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
111404       0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
111405      92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
111406      96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
111407      39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
111408      58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
111409      29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
111410  };
111411  static const unsigned char aNext[121] = {
111412       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
111413       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
111414       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
111415       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
111416       0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
111417      62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
111418      61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
111419       0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
111420     103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
111421      35,  64,   0,   0,
111422  };
111423  static const unsigned char aLen[121] = {
111424       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
111425       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
111426      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
111427       4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
111428       5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
111429       7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
111430       7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
111431       6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
111432       4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
111433       6,   4,   9,   3,
111434  };
111435  static const unsigned short int aOffset[121] = {
111436       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
111437      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
111438      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
111439     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
111440     203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
111441     248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
111442     326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
111443     387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
111444     462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
111445     521, 527, 531, 536,
111446  };
111447  static const unsigned char aCode[121] = {
111448    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
111449    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
111450    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
111451    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
111452    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
111453    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
111454    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
111455    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
111456    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
111457    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
111458    TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
111459    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
111460    TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
111461    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
111462    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
111463    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
111464    TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
111465    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
111466    TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
111467    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
111468    TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
111469    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
111470    TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
111471    TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
111472    TK_ALL,
111473  };
111474  int h, i;
111475  if( n<2 ) return TK_ID;
111476  h = ((charMap(z[0])*4) ^
111477      (charMap(z[n-1])*3) ^
111478      n) % 127;
111479  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
111480    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
111481      testcase( i==0 ); /* REINDEX */
111482      testcase( i==1 ); /* INDEXED */
111483      testcase( i==2 ); /* INDEX */
111484      testcase( i==3 ); /* DESC */
111485      testcase( i==4 ); /* ESCAPE */
111486      testcase( i==5 ); /* EACH */
111487      testcase( i==6 ); /* CHECK */
111488      testcase( i==7 ); /* KEY */
111489      testcase( i==8 ); /* BEFORE */
111490      testcase( i==9 ); /* FOREIGN */
111491      testcase( i==10 ); /* FOR */
111492      testcase( i==11 ); /* IGNORE */
111493      testcase( i==12 ); /* REGEXP */
111494      testcase( i==13 ); /* EXPLAIN */
111495      testcase( i==14 ); /* INSTEAD */
111496      testcase( i==15 ); /* ADD */
111497      testcase( i==16 ); /* DATABASE */
111498      testcase( i==17 ); /* AS */
111499      testcase( i==18 ); /* SELECT */
111500      testcase( i==19 ); /* TABLE */
111501      testcase( i==20 ); /* LEFT */
111502      testcase( i==21 ); /* THEN */
111503      testcase( i==22 ); /* END */
111504      testcase( i==23 ); /* DEFERRABLE */
111505      testcase( i==24 ); /* ELSE */
111506      testcase( i==25 ); /* EXCEPT */
111507      testcase( i==26 ); /* TRANSACTION */
111508      testcase( i==27 ); /* ACTION */
111509      testcase( i==28 ); /* ON */
111510      testcase( i==29 ); /* NATURAL */
111511      testcase( i==30 ); /* ALTER */
111512      testcase( i==31 ); /* RAISE */
111513      testcase( i==32 ); /* EXCLUSIVE */
111514      testcase( i==33 ); /* EXISTS */
111515      testcase( i==34 ); /* SAVEPOINT */
111516      testcase( i==35 ); /* INTERSECT */
111517      testcase( i==36 ); /* TRIGGER */
111518      testcase( i==37 ); /* REFERENCES */
111519      testcase( i==38 ); /* CONSTRAINT */
111520      testcase( i==39 ); /* INTO */
111521      testcase( i==40 ); /* OFFSET */
111522      testcase( i==41 ); /* OF */
111523      testcase( i==42 ); /* SET */
111524      testcase( i==43 ); /* TEMPORARY */
111525      testcase( i==44 ); /* TEMP */
111526      testcase( i==45 ); /* OR */
111527      testcase( i==46 ); /* UNIQUE */
111528      testcase( i==47 ); /* QUERY */
111529      testcase( i==48 ); /* ATTACH */
111530      testcase( i==49 ); /* HAVING */
111531      testcase( i==50 ); /* GROUP */
111532      testcase( i==51 ); /* UPDATE */
111533      testcase( i==52 ); /* BEGIN */
111534      testcase( i==53 ); /* INNER */
111535      testcase( i==54 ); /* RELEASE */
111536      testcase( i==55 ); /* BETWEEN */
111537      testcase( i==56 ); /* NOTNULL */
111538      testcase( i==57 ); /* NOT */
111539      testcase( i==58 ); /* NO */
111540      testcase( i==59 ); /* NULL */
111541      testcase( i==60 ); /* LIKE */
111542      testcase( i==61 ); /* CASCADE */
111543      testcase( i==62 ); /* ASC */
111544      testcase( i==63 ); /* DELETE */
111545      testcase( i==64 ); /* CASE */
111546      testcase( i==65 ); /* COLLATE */
111547      testcase( i==66 ); /* CREATE */
111548      testcase( i==67 ); /* CURRENT_DATE */
111549      testcase( i==68 ); /* DETACH */
111550      testcase( i==69 ); /* IMMEDIATE */
111551      testcase( i==70 ); /* JOIN */
111552      testcase( i==71 ); /* INSERT */
111553      testcase( i==72 ); /* MATCH */
111554      testcase( i==73 ); /* PLAN */
111555      testcase( i==74 ); /* ANALYZE */
111556      testcase( i==75 ); /* PRAGMA */
111557      testcase( i==76 ); /* ABORT */
111558      testcase( i==77 ); /* VALUES */
111559      testcase( i==78 ); /* VIRTUAL */
111560      testcase( i==79 ); /* LIMIT */
111561      testcase( i==80 ); /* WHEN */
111562      testcase( i==81 ); /* WHERE */
111563      testcase( i==82 ); /* RENAME */
111564      testcase( i==83 ); /* AFTER */
111565      testcase( i==84 ); /* REPLACE */
111566      testcase( i==85 ); /* AND */
111567      testcase( i==86 ); /* DEFAULT */
111568      testcase( i==87 ); /* AUTOINCREMENT */
111569      testcase( i==88 ); /* TO */
111570      testcase( i==89 ); /* IN */
111571      testcase( i==90 ); /* CAST */
111572      testcase( i==91 ); /* COLUMN */
111573      testcase( i==92 ); /* COMMIT */
111574      testcase( i==93 ); /* CONFLICT */
111575      testcase( i==94 ); /* CROSS */
111576      testcase( i==95 ); /* CURRENT_TIMESTAMP */
111577      testcase( i==96 ); /* CURRENT_TIME */
111578      testcase( i==97 ); /* PRIMARY */
111579      testcase( i==98 ); /* DEFERRED */
111580      testcase( i==99 ); /* DISTINCT */
111581      testcase( i==100 ); /* IS */
111582      testcase( i==101 ); /* DROP */
111583      testcase( i==102 ); /* FAIL */
111584      testcase( i==103 ); /* FROM */
111585      testcase( i==104 ); /* FULL */
111586      testcase( i==105 ); /* GLOB */
111587      testcase( i==106 ); /* BY */
111588      testcase( i==107 ); /* IF */
111589      testcase( i==108 ); /* ISNULL */
111590      testcase( i==109 ); /* ORDER */
111591      testcase( i==110 ); /* RESTRICT */
111592      testcase( i==111 ); /* OUTER */
111593      testcase( i==112 ); /* RIGHT */
111594      testcase( i==113 ); /* ROLLBACK */
111595      testcase( i==114 ); /* ROW */
111596      testcase( i==115 ); /* UNION */
111597      testcase( i==116 ); /* USING */
111598      testcase( i==117 ); /* VACUUM */
111599      testcase( i==118 ); /* VIEW */
111600      testcase( i==119 ); /* INITIALLY */
111601      testcase( i==120 ); /* ALL */
111602      return aCode[i];
111603    }
111604  }
111605  return TK_ID;
111606}
111607SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
111608  return keywordCode((char*)z, n);
111609}
111610#define SQLITE_N_KEYWORD 121
111611
111612/************** End of keywordhash.h *****************************************/
111613/************** Continuing where we left off in tokenize.c *******************/
111614
111615
111616/*
111617** If X is a character that can be used in an identifier then
111618** IdChar(X) will be true.  Otherwise it is false.
111619**
111620** For ASCII, any character with the high-order bit set is
111621** allowed in an identifier.  For 7-bit characters,
111622** sqlite3IsIdChar[X] must be 1.
111623**
111624** For EBCDIC, the rules are more complex but have the same
111625** end result.
111626**
111627** Ticket #1066.  the SQL standard does not allow '$' in the
111628** middle of identfiers.  But many SQL implementations do.
111629** SQLite will allow '$' in identifiers for compatibility.
111630** But the feature is undocumented.
111631*/
111632#ifdef SQLITE_ASCII
111633#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
111634#endif
111635#ifdef SQLITE_EBCDIC
111636SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
111637/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
111638    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
111639    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
111640    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
111641    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
111642    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
111643    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
111644    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
111645    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
111646    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
111647    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
111648    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
111649    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
111650};
111651#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
111652#endif
111653
111654
111655/*
111656** Return the length of the token that begins at z[0].
111657** Store the token type in *tokenType before returning.
111658*/
111659SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
111660  int i, c;
111661  switch( *z ){
111662    case ' ': case '\t': case '\n': case '\f': case '\r': {
111663      testcase( z[0]==' ' );
111664      testcase( z[0]=='\t' );
111665      testcase( z[0]=='\n' );
111666      testcase( z[0]=='\f' );
111667      testcase( z[0]=='\r' );
111668      for(i=1; sqlite3Isspace(z[i]); i++){}
111669      *tokenType = TK_SPACE;
111670      return i;
111671    }
111672    case '-': {
111673      if( z[1]=='-' ){
111674        /* IMP: R-50417-27976 -- syntax diagram for comments */
111675        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
111676        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
111677        return i;
111678      }
111679      *tokenType = TK_MINUS;
111680      return 1;
111681    }
111682    case '(': {
111683      *tokenType = TK_LP;
111684      return 1;
111685    }
111686    case ')': {
111687      *tokenType = TK_RP;
111688      return 1;
111689    }
111690    case ';': {
111691      *tokenType = TK_SEMI;
111692      return 1;
111693    }
111694    case '+': {
111695      *tokenType = TK_PLUS;
111696      return 1;
111697    }
111698    case '*': {
111699      *tokenType = TK_STAR;
111700      return 1;
111701    }
111702    case '/': {
111703      if( z[1]!='*' || z[2]==0 ){
111704        *tokenType = TK_SLASH;
111705        return 1;
111706      }
111707      /* IMP: R-50417-27976 -- syntax diagram for comments */
111708      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
111709      if( c ) i++;
111710      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
111711      return i;
111712    }
111713    case '%': {
111714      *tokenType = TK_REM;
111715      return 1;
111716    }
111717    case '=': {
111718      *tokenType = TK_EQ;
111719      return 1 + (z[1]=='=');
111720    }
111721    case '<': {
111722      if( (c=z[1])=='=' ){
111723        *tokenType = TK_LE;
111724        return 2;
111725      }else if( c=='>' ){
111726        *tokenType = TK_NE;
111727        return 2;
111728      }else if( c=='<' ){
111729        *tokenType = TK_LSHIFT;
111730        return 2;
111731      }else{
111732        *tokenType = TK_LT;
111733        return 1;
111734      }
111735    }
111736    case '>': {
111737      if( (c=z[1])=='=' ){
111738        *tokenType = TK_GE;
111739        return 2;
111740      }else if( c=='>' ){
111741        *tokenType = TK_RSHIFT;
111742        return 2;
111743      }else{
111744        *tokenType = TK_GT;
111745        return 1;
111746      }
111747    }
111748    case '!': {
111749      if( z[1]!='=' ){
111750        *tokenType = TK_ILLEGAL;
111751        return 2;
111752      }else{
111753        *tokenType = TK_NE;
111754        return 2;
111755      }
111756    }
111757    case '|': {
111758      if( z[1]!='|' ){
111759        *tokenType = TK_BITOR;
111760        return 1;
111761      }else{
111762        *tokenType = TK_CONCAT;
111763        return 2;
111764      }
111765    }
111766    case ',': {
111767      *tokenType = TK_COMMA;
111768      return 1;
111769    }
111770    case '&': {
111771      *tokenType = TK_BITAND;
111772      return 1;
111773    }
111774    case '~': {
111775      *tokenType = TK_BITNOT;
111776      return 1;
111777    }
111778    case '`':
111779    case '\'':
111780    case '"': {
111781      int delim = z[0];
111782      testcase( delim=='`' );
111783      testcase( delim=='\'' );
111784      testcase( delim=='"' );
111785      for(i=1; (c=z[i])!=0; i++){
111786        if( c==delim ){
111787          if( z[i+1]==delim ){
111788            i++;
111789          }else{
111790            break;
111791          }
111792        }
111793      }
111794      if( c=='\'' ){
111795        *tokenType = TK_STRING;
111796        return i+1;
111797      }else if( c!=0 ){
111798        *tokenType = TK_ID;
111799        return i+1;
111800      }else{
111801        *tokenType = TK_ILLEGAL;
111802        return i;
111803      }
111804    }
111805    case '.': {
111806#ifndef SQLITE_OMIT_FLOATING_POINT
111807      if( !sqlite3Isdigit(z[1]) )
111808#endif
111809      {
111810        *tokenType = TK_DOT;
111811        return 1;
111812      }
111813      /* If the next character is a digit, this is a floating point
111814      ** number that begins with ".".  Fall thru into the next case */
111815    }
111816    case '0': case '1': case '2': case '3': case '4':
111817    case '5': case '6': case '7': case '8': case '9': {
111818      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
111819      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
111820      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
111821      testcase( z[0]=='9' );
111822      *tokenType = TK_INTEGER;
111823      for(i=0; sqlite3Isdigit(z[i]); i++){}
111824#ifndef SQLITE_OMIT_FLOATING_POINT
111825      if( z[i]=='.' ){
111826        i++;
111827        while( sqlite3Isdigit(z[i]) ){ i++; }
111828        *tokenType = TK_FLOAT;
111829      }
111830      if( (z[i]=='e' || z[i]=='E') &&
111831           ( sqlite3Isdigit(z[i+1])
111832            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
111833           )
111834      ){
111835        i += 2;
111836        while( sqlite3Isdigit(z[i]) ){ i++; }
111837        *tokenType = TK_FLOAT;
111838      }
111839#endif
111840      while( IdChar(z[i]) ){
111841        *tokenType = TK_ILLEGAL;
111842        i++;
111843      }
111844      return i;
111845    }
111846    case '[': {
111847      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
111848      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
111849      return i;
111850    }
111851    case '?': {
111852      *tokenType = TK_VARIABLE;
111853      for(i=1; sqlite3Isdigit(z[i]); i++){}
111854      return i;
111855    }
111856    case '#': {
111857      for(i=1; sqlite3Isdigit(z[i]); i++){}
111858      if( i>1 ){
111859        /* Parameters of the form #NNN (where NNN is a number) are used
111860        ** internally by sqlite3NestedParse.  */
111861        *tokenType = TK_REGISTER;
111862        return i;
111863      }
111864      /* Fall through into the next case if the '#' is not followed by
111865      ** a digit. Try to match #AAAA where AAAA is a parameter name. */
111866    }
111867#ifndef SQLITE_OMIT_TCL_VARIABLE
111868    case '$':
111869#endif
111870    case '@':  /* For compatibility with MS SQL Server */
111871    case ':': {
111872      int n = 0;
111873      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
111874      *tokenType = TK_VARIABLE;
111875      for(i=1; (c=z[i])!=0; i++){
111876        if( IdChar(c) ){
111877          n++;
111878#ifndef SQLITE_OMIT_TCL_VARIABLE
111879        }else if( c=='(' && n>0 ){
111880          do{
111881            i++;
111882          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
111883          if( c==')' ){
111884            i++;
111885          }else{
111886            *tokenType = TK_ILLEGAL;
111887          }
111888          break;
111889        }else if( c==':' && z[i+1]==':' ){
111890          i++;
111891#endif
111892        }else{
111893          break;
111894        }
111895      }
111896      if( n==0 ) *tokenType = TK_ILLEGAL;
111897      return i;
111898    }
111899#ifndef SQLITE_OMIT_BLOB_LITERAL
111900    case 'x': case 'X': {
111901      testcase( z[0]=='x' ); testcase( z[0]=='X' );
111902      if( z[1]=='\'' ){
111903        *tokenType = TK_BLOB;
111904        for(i=2; sqlite3Isxdigit(z[i]); i++){}
111905        if( z[i]!='\'' || i%2 ){
111906          *tokenType = TK_ILLEGAL;
111907          while( z[i] && z[i]!='\'' ){ i++; }
111908        }
111909        if( z[i] ) i++;
111910        return i;
111911      }
111912      /* Otherwise fall through to the next case */
111913    }
111914#endif
111915    default: {
111916      if( !IdChar(*z) ){
111917        break;
111918      }
111919      for(i=1; IdChar(z[i]); i++){}
111920      *tokenType = keywordCode((char*)z, i);
111921      return i;
111922    }
111923  }
111924  *tokenType = TK_ILLEGAL;
111925  return 1;
111926}
111927
111928/*
111929** Run the parser on the given SQL string.  The parser structure is
111930** passed in.  An SQLITE_ status code is returned.  If an error occurs
111931** then an and attempt is made to write an error message into
111932** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
111933** error message.
111934*/
111935SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
111936  int nErr = 0;                   /* Number of errors encountered */
111937  int i;                          /* Loop counter */
111938  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
111939  int tokenType;                  /* type of the next token */
111940  int lastTokenParsed = -1;       /* type of the previous token */
111941  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
111942  sqlite3 *db = pParse->db;       /* The database connection */
111943  int mxSqlLen;                   /* Max length of an SQL string */
111944
111945
111946  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
111947  if( db->activeVdbeCnt==0 ){
111948    db->u1.isInterrupted = 0;
111949  }
111950  pParse->rc = SQLITE_OK;
111951  pParse->zTail = zSql;
111952  i = 0;
111953  assert( pzErrMsg!=0 );
111954  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
111955  if( pEngine==0 ){
111956    db->mallocFailed = 1;
111957    return SQLITE_NOMEM;
111958  }
111959  assert( pParse->pNewTable==0 );
111960  assert( pParse->pNewTrigger==0 );
111961  assert( pParse->nVar==0 );
111962  assert( pParse->nzVar==0 );
111963  assert( pParse->azVar==0 );
111964  enableLookaside = db->lookaside.bEnabled;
111965  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
111966  while( !db->mallocFailed && zSql[i]!=0 ){
111967    assert( i>=0 );
111968    pParse->sLastToken.z = &zSql[i];
111969    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
111970    i += pParse->sLastToken.n;
111971    if( i>mxSqlLen ){
111972      pParse->rc = SQLITE_TOOBIG;
111973      break;
111974    }
111975    switch( tokenType ){
111976      case TK_SPACE: {
111977        if( db->u1.isInterrupted ){
111978          sqlite3ErrorMsg(pParse, "interrupt");
111979          pParse->rc = SQLITE_INTERRUPT;
111980          goto abort_parse;
111981        }
111982        break;
111983      }
111984      case TK_ILLEGAL: {
111985        sqlite3DbFree(db, *pzErrMsg);
111986        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
111987                        &pParse->sLastToken);
111988        nErr++;
111989        goto abort_parse;
111990      }
111991      case TK_SEMI: {
111992        pParse->zTail = &zSql[i];
111993        /* Fall thru into the default case */
111994      }
111995      default: {
111996        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
111997        lastTokenParsed = tokenType;
111998        if( pParse->rc!=SQLITE_OK ){
111999          goto abort_parse;
112000        }
112001        break;
112002      }
112003    }
112004  }
112005abort_parse:
112006  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
112007    if( lastTokenParsed!=TK_SEMI ){
112008      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
112009      pParse->zTail = &zSql[i];
112010    }
112011    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
112012  }
112013#ifdef YYTRACKMAXSTACKDEPTH
112014  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
112015      sqlite3ParserStackPeak(pEngine)
112016  );
112017#endif /* YYDEBUG */
112018  sqlite3ParserFree(pEngine, sqlite3_free);
112019  db->lookaside.bEnabled = enableLookaside;
112020  if( db->mallocFailed ){
112021    pParse->rc = SQLITE_NOMEM;
112022  }
112023  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
112024    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
112025  }
112026  assert( pzErrMsg!=0 );
112027  if( pParse->zErrMsg ){
112028    *pzErrMsg = pParse->zErrMsg;
112029    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
112030    pParse->zErrMsg = 0;
112031    nErr++;
112032  }
112033  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
112034    sqlite3VdbeDelete(pParse->pVdbe);
112035    pParse->pVdbe = 0;
112036  }
112037#ifndef SQLITE_OMIT_SHARED_CACHE
112038  if( pParse->nested==0 ){
112039    sqlite3DbFree(db, pParse->aTableLock);
112040    pParse->aTableLock = 0;
112041    pParse->nTableLock = 0;
112042  }
112043#endif
112044#ifndef SQLITE_OMIT_VIRTUALTABLE
112045  sqlite3_free(pParse->apVtabLock);
112046#endif
112047
112048  if( !IN_DECLARE_VTAB ){
112049    /* If the pParse->declareVtab flag is set, do not delete any table
112050    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
112051    ** will take responsibility for freeing the Table structure.
112052    */
112053    sqlite3DeleteTable(db, pParse->pNewTable);
112054  }
112055
112056  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
112057  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
112058  sqlite3DbFree(db, pParse->azVar);
112059  sqlite3DbFree(db, pParse->aAlias);
112060  while( pParse->pAinc ){
112061    AutoincInfo *p = pParse->pAinc;
112062    pParse->pAinc = p->pNext;
112063    sqlite3DbFree(db, p);
112064  }
112065  while( pParse->pZombieTab ){
112066    Table *p = pParse->pZombieTab;
112067    pParse->pZombieTab = p->pNextZombie;
112068    sqlite3DeleteTable(db, p);
112069  }
112070  if( nErr>0 && pParse->rc==SQLITE_OK ){
112071    pParse->rc = SQLITE_ERROR;
112072  }
112073  return nErr;
112074}
112075
112076/************** End of tokenize.c ********************************************/
112077/************** Begin file complete.c ****************************************/
112078/*
112079** 2001 September 15
112080**
112081** The author disclaims copyright to this source code.  In place of
112082** a legal notice, here is a blessing:
112083**
112084**    May you do good and not evil.
112085**    May you find forgiveness for yourself and forgive others.
112086**    May you share freely, never taking more than you give.
112087**
112088*************************************************************************
112089** An tokenizer for SQL
112090**
112091** This file contains C code that implements the sqlite3_complete() API.
112092** This code used to be part of the tokenizer.c source file.  But by
112093** separating it out, the code will be automatically omitted from
112094** static links that do not use it.
112095*/
112096#ifndef SQLITE_OMIT_COMPLETE
112097
112098/*
112099** This is defined in tokenize.c.  We just have to import the definition.
112100*/
112101#ifndef SQLITE_AMALGAMATION
112102#ifdef SQLITE_ASCII
112103#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
112104#endif
112105#ifdef SQLITE_EBCDIC
112106SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
112107#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
112108#endif
112109#endif /* SQLITE_AMALGAMATION */
112110
112111
112112/*
112113** Token types used by the sqlite3_complete() routine.  See the header
112114** comments on that procedure for additional information.
112115*/
112116#define tkSEMI    0
112117#define tkWS      1
112118#define tkOTHER   2
112119#ifndef SQLITE_OMIT_TRIGGER
112120#define tkEXPLAIN 3
112121#define tkCREATE  4
112122#define tkTEMP    5
112123#define tkTRIGGER 6
112124#define tkEND     7
112125#endif
112126
112127/*
112128** Return TRUE if the given SQL string ends in a semicolon.
112129**
112130** Special handling is require for CREATE TRIGGER statements.
112131** Whenever the CREATE TRIGGER keywords are seen, the statement
112132** must end with ";END;".
112133**
112134** This implementation uses a state machine with 8 states:
112135**
112136**   (0) INVALID   We have not yet seen a non-whitespace character.
112137**
112138**   (1) START     At the beginning or end of an SQL statement.  This routine
112139**                 returns 1 if it ends in the START state and 0 if it ends
112140**                 in any other state.
112141**
112142**   (2) NORMAL    We are in the middle of statement which ends with a single
112143**                 semicolon.
112144**
112145**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
112146**                 a statement.
112147**
112148**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
112149**                 statement, possibly preceeded by EXPLAIN and/or followed by
112150**                 TEMP or TEMPORARY
112151**
112152**   (5) TRIGGER   We are in the middle of a trigger definition that must be
112153**                 ended by a semicolon, the keyword END, and another semicolon.
112154**
112155**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
112156**                 the end of a trigger definition.
112157**
112158**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
112159**                 of a trigger difinition.
112160**
112161** Transitions between states above are determined by tokens extracted
112162** from the input.  The following tokens are significant:
112163**
112164**   (0) tkSEMI      A semicolon.
112165**   (1) tkWS        Whitespace.
112166**   (2) tkOTHER     Any other SQL token.
112167**   (3) tkEXPLAIN   The "explain" keyword.
112168**   (4) tkCREATE    The "create" keyword.
112169**   (5) tkTEMP      The "temp" or "temporary" keyword.
112170**   (6) tkTRIGGER   The "trigger" keyword.
112171**   (7) tkEND       The "end" keyword.
112172**
112173** Whitespace never causes a state transition and is always ignored.
112174** This means that a SQL string of all whitespace is invalid.
112175**
112176** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
112177** to recognize the end of a trigger can be omitted.  All we have to do
112178** is look for a semicolon that is not part of an string or comment.
112179*/
112180SQLITE_API int sqlite3_complete(const char *zSql){
112181  u8 state = 0;   /* Current state, using numbers defined in header comment */
112182  u8 token;       /* Value of the next token */
112183
112184#ifndef SQLITE_OMIT_TRIGGER
112185  /* A complex statement machine used to detect the end of a CREATE TRIGGER
112186  ** statement.  This is the normal case.
112187  */
112188  static const u8 trans[8][8] = {
112189                     /* Token:                                                */
112190     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
112191     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
112192     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
112193     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
112194     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
112195     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
112196     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
112197     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
112198     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
112199  };
112200#else
112201  /* If triggers are not supported by this compile then the statement machine
112202  ** used to detect the end of a statement is much simplier
112203  */
112204  static const u8 trans[3][3] = {
112205                     /* Token:           */
112206     /* State:       **  SEMI  WS  OTHER */
112207     /* 0 INVALID: */ {    1,  0,     2, },
112208     /* 1   START: */ {    1,  1,     2, },
112209     /* 2  NORMAL: */ {    1,  2,     2, },
112210  };
112211#endif /* SQLITE_OMIT_TRIGGER */
112212
112213  while( *zSql ){
112214    switch( *zSql ){
112215      case ';': {  /* A semicolon */
112216        token = tkSEMI;
112217        break;
112218      }
112219      case ' ':
112220      case '\r':
112221      case '\t':
112222      case '\n':
112223      case '\f': {  /* White space is ignored */
112224        token = tkWS;
112225        break;
112226      }
112227      case '/': {   /* C-style comments */
112228        if( zSql[1]!='*' ){
112229          token = tkOTHER;
112230          break;
112231        }
112232        zSql += 2;
112233        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
112234        if( zSql[0]==0 ) return 0;
112235        zSql++;
112236        token = tkWS;
112237        break;
112238      }
112239      case '-': {   /* SQL-style comments from "--" to end of line */
112240        if( zSql[1]!='-' ){
112241          token = tkOTHER;
112242          break;
112243        }
112244        while( *zSql && *zSql!='\n' ){ zSql++; }
112245        if( *zSql==0 ) return state==1;
112246        token = tkWS;
112247        break;
112248      }
112249      case '[': {   /* Microsoft-style identifiers in [...] */
112250        zSql++;
112251        while( *zSql && *zSql!=']' ){ zSql++; }
112252        if( *zSql==0 ) return 0;
112253        token = tkOTHER;
112254        break;
112255      }
112256      case '`':     /* Grave-accent quoted symbols used by MySQL */
112257      case '"':     /* single- and double-quoted strings */
112258      case '\'': {
112259        int c = *zSql;
112260        zSql++;
112261        while( *zSql && *zSql!=c ){ zSql++; }
112262        if( *zSql==0 ) return 0;
112263        token = tkOTHER;
112264        break;
112265      }
112266      default: {
112267#ifdef SQLITE_EBCDIC
112268        unsigned char c;
112269#endif
112270        if( IdChar((u8)*zSql) ){
112271          /* Keywords and unquoted identifiers */
112272          int nId;
112273          for(nId=1; IdChar(zSql[nId]); nId++){}
112274#ifdef SQLITE_OMIT_TRIGGER
112275          token = tkOTHER;
112276#else
112277          switch( *zSql ){
112278            case 'c': case 'C': {
112279              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
112280                token = tkCREATE;
112281              }else{
112282                token = tkOTHER;
112283              }
112284              break;
112285            }
112286            case 't': case 'T': {
112287              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
112288                token = tkTRIGGER;
112289              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
112290                token = tkTEMP;
112291              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
112292                token = tkTEMP;
112293              }else{
112294                token = tkOTHER;
112295              }
112296              break;
112297            }
112298            case 'e':  case 'E': {
112299              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
112300                token = tkEND;
112301              }else
112302#ifndef SQLITE_OMIT_EXPLAIN
112303              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
112304                token = tkEXPLAIN;
112305              }else
112306#endif
112307              {
112308                token = tkOTHER;
112309              }
112310              break;
112311            }
112312            default: {
112313              token = tkOTHER;
112314              break;
112315            }
112316          }
112317#endif /* SQLITE_OMIT_TRIGGER */
112318          zSql += nId-1;
112319        }else{
112320          /* Operators and special symbols */
112321          token = tkOTHER;
112322        }
112323        break;
112324      }
112325    }
112326    state = trans[state][token];
112327    zSql++;
112328  }
112329  return state==1;
112330}
112331
112332#ifndef SQLITE_OMIT_UTF16
112333/*
112334** This routine is the same as the sqlite3_complete() routine described
112335** above, except that the parameter is required to be UTF-16 encoded, not
112336** UTF-8.
112337*/
112338SQLITE_API int sqlite3_complete16(const void *zSql){
112339  sqlite3_value *pVal;
112340  char const *zSql8;
112341  int rc = SQLITE_NOMEM;
112342
112343#ifndef SQLITE_OMIT_AUTOINIT
112344  rc = sqlite3_initialize();
112345  if( rc ) return rc;
112346#endif
112347  pVal = sqlite3ValueNew(0);
112348  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
112349  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
112350  if( zSql8 ){
112351    rc = sqlite3_complete(zSql8);
112352  }else{
112353    rc = SQLITE_NOMEM;
112354  }
112355  sqlite3ValueFree(pVal);
112356  return sqlite3ApiExit(0, rc);
112357}
112358#endif /* SQLITE_OMIT_UTF16 */
112359#endif /* SQLITE_OMIT_COMPLETE */
112360
112361/************** End of complete.c ********************************************/
112362/************** Begin file main.c ********************************************/
112363/*
112364** 2001 September 15
112365**
112366** The author disclaims copyright to this source code.  In place of
112367** a legal notice, here is a blessing:
112368**
112369**    May you do good and not evil.
112370**    May you find forgiveness for yourself and forgive others.
112371**    May you share freely, never taking more than you give.
112372**
112373*************************************************************************
112374** Main file for the SQLite library.  The routines in this file
112375** implement the programmer interface to the library.  Routines in
112376** other files are for internal use by SQLite and should not be
112377** accessed by users of the library.
112378*/
112379
112380#ifdef SQLITE_ENABLE_FTS3
112381/************** Include fts3.h in the middle of main.c ***********************/
112382/************** Begin file fts3.h ********************************************/
112383/*
112384** 2006 Oct 10
112385**
112386** The author disclaims copyright to this source code.  In place of
112387** a legal notice, here is a blessing:
112388**
112389**    May you do good and not evil.
112390**    May you find forgiveness for yourself and forgive others.
112391**    May you share freely, never taking more than you give.
112392**
112393******************************************************************************
112394**
112395** This header file is used by programs that want to link against the
112396** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
112397*/
112398
112399#if 0
112400extern "C" {
112401#endif  /* __cplusplus */
112402
112403SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs); // Android Change
112404
112405#if 0
112406}  /* extern "C" */
112407#endif  /* __cplusplus */
112408
112409/************** End of fts3.h ************************************************/
112410/************** Continuing where we left off in main.c ***********************/
112411#endif
112412#ifdef SQLITE_ENABLE_RTREE
112413/************** Include rtree.h in the middle of main.c **********************/
112414/************** Begin file rtree.h *******************************************/
112415/*
112416** 2008 May 26
112417**
112418** The author disclaims copyright to this source code.  In place of
112419** a legal notice, here is a blessing:
112420**
112421**    May you do good and not evil.
112422**    May you find forgiveness for yourself and forgive others.
112423**    May you share freely, never taking more than you give.
112424**
112425******************************************************************************
112426**
112427** This header file is used by programs that want to link against the
112428** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
112429*/
112430
112431#if 0
112432extern "C" {
112433#endif  /* __cplusplus */
112434
112435SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
112436
112437#if 0
112438}  /* extern "C" */
112439#endif  /* __cplusplus */
112440
112441/************** End of rtree.h ***********************************************/
112442/************** Continuing where we left off in main.c ***********************/
112443#endif
112444#ifdef SQLITE_ENABLE_ICU
112445/************** Include sqliteicu.h in the middle of main.c ******************/
112446/************** Begin file sqliteicu.h ***************************************/
112447/*
112448** 2008 May 26
112449**
112450** The author disclaims copyright to this source code.  In place of
112451** a legal notice, here is a blessing:
112452**
112453**    May you do good and not evil.
112454**    May you find forgiveness for yourself and forgive others.
112455**    May you share freely, never taking more than you give.
112456**
112457******************************************************************************
112458**
112459** This header file is used by programs that want to link against the
112460** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
112461*/
112462
112463#if 0
112464extern "C" {
112465#endif  /* __cplusplus */
112466
112467SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
112468
112469#if 0
112470}  /* extern "C" */
112471#endif  /* __cplusplus */
112472
112473
112474/************** End of sqliteicu.h *******************************************/
112475/************** Continuing where we left off in main.c ***********************/
112476#endif
112477
112478#ifndef SQLITE_AMALGAMATION
112479/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
112480** contains the text of SQLITE_VERSION macro.
112481*/
112482SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
112483#endif
112484
112485/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
112486** a pointer to the to the sqlite3_version[] string constant.
112487*/
112488SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
112489
112490/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
112491** pointer to a string constant whose value is the same as the
112492** SQLITE_SOURCE_ID C preprocessor macro.
112493*/
112494SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
112495
112496/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
112497** returns an integer equal to SQLITE_VERSION_NUMBER.
112498*/
112499SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
112500
112501/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
112502** zero if and only if SQLite was compiled with mutexing code omitted due to
112503** the SQLITE_THREADSAFE compile-time option being set to 0.
112504*/
112505SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
112506
112507#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
112508/*
112509** If the following function pointer is not NULL and if
112510** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
112511** I/O active are written using this function.  These messages
112512** are intended for debugging activity only.
112513*/
112514SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
112515#endif
112516
112517/*
112518** If the following global variable points to a string which is the
112519** name of a directory, then that directory will be used to store
112520** temporary files.
112521**
112522** See also the "PRAGMA temp_store_directory" SQL command.
112523*/
112524SQLITE_API char *sqlite3_temp_directory = 0;
112525
112526/*
112527** Initialize SQLite.
112528**
112529** This routine must be called to initialize the memory allocation,
112530** VFS, and mutex subsystems prior to doing any serious work with
112531** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
112532** this routine will be called automatically by key routines such as
112533** sqlite3_open().
112534**
112535** This routine is a no-op except on its very first call for the process,
112536** or for the first call after a call to sqlite3_shutdown.
112537**
112538** The first thread to call this routine runs the initialization to
112539** completion.  If subsequent threads call this routine before the first
112540** thread has finished the initialization process, then the subsequent
112541** threads must block until the first thread finishes with the initialization.
112542**
112543** The first thread might call this routine recursively.  Recursive
112544** calls to this routine should not block, of course.  Otherwise the
112545** initialization process would never complete.
112546**
112547** Let X be the first thread to enter this routine.  Let Y be some other
112548** thread.  Then while the initial invocation of this routine by X is
112549** incomplete, it is required that:
112550**
112551**    *  Calls to this routine from Y must block until the outer-most
112552**       call by X completes.
112553**
112554**    *  Recursive calls to this routine from thread X return immediately
112555**       without blocking.
112556*/
112557SQLITE_API int sqlite3_initialize(void){
112558  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
112559  int rc;                                      /* Result code */
112560
112561#ifdef SQLITE_OMIT_WSD
112562  rc = sqlite3_wsd_init(4096, 24);
112563  if( rc!=SQLITE_OK ){
112564    return rc;
112565  }
112566#endif
112567
112568  /* If SQLite is already completely initialized, then this call
112569  ** to sqlite3_initialize() should be a no-op.  But the initialization
112570  ** must be complete.  So isInit must not be set until the very end
112571  ** of this routine.
112572  */
112573  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
112574
112575  /* Make sure the mutex subsystem is initialized.  If unable to
112576  ** initialize the mutex subsystem, return early with the error.
112577  ** If the system is so sick that we are unable to allocate a mutex,
112578  ** there is not much SQLite is going to be able to do.
112579  **
112580  ** The mutex subsystem must take care of serializing its own
112581  ** initialization.
112582  */
112583  rc = sqlite3MutexInit();
112584  if( rc ) return rc;
112585
112586  /* Initialize the malloc() system and the recursive pInitMutex mutex.
112587  ** This operation is protected by the STATIC_MASTER mutex.  Note that
112588  ** MutexAlloc() is called for a static mutex prior to initializing the
112589  ** malloc subsystem - this implies that the allocation of a static
112590  ** mutex must not require support from the malloc subsystem.
112591  */
112592  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
112593  sqlite3_mutex_enter(pMaster);
112594  sqlite3GlobalConfig.isMutexInit = 1;
112595  if( !sqlite3GlobalConfig.isMallocInit ){
112596    rc = sqlite3MallocInit();
112597  }
112598  if( rc==SQLITE_OK ){
112599    sqlite3GlobalConfig.isMallocInit = 1;
112600    if( !sqlite3GlobalConfig.pInitMutex ){
112601      sqlite3GlobalConfig.pInitMutex =
112602           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
112603      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
112604        rc = SQLITE_NOMEM;
112605      }
112606    }
112607  }
112608  if( rc==SQLITE_OK ){
112609    sqlite3GlobalConfig.nRefInitMutex++;
112610  }
112611  sqlite3_mutex_leave(pMaster);
112612
112613  /* If rc is not SQLITE_OK at this point, then either the malloc
112614  ** subsystem could not be initialized or the system failed to allocate
112615  ** the pInitMutex mutex. Return an error in either case.  */
112616  if( rc!=SQLITE_OK ){
112617    return rc;
112618  }
112619
112620  /* Do the rest of the initialization under the recursive mutex so
112621  ** that we will be able to handle recursive calls into
112622  ** sqlite3_initialize().  The recursive calls normally come through
112623  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
112624  ** recursive calls might also be possible.
112625  **
112626  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
112627  ** to the xInit method, so the xInit method need not be threadsafe.
112628  **
112629  ** The following mutex is what serializes access to the appdef pcache xInit
112630  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
112631  ** call to sqlite3PcacheInitialize().
112632  */
112633  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
112634  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
112635    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
112636    sqlite3GlobalConfig.inProgress = 1;
112637    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
112638    sqlite3RegisterGlobalFunctions();
112639    if( sqlite3GlobalConfig.isPCacheInit==0 ){
112640      rc = sqlite3PcacheInitialize();
112641    }
112642    if( rc==SQLITE_OK ){
112643      sqlite3GlobalConfig.isPCacheInit = 1;
112644      rc = sqlite3OsInit();
112645    }
112646    if( rc==SQLITE_OK ){
112647      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
112648          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
112649      sqlite3GlobalConfig.isInit = 1;
112650    }
112651    sqlite3GlobalConfig.inProgress = 0;
112652  }
112653  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
112654
112655  /* Go back under the static mutex and clean up the recursive
112656  ** mutex to prevent a resource leak.
112657  */
112658  sqlite3_mutex_enter(pMaster);
112659  sqlite3GlobalConfig.nRefInitMutex--;
112660  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
112661    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
112662    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
112663    sqlite3GlobalConfig.pInitMutex = 0;
112664  }
112665  sqlite3_mutex_leave(pMaster);
112666
112667  /* The following is just a sanity check to make sure SQLite has
112668  ** been compiled correctly.  It is important to run this code, but
112669  ** we don't want to run it too often and soak up CPU cycles for no
112670  ** reason.  So we run it once during initialization.
112671  */
112672#ifndef NDEBUG
112673#ifndef SQLITE_OMIT_FLOATING_POINT
112674  /* This section of code's only "output" is via assert() statements. */
112675  if ( rc==SQLITE_OK ){
112676    u64 x = (((u64)1)<<63)-1;
112677    double y;
112678    assert(sizeof(x)==8);
112679    assert(sizeof(x)==sizeof(y));
112680    memcpy(&y, &x, 8);
112681    assert( sqlite3IsNaN(y) );
112682  }
112683#endif
112684#endif
112685
112686  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
112687  ** compile-time option.
112688  */
112689#ifdef SQLITE_EXTRA_INIT
112690  if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
112691    int SQLITE_EXTRA_INIT(const char*);
112692    rc = SQLITE_EXTRA_INIT(0);
112693  }
112694#endif
112695
112696  return rc;
112697}
112698
112699/*
112700** Undo the effects of sqlite3_initialize().  Must not be called while
112701** there are outstanding database connections or memory allocations or
112702** while any part of SQLite is otherwise in use in any thread.  This
112703** routine is not threadsafe.  But it is safe to invoke this routine
112704** on when SQLite is already shut down.  If SQLite is already shut down
112705** when this routine is invoked, then this routine is a harmless no-op.
112706*/
112707SQLITE_API int sqlite3_shutdown(void){
112708  if( sqlite3GlobalConfig.isInit ){
112709#ifdef SQLITE_EXTRA_SHUTDOWN
112710    void SQLITE_EXTRA_SHUTDOWN(void);
112711    SQLITE_EXTRA_SHUTDOWN();
112712#endif
112713    sqlite3_os_end();
112714    sqlite3_reset_auto_extension();
112715    sqlite3GlobalConfig.isInit = 0;
112716  }
112717  if( sqlite3GlobalConfig.isPCacheInit ){
112718    sqlite3PcacheShutdown();
112719    sqlite3GlobalConfig.isPCacheInit = 0;
112720  }
112721  if( sqlite3GlobalConfig.isMallocInit ){
112722    sqlite3MallocEnd();
112723    sqlite3GlobalConfig.isMallocInit = 0;
112724  }
112725  if( sqlite3GlobalConfig.isMutexInit ){
112726    sqlite3MutexEnd();
112727    sqlite3GlobalConfig.isMutexInit = 0;
112728  }
112729
112730  return SQLITE_OK;
112731}
112732
112733/*
112734** This API allows applications to modify the global configuration of
112735** the SQLite library at run-time.
112736**
112737** This routine should only be called when there are no outstanding
112738** database connections or memory allocations.  This routine is not
112739** threadsafe.  Failure to heed these warnings can lead to unpredictable
112740** behavior.
112741*/
112742SQLITE_API int sqlite3_config(int op, ...){
112743  va_list ap;
112744  int rc = SQLITE_OK;
112745
112746  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
112747  ** the SQLite library is in use. */
112748  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
112749
112750  va_start(ap, op);
112751  switch( op ){
112752
112753    /* Mutex configuration options are only available in a threadsafe
112754    ** compile.
112755    */
112756#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
112757    case SQLITE_CONFIG_SINGLETHREAD: {
112758      /* Disable all mutexing */
112759      sqlite3GlobalConfig.bCoreMutex = 0;
112760      sqlite3GlobalConfig.bFullMutex = 0;
112761      break;
112762    }
112763    case SQLITE_CONFIG_MULTITHREAD: {
112764      /* Disable mutexing of database connections */
112765      /* Enable mutexing of core data structures */
112766      sqlite3GlobalConfig.bCoreMutex = 1;
112767      sqlite3GlobalConfig.bFullMutex = 0;
112768      break;
112769    }
112770    case SQLITE_CONFIG_SERIALIZED: {
112771      /* Enable all mutexing */
112772      sqlite3GlobalConfig.bCoreMutex = 1;
112773      sqlite3GlobalConfig.bFullMutex = 1;
112774      break;
112775    }
112776    case SQLITE_CONFIG_MUTEX: {
112777      /* Specify an alternative mutex implementation */
112778      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
112779      break;
112780    }
112781    case SQLITE_CONFIG_GETMUTEX: {
112782      /* Retrieve the current mutex implementation */
112783      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
112784      break;
112785    }
112786#endif
112787
112788
112789    case SQLITE_CONFIG_MALLOC: {
112790      /* Specify an alternative malloc implementation */
112791      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
112792      break;
112793    }
112794    case SQLITE_CONFIG_GETMALLOC: {
112795      /* Retrieve the current malloc() implementation */
112796      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
112797      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
112798      break;
112799    }
112800    case SQLITE_CONFIG_MEMSTATUS: {
112801      /* Enable or disable the malloc status collection */
112802      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
112803      break;
112804    }
112805    case SQLITE_CONFIG_SCRATCH: {
112806      /* Designate a buffer for scratch memory space */
112807      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
112808      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
112809      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
112810      break;
112811    }
112812    case SQLITE_CONFIG_PAGECACHE: {
112813      /* Designate a buffer for page cache memory space */
112814      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
112815      sqlite3GlobalConfig.szPage = va_arg(ap, int);
112816      sqlite3GlobalConfig.nPage = va_arg(ap, int);
112817      break;
112818    }
112819
112820    case SQLITE_CONFIG_PCACHE: {
112821      /* no-op */
112822      break;
112823    }
112824    case SQLITE_CONFIG_GETPCACHE: {
112825      /* now an error */
112826      rc = SQLITE_ERROR;
112827      break;
112828    }
112829
112830    case SQLITE_CONFIG_PCACHE2: {
112831      /* Specify an alternative page cache implementation */
112832      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
112833      break;
112834    }
112835    case SQLITE_CONFIG_GETPCACHE2: {
112836      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
112837        sqlite3PCacheSetDefault();
112838      }
112839      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
112840      break;
112841    }
112842
112843#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
112844    case SQLITE_CONFIG_HEAP: {
112845      /* Designate a buffer for heap memory space */
112846      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
112847      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
112848      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
112849
112850      if( sqlite3GlobalConfig.mnReq<1 ){
112851        sqlite3GlobalConfig.mnReq = 1;
112852      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
112853        /* cap min request size at 2^12 */
112854        sqlite3GlobalConfig.mnReq = (1<<12);
112855      }
112856
112857      if( sqlite3GlobalConfig.pHeap==0 ){
112858        /* If the heap pointer is NULL, then restore the malloc implementation
112859        ** back to NULL pointers too.  This will cause the malloc to go
112860        ** back to its default implementation when sqlite3_initialize() is
112861        ** run.
112862        */
112863        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
112864      }else{
112865        /* The heap pointer is not NULL, then install one of the
112866        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
112867        ** ENABLE_MEMSYS5 is defined, return an error.
112868        */
112869#ifdef SQLITE_ENABLE_MEMSYS3
112870        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
112871#endif
112872#ifdef SQLITE_ENABLE_MEMSYS5
112873        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
112874#endif
112875      }
112876      break;
112877    }
112878#endif
112879
112880    case SQLITE_CONFIG_LOOKASIDE: {
112881      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
112882      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
112883      break;
112884    }
112885
112886    /* Record a pointer to the logger funcction and its first argument.
112887    ** The default is NULL.  Logging is disabled if the function pointer is
112888    ** NULL.
112889    */
112890    case SQLITE_CONFIG_LOG: {
112891      /* MSVC is picky about pulling func ptrs from va lists.
112892      ** http://support.microsoft.com/kb/47961
112893      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
112894      */
112895      typedef void(*LOGFUNC_t)(void*,int,const char*);
112896      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
112897      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
112898      break;
112899    }
112900
112901    case SQLITE_CONFIG_URI: {
112902      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
112903      break;
112904    }
112905
112906    default: {
112907      rc = SQLITE_ERROR;
112908      break;
112909    }
112910  }
112911  va_end(ap);
112912  return rc;
112913}
112914
112915/*
112916** Set up the lookaside buffers for a database connection.
112917** Return SQLITE_OK on success.
112918** If lookaside is already active, return SQLITE_BUSY.
112919**
112920** The sz parameter is the number of bytes in each lookaside slot.
112921** The cnt parameter is the number of slots.  If pStart is NULL the
112922** space for the lookaside memory is obtained from sqlite3_malloc().
112923** If pStart is not NULL then it is sz*cnt bytes of memory to use for
112924** the lookaside memory.
112925*/
112926static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
112927  void *pStart;
112928  if( db->lookaside.nOut ){
112929    return SQLITE_BUSY;
112930  }
112931  /* Free any existing lookaside buffer for this handle before
112932  ** allocating a new one so we don't have to have space for
112933  ** both at the same time.
112934  */
112935  if( db->lookaside.bMalloced ){
112936    sqlite3_free(db->lookaside.pStart);
112937  }
112938  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
112939  ** than a pointer to be useful.
112940  */
112941  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
112942  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
112943  if( cnt<0 ) cnt = 0;
112944  if( sz==0 || cnt==0 ){
112945    sz = 0;
112946    pStart = 0;
112947  }else if( pBuf==0 ){
112948    sqlite3BeginBenignMalloc();
112949    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
112950    sqlite3EndBenignMalloc();
112951    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
112952  }else{
112953    pStart = pBuf;
112954  }
112955  db->lookaside.pStart = pStart;
112956  db->lookaside.pFree = 0;
112957  db->lookaside.sz = (u16)sz;
112958  if( pStart ){
112959    int i;
112960    LookasideSlot *p;
112961    assert( sz > (int)sizeof(LookasideSlot*) );
112962    p = (LookasideSlot*)pStart;
112963    for(i=cnt-1; i>=0; i--){
112964      p->pNext = db->lookaside.pFree;
112965      db->lookaside.pFree = p;
112966      p = (LookasideSlot*)&((u8*)p)[sz];
112967    }
112968    db->lookaside.pEnd = p;
112969    db->lookaside.bEnabled = 1;
112970    db->lookaside.bMalloced = pBuf==0 ?1:0;
112971  }else{
112972    db->lookaside.pEnd = 0;
112973    db->lookaside.bEnabled = 0;
112974    db->lookaside.bMalloced = 0;
112975  }
112976  return SQLITE_OK;
112977}
112978
112979/*
112980** Return the mutex associated with a database connection.
112981*/
112982SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
112983  return db->mutex;
112984}
112985
112986/*
112987** Free up as much memory as we can from the given database
112988** connection.
112989*/
112990SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
112991  int i;
112992  sqlite3_mutex_enter(db->mutex);
112993  sqlite3BtreeEnterAll(db);
112994  for(i=0; i<db->nDb; i++){
112995    Btree *pBt = db->aDb[i].pBt;
112996    if( pBt ){
112997      Pager *pPager = sqlite3BtreePager(pBt);
112998      sqlite3PagerShrink(pPager);
112999    }
113000  }
113001  sqlite3BtreeLeaveAll(db);
113002  sqlite3_mutex_leave(db->mutex);
113003  return SQLITE_OK;
113004}
113005
113006/*
113007** Configuration settings for an individual database connection
113008*/
113009SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
113010  va_list ap;
113011  int rc;
113012  va_start(ap, op);
113013  switch( op ){
113014    case SQLITE_DBCONFIG_LOOKASIDE: {
113015      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
113016      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
113017      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
113018      rc = setupLookaside(db, pBuf, sz, cnt);
113019      break;
113020    }
113021    default: {
113022      static const struct {
113023        int op;      /* The opcode */
113024        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
113025      } aFlagOp[] = {
113026        { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
113027        { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
113028      };
113029      unsigned int i;
113030      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
113031      for(i=0; i<ArraySize(aFlagOp); i++){
113032        if( aFlagOp[i].op==op ){
113033          int onoff = va_arg(ap, int);
113034          int *pRes = va_arg(ap, int*);
113035          int oldFlags = db->flags;
113036          if( onoff>0 ){
113037            db->flags |= aFlagOp[i].mask;
113038          }else if( onoff==0 ){
113039            db->flags &= ~aFlagOp[i].mask;
113040          }
113041          if( oldFlags!=db->flags ){
113042            sqlite3ExpirePreparedStatements(db);
113043          }
113044          if( pRes ){
113045            *pRes = (db->flags & aFlagOp[i].mask)!=0;
113046          }
113047          rc = SQLITE_OK;
113048          break;
113049        }
113050      }
113051      break;
113052    }
113053  }
113054  va_end(ap);
113055  return rc;
113056}
113057
113058
113059/*
113060** Return true if the buffer z[0..n-1] contains all spaces.
113061*/
113062static int allSpaces(const char *z, int n){
113063  while( n>0 && z[n-1]==' ' ){ n--; }
113064  return n==0;
113065}
113066
113067/*
113068** This is the default collating function named "BINARY" which is always
113069** available.
113070**
113071** If the padFlag argument is not NULL then space padding at the end
113072** of strings is ignored.  This implements the RTRIM collation.
113073*/
113074static int binCollFunc(
113075  void *padFlag,
113076  int nKey1, const void *pKey1,
113077  int nKey2, const void *pKey2
113078){
113079  int rc, n;
113080  n = nKey1<nKey2 ? nKey1 : nKey2;
113081  rc = memcmp(pKey1, pKey2, n);
113082  if( rc==0 ){
113083    if( padFlag
113084     && allSpaces(((char*)pKey1)+n, nKey1-n)
113085     && allSpaces(((char*)pKey2)+n, nKey2-n)
113086    ){
113087      /* Leave rc unchanged at 0 */
113088    }else{
113089      rc = nKey1 - nKey2;
113090    }
113091  }
113092  return rc;
113093}
113094
113095/*
113096** Another built-in collating sequence: NOCASE.
113097**
113098** This collating sequence is intended to be used for "case independant
113099** comparison". SQLite's knowledge of upper and lower case equivalents
113100** extends only to the 26 characters used in the English language.
113101**
113102** At the moment there is only a UTF-8 implementation.
113103*/
113104static int nocaseCollatingFunc(
113105  void *NotUsed,
113106  int nKey1, const void *pKey1,
113107  int nKey2, const void *pKey2
113108){
113109  int r = sqlite3StrNICmp(
113110      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
113111  UNUSED_PARAMETER(NotUsed);
113112  if( 0==r ){
113113    r = nKey1-nKey2;
113114  }
113115  return r;
113116}
113117
113118/*
113119** Return the ROWID of the most recent insert
113120*/
113121SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
113122  return db->lastRowid;
113123}
113124
113125/*
113126** Return the number of changes in the most recent call to sqlite3_exec().
113127*/
113128SQLITE_API int sqlite3_changes(sqlite3 *db){
113129  return db->nChange;
113130}
113131
113132/*
113133** Return the number of changes since the database handle was opened.
113134*/
113135SQLITE_API int sqlite3_total_changes(sqlite3 *db){
113136  return db->nTotalChange;
113137}
113138
113139/*
113140** Close all open savepoints. This function only manipulates fields of the
113141** database handle object, it does not close any savepoints that may be open
113142** at the b-tree/pager level.
113143*/
113144SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
113145  while( db->pSavepoint ){
113146    Savepoint *pTmp = db->pSavepoint;
113147    db->pSavepoint = pTmp->pNext;
113148    sqlite3DbFree(db, pTmp);
113149  }
113150  db->nSavepoint = 0;
113151  db->nStatement = 0;
113152  db->isTransactionSavepoint = 0;
113153}
113154
113155/*
113156** Invoke the destructor function associated with FuncDef p, if any. Except,
113157** if this is not the last copy of the function, do not invoke it. Multiple
113158** copies of a single function are created when create_function() is called
113159** with SQLITE_ANY as the encoding.
113160*/
113161static void functionDestroy(sqlite3 *db, FuncDef *p){
113162  FuncDestructor *pDestructor = p->pDestructor;
113163  if( pDestructor ){
113164    pDestructor->nRef--;
113165    if( pDestructor->nRef==0 ){
113166      pDestructor->xDestroy(pDestructor->pUserData);
113167      sqlite3DbFree(db, pDestructor);
113168    }
113169  }
113170}
113171
113172/*
113173** Close an existing SQLite database
113174*/
113175SQLITE_API int sqlite3_close(sqlite3 *db){
113176  HashElem *i;                    /* Hash table iterator */
113177  int j;
113178
113179  if( !db ){
113180    return SQLITE_OK;
113181  }
113182  if( !sqlite3SafetyCheckSickOrOk(db) ){
113183    return SQLITE_MISUSE_BKPT;
113184  }
113185  sqlite3_mutex_enter(db->mutex);
113186
113187  /* Force xDestroy calls on all virtual tables */
113188  sqlite3ResetInternalSchema(db, -1);
113189
113190  /* If a transaction is open, the ResetInternalSchema() call above
113191  ** will not have called the xDisconnect() method on any virtual
113192  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
113193  ** call will do so. We need to do this before the check for active
113194  ** SQL statements below, as the v-table implementation may be storing
113195  ** some prepared statements internally.
113196  */
113197  sqlite3VtabRollback(db);
113198
113199  /* If there are any outstanding VMs, return SQLITE_BUSY. */
113200  if( db->pVdbe ){
113201    sqlite3Error(db, SQLITE_BUSY,
113202        "unable to close due to unfinalised statements");
113203    sqlite3_mutex_leave(db->mutex);
113204    return SQLITE_BUSY;
113205  }
113206  assert( sqlite3SafetyCheckSickOrOk(db) );
113207
113208  for(j=0; j<db->nDb; j++){
113209    Btree *pBt = db->aDb[j].pBt;
113210    if( pBt && sqlite3BtreeIsInBackup(pBt) ){
113211      sqlite3Error(db, SQLITE_BUSY,
113212          "unable to close due to unfinished backup operation");
113213      sqlite3_mutex_leave(db->mutex);
113214      return SQLITE_BUSY;
113215    }
113216  }
113217
113218  /* Free any outstanding Savepoint structures. */
113219  sqlite3CloseSavepoints(db);
113220
113221  for(j=0; j<db->nDb; j++){
113222    struct Db *pDb = &db->aDb[j];
113223    if( pDb->pBt ){
113224      sqlite3BtreeClose(pDb->pBt);
113225      pDb->pBt = 0;
113226      if( j!=1 ){
113227        pDb->pSchema = 0;
113228      }
113229    }
113230  }
113231  sqlite3ResetInternalSchema(db, -1);
113232
113233  /* Tell the code in notify.c that the connection no longer holds any
113234  ** locks and does not require any further unlock-notify callbacks.
113235  */
113236  sqlite3ConnectionClosed(db);
113237
113238  assert( db->nDb<=2 );
113239  assert( db->aDb==db->aDbStatic );
113240  for(j=0; j<ArraySize(db->aFunc.a); j++){
113241    FuncDef *pNext, *pHash, *p;
113242    for(p=db->aFunc.a[j]; p; p=pHash){
113243      pHash = p->pHash;
113244      while( p ){
113245        functionDestroy(db, p);
113246        pNext = p->pNext;
113247        sqlite3DbFree(db, p);
113248        p = pNext;
113249      }
113250    }
113251  }
113252  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
113253    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
113254    /* Invoke any destructors registered for collation sequence user data. */
113255    for(j=0; j<3; j++){
113256      if( pColl[j].xDel ){
113257        pColl[j].xDel(pColl[j].pUser);
113258      }
113259    }
113260    sqlite3DbFree(db, pColl);
113261  }
113262  sqlite3HashClear(&db->aCollSeq);
113263#ifndef SQLITE_OMIT_VIRTUALTABLE
113264  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
113265    Module *pMod = (Module *)sqliteHashData(i);
113266    if( pMod->xDestroy ){
113267      pMod->xDestroy(pMod->pAux);
113268    }
113269    sqlite3DbFree(db, pMod);
113270  }
113271  sqlite3HashClear(&db->aModule);
113272#endif
113273
113274  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
113275  if( db->pErr ){
113276    sqlite3ValueFree(db->pErr);
113277  }
113278  sqlite3CloseExtensions(db);
113279
113280  db->magic = SQLITE_MAGIC_ERROR;
113281
113282  /* The temp-database schema is allocated differently from the other schema
113283  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
113284  ** So it needs to be freed here. Todo: Why not roll the temp schema into
113285  ** the same sqliteMalloc() as the one that allocates the database
113286  ** structure?
113287  */
113288  sqlite3DbFree(db, db->aDb[1].pSchema);
113289  sqlite3_mutex_leave(db->mutex);
113290  db->magic = SQLITE_MAGIC_CLOSED;
113291  sqlite3_mutex_free(db->mutex);
113292  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
113293  if( db->lookaside.bMalloced ){
113294    sqlite3_free(db->lookaside.pStart);
113295  }
113296  sqlite3_free(db);
113297  return SQLITE_OK;
113298}
113299
113300/*
113301** Rollback all database files.  If tripCode is not SQLITE_OK, then
113302** any open cursors are invalidated ("tripped" - as in "tripping a circuit
113303** breaker") and made to return tripCode if there are any further
113304** attempts to use that cursor.
113305*/
113306SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
113307  int i;
113308  int inTrans = 0;
113309  assert( sqlite3_mutex_held(db->mutex) );
113310  sqlite3BeginBenignMalloc();
113311  for(i=0; i<db->nDb; i++){
113312    Btree *p = db->aDb[i].pBt;
113313    if( p ){
113314      if( sqlite3BtreeIsInTrans(p) ){
113315        inTrans = 1;
113316      }
113317      sqlite3BtreeRollback(p, tripCode);
113318      db->aDb[i].inTrans = 0;
113319    }
113320  }
113321  sqlite3VtabRollback(db);
113322  sqlite3EndBenignMalloc();
113323
113324  if( db->flags&SQLITE_InternChanges ){
113325    sqlite3ExpirePreparedStatements(db);
113326    sqlite3ResetInternalSchema(db, -1);
113327  }
113328
113329  /* Any deferred constraint violations have now been resolved. */
113330  db->nDeferredCons = 0;
113331
113332  /* If one has been configured, invoke the rollback-hook callback */
113333  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
113334    db->xRollbackCallback(db->pRollbackArg);
113335  }
113336}
113337
113338/*
113339** Return a static string that describes the kind of error specified in the
113340** argument.
113341*/
113342SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
113343  static const char* const aMsg[] = {
113344    /* SQLITE_OK          */ "not an error",
113345    /* SQLITE_ERROR       */ "SQL logic error or missing database",
113346    /* SQLITE_INTERNAL    */ 0,
113347    /* SQLITE_PERM        */ "access permission denied",
113348    /* SQLITE_ABORT       */ "callback requested query abort",
113349    /* SQLITE_BUSY        */ "database is locked",
113350    /* SQLITE_LOCKED      */ "database table is locked",
113351    /* SQLITE_NOMEM       */ "out of memory",
113352    /* SQLITE_READONLY    */ "attempt to write a readonly database",
113353    /* SQLITE_INTERRUPT   */ "interrupted",
113354    /* SQLITE_IOERR       */ "disk I/O error",
113355    /* SQLITE_CORRUPT     */ "database disk image is malformed",
113356    /* SQLITE_NOTFOUND    */ "unknown operation",
113357    /* SQLITE_FULL        */ "database or disk is full",
113358    /* SQLITE_CANTOPEN    */ "unable to open database file",
113359    /* SQLITE_PROTOCOL    */ "locking protocol",
113360    /* SQLITE_EMPTY       */ "table contains no data",
113361    /* SQLITE_SCHEMA      */ "database schema has changed",
113362    /* SQLITE_TOOBIG      */ "string or blob too big",
113363    /* SQLITE_CONSTRAINT  */ "constraint failed",
113364    /* SQLITE_MISMATCH    */ "datatype mismatch",
113365    /* SQLITE_MISUSE      */ "library routine called out of sequence",
113366    /* SQLITE_NOLFS       */ "large file support is disabled",
113367    /* SQLITE_AUTH        */ "authorization denied",
113368    /* SQLITE_FORMAT      */ "auxiliary database format error",
113369    /* SQLITE_RANGE       */ "bind or column index out of range",
113370    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
113371  };
113372  const char *zErr = "unknown error";
113373  switch( rc ){
113374    case SQLITE_ABORT_ROLLBACK: {
113375      zErr = "abort due to ROLLBACK";
113376      break;
113377    }
113378    default: {
113379      rc &= 0xff;
113380      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
113381        zErr = aMsg[rc];
113382      }
113383      break;
113384    }
113385  }
113386  return zErr;
113387}
113388
113389/*
113390** This routine implements a busy callback that sleeps and tries
113391** again until a timeout value is reached.  The timeout value is
113392** an integer number of milliseconds passed in as the first
113393** argument.
113394*/
113395static int sqliteDefaultBusyCallback(
113396 void *ptr,               /* Database connection */
113397 int count                /* Number of times table has been busy */
113398){
113399#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
113400  static const u8 delays[] =
113401     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
113402  static const u8 totals[] =
113403     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
113404# define NDELAY ArraySize(delays)
113405  sqlite3 *db = (sqlite3 *)ptr;
113406  int timeout = db->busyTimeout;
113407  int delay, prior;
113408
113409  assert( count>=0 );
113410  if( count < NDELAY ){
113411    delay = delays[count];
113412    prior = totals[count];
113413  }else{
113414    delay = delays[NDELAY-1];
113415    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
113416  }
113417  if( prior + delay > timeout ){
113418    delay = timeout - prior;
113419    if( delay<=0 ) return 0;
113420  }
113421  sqlite3OsSleep(db->pVfs, delay*1000);
113422  return 1;
113423#else
113424  sqlite3 *db = (sqlite3 *)ptr;
113425  int timeout = ((sqlite3 *)ptr)->busyTimeout;
113426  if( (count+1)*1000 > timeout ){
113427    return 0;
113428  }
113429  sqlite3OsSleep(db->pVfs, 1000000);
113430  return 1;
113431#endif
113432}
113433
113434/*
113435** Invoke the given busy handler.
113436**
113437** This routine is called when an operation failed with a lock.
113438** If this routine returns non-zero, the lock is retried.  If it
113439** returns 0, the operation aborts with an SQLITE_BUSY error.
113440*/
113441SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
113442  int rc;
113443  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
113444  rc = p->xFunc(p->pArg, p->nBusy);
113445  if( rc==0 ){
113446    p->nBusy = -1;
113447  }else{
113448    p->nBusy++;
113449  }
113450  return rc;
113451}
113452
113453/*
113454** This routine sets the busy callback for an Sqlite database to the
113455** given callback function with the given argument.
113456*/
113457SQLITE_API int sqlite3_busy_handler(
113458  sqlite3 *db,
113459  int (*xBusy)(void*,int),
113460  void *pArg
113461){
113462  sqlite3_mutex_enter(db->mutex);
113463  db->busyHandler.xFunc = xBusy;
113464  db->busyHandler.pArg = pArg;
113465  db->busyHandler.nBusy = 0;
113466  sqlite3_mutex_leave(db->mutex);
113467  return SQLITE_OK;
113468}
113469
113470#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
113471/*
113472** This routine sets the progress callback for an Sqlite database to the
113473** given callback function with the given argument. The progress callback will
113474** be invoked every nOps opcodes.
113475*/
113476SQLITE_API void sqlite3_progress_handler(
113477  sqlite3 *db,
113478  int nOps,
113479  int (*xProgress)(void*),
113480  void *pArg
113481){
113482  sqlite3_mutex_enter(db->mutex);
113483  if( nOps>0 ){
113484    db->xProgress = xProgress;
113485    db->nProgressOps = nOps;
113486    db->pProgressArg = pArg;
113487  }else{
113488    db->xProgress = 0;
113489    db->nProgressOps = 0;
113490    db->pProgressArg = 0;
113491  }
113492  sqlite3_mutex_leave(db->mutex);
113493}
113494#endif
113495
113496
113497/*
113498** This routine installs a default busy handler that waits for the
113499** specified number of milliseconds before returning 0.
113500*/
113501SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
113502  if( ms>0 ){
113503    db->busyTimeout = ms;
113504    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
113505  }else{
113506    sqlite3_busy_handler(db, 0, 0);
113507  }
113508  return SQLITE_OK;
113509}
113510
113511/*
113512** Cause any pending operation to stop at its earliest opportunity.
113513*/
113514SQLITE_API void sqlite3_interrupt(sqlite3 *db){
113515  db->u1.isInterrupted = 1;
113516}
113517
113518
113519/*
113520** This function is exactly the same as sqlite3_create_function(), except
113521** that it is designed to be called by internal code. The difference is
113522** that if a malloc() fails in sqlite3_create_function(), an error code
113523** is returned and the mallocFailed flag cleared.
113524*/
113525SQLITE_PRIVATE int sqlite3CreateFunc(
113526  sqlite3 *db,
113527  const char *zFunctionName,
113528  int nArg,
113529  int enc,
113530  void *pUserData,
113531  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
113532  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
113533  void (*xFinal)(sqlite3_context*),
113534  FuncDestructor *pDestructor
113535){
113536  FuncDef *p;
113537  int nName;
113538
113539  assert( sqlite3_mutex_held(db->mutex) );
113540  if( zFunctionName==0 ||
113541      (xFunc && (xFinal || xStep)) ||
113542      (!xFunc && (xFinal && !xStep)) ||
113543      (!xFunc && (!xFinal && xStep)) ||
113544      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
113545      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
113546    return SQLITE_MISUSE_BKPT;
113547  }
113548
113549#ifndef SQLITE_OMIT_UTF16
113550  /* If SQLITE_UTF16 is specified as the encoding type, transform this
113551  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
113552  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
113553  **
113554  ** If SQLITE_ANY is specified, add three versions of the function
113555  ** to the hash table.
113556  */
113557  if( enc==SQLITE_UTF16 ){
113558    enc = SQLITE_UTF16NATIVE;
113559  }else if( enc==SQLITE_ANY ){
113560    int rc;
113561    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
113562         pUserData, xFunc, xStep, xFinal, pDestructor);
113563    if( rc==SQLITE_OK ){
113564      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
113565          pUserData, xFunc, xStep, xFinal, pDestructor);
113566    }
113567    if( rc!=SQLITE_OK ){
113568      return rc;
113569    }
113570    enc = SQLITE_UTF16BE;
113571  }
113572#else
113573  enc = SQLITE_UTF8;
113574#endif
113575
113576  /* Check if an existing function is being overridden or deleted. If so,
113577  ** and there are active VMs, then return SQLITE_BUSY. If a function
113578  ** is being overridden/deleted but there are no active VMs, allow the
113579  ** operation to continue but invalidate all precompiled statements.
113580  */
113581  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
113582  if( p && p->iPrefEnc==enc && p->nArg==nArg ){
113583    if( db->activeVdbeCnt ){
113584      sqlite3Error(db, SQLITE_BUSY,
113585        "unable to delete/modify user-function due to active statements");
113586      assert( !db->mallocFailed );
113587      return SQLITE_BUSY;
113588    }else{
113589      sqlite3ExpirePreparedStatements(db);
113590    }
113591  }
113592
113593  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
113594  assert(p || db->mallocFailed);
113595  if( !p ){
113596    return SQLITE_NOMEM;
113597  }
113598
113599  /* If an older version of the function with a configured destructor is
113600  ** being replaced invoke the destructor function here. */
113601  functionDestroy(db, p);
113602
113603  if( pDestructor ){
113604    pDestructor->nRef++;
113605  }
113606  p->pDestructor = pDestructor;
113607  p->flags = 0;
113608  p->xFunc = xFunc;
113609  p->xStep = xStep;
113610  p->xFinalize = xFinal;
113611  p->pUserData = pUserData;
113612  p->nArg = (u16)nArg;
113613  return SQLITE_OK;
113614}
113615
113616/*
113617** Create new user functions.
113618*/
113619SQLITE_API int sqlite3_create_function(
113620  sqlite3 *db,
113621  const char *zFunc,
113622  int nArg,
113623  int enc,
113624  void *p,
113625  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
113626  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
113627  void (*xFinal)(sqlite3_context*)
113628){
113629  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
113630                                    xFinal, 0);
113631}
113632
113633SQLITE_API int sqlite3_create_function_v2(
113634  sqlite3 *db,
113635  const char *zFunc,
113636  int nArg,
113637  int enc,
113638  void *p,
113639  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
113640  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
113641  void (*xFinal)(sqlite3_context*),
113642  void (*xDestroy)(void *)
113643){
113644  int rc = SQLITE_ERROR;
113645  FuncDestructor *pArg = 0;
113646  sqlite3_mutex_enter(db->mutex);
113647  if( xDestroy ){
113648    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
113649    if( !pArg ){
113650      xDestroy(p);
113651      goto out;
113652    }
113653    pArg->xDestroy = xDestroy;
113654    pArg->pUserData = p;
113655  }
113656  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
113657  if( pArg && pArg->nRef==0 ){
113658    assert( rc!=SQLITE_OK );
113659    xDestroy(p);
113660    sqlite3DbFree(db, pArg);
113661  }
113662
113663 out:
113664  rc = sqlite3ApiExit(db, rc);
113665  sqlite3_mutex_leave(db->mutex);
113666  return rc;
113667}
113668
113669#ifndef SQLITE_OMIT_UTF16
113670SQLITE_API int sqlite3_create_function16(
113671  sqlite3 *db,
113672  const void *zFunctionName,
113673  int nArg,
113674  int eTextRep,
113675  void *p,
113676  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
113677  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
113678  void (*xFinal)(sqlite3_context*)
113679){
113680  int rc;
113681  char *zFunc8;
113682  sqlite3_mutex_enter(db->mutex);
113683  assert( !db->mallocFailed );
113684  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
113685  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
113686  sqlite3DbFree(db, zFunc8);
113687  rc = sqlite3ApiExit(db, rc);
113688  sqlite3_mutex_leave(db->mutex);
113689  return rc;
113690}
113691#endif
113692
113693
113694/*
113695** Declare that a function has been overloaded by a virtual table.
113696**
113697** If the function already exists as a regular global function, then
113698** this routine is a no-op.  If the function does not exist, then create
113699** a new one that always throws a run-time error.
113700**
113701** When virtual tables intend to provide an overloaded function, they
113702** should call this routine to make sure the global function exists.
113703** A global function must exist in order for name resolution to work
113704** properly.
113705*/
113706SQLITE_API int sqlite3_overload_function(
113707  sqlite3 *db,
113708  const char *zName,
113709  int nArg
113710){
113711  int nName = sqlite3Strlen30(zName);
113712  int rc = SQLITE_OK;
113713  sqlite3_mutex_enter(db->mutex);
113714  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
113715    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
113716                           0, sqlite3InvalidFunction, 0, 0, 0);
113717  }
113718  rc = sqlite3ApiExit(db, rc);
113719  sqlite3_mutex_leave(db->mutex);
113720  return rc;
113721}
113722
113723#ifndef SQLITE_OMIT_TRACE
113724/*
113725** Register a trace function.  The pArg from the previously registered trace
113726** is returned.
113727**
113728** A NULL trace function means that no tracing is executes.  A non-NULL
113729** trace is a pointer to a function that is invoked at the start of each
113730** SQL statement.
113731*/
113732SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
113733  void *pOld;
113734  sqlite3_mutex_enter(db->mutex);
113735  pOld = db->pTraceArg;
113736  db->xTrace = xTrace;
113737  db->pTraceArg = pArg;
113738  sqlite3_mutex_leave(db->mutex);
113739  return pOld;
113740}
113741/*
113742** Register a profile function.  The pArg from the previously registered
113743** profile function is returned.
113744**
113745** A NULL profile function means that no profiling is executes.  A non-NULL
113746** profile is a pointer to a function that is invoked at the conclusion of
113747** each SQL statement that is run.
113748*/
113749SQLITE_API void *sqlite3_profile(
113750  sqlite3 *db,
113751  void (*xProfile)(void*,const char*,sqlite_uint64),
113752  void *pArg
113753){
113754  void *pOld;
113755  sqlite3_mutex_enter(db->mutex);
113756  pOld = db->pProfileArg;
113757  db->xProfile = xProfile;
113758  db->pProfileArg = pArg;
113759  sqlite3_mutex_leave(db->mutex);
113760  return pOld;
113761}
113762#endif /* SQLITE_OMIT_TRACE */
113763
113764/*
113765** Register a function to be invoked when a transaction commits.
113766** If the invoked function returns non-zero, then the commit becomes a
113767** rollback.
113768*/
113769SQLITE_API void *sqlite3_commit_hook(
113770  sqlite3 *db,              /* Attach the hook to this database */
113771  int (*xCallback)(void*),  /* Function to invoke on each commit */
113772  void *pArg                /* Argument to the function */
113773){
113774  void *pOld;
113775  sqlite3_mutex_enter(db->mutex);
113776  pOld = db->pCommitArg;
113777  db->xCommitCallback = xCallback;
113778  db->pCommitArg = pArg;
113779  sqlite3_mutex_leave(db->mutex);
113780  return pOld;
113781}
113782
113783/*
113784** Register a callback to be invoked each time a row is updated,
113785** inserted or deleted using this database connection.
113786*/
113787SQLITE_API void *sqlite3_update_hook(
113788  sqlite3 *db,              /* Attach the hook to this database */
113789  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
113790  void *pArg                /* Argument to the function */
113791){
113792  void *pRet;
113793  sqlite3_mutex_enter(db->mutex);
113794  pRet = db->pUpdateArg;
113795  db->xUpdateCallback = xCallback;
113796  db->pUpdateArg = pArg;
113797  sqlite3_mutex_leave(db->mutex);
113798  return pRet;
113799}
113800
113801/*
113802** Register a callback to be invoked each time a transaction is rolled
113803** back by this database connection.
113804*/
113805SQLITE_API void *sqlite3_rollback_hook(
113806  sqlite3 *db,              /* Attach the hook to this database */
113807  void (*xCallback)(void*), /* Callback function */
113808  void *pArg                /* Argument to the function */
113809){
113810  void *pRet;
113811  sqlite3_mutex_enter(db->mutex);
113812  pRet = db->pRollbackArg;
113813  db->xRollbackCallback = xCallback;
113814  db->pRollbackArg = pArg;
113815  sqlite3_mutex_leave(db->mutex);
113816  return pRet;
113817}
113818
113819#ifndef SQLITE_OMIT_WAL
113820/*
113821** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
113822** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
113823** is greater than sqlite3.pWalArg cast to an integer (the value configured by
113824** wal_autocheckpoint()).
113825*/
113826SQLITE_PRIVATE int sqlite3WalDefaultHook(
113827  void *pClientData,     /* Argument */
113828  sqlite3 *db,           /* Connection */
113829  const char *zDb,       /* Database */
113830  int nFrame             /* Size of WAL */
113831){
113832  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
113833    sqlite3BeginBenignMalloc();
113834    sqlite3_wal_checkpoint(db, zDb);
113835    sqlite3EndBenignMalloc();
113836  }
113837  return SQLITE_OK;
113838}
113839#endif /* SQLITE_OMIT_WAL */
113840
113841/*
113842** Configure an sqlite3_wal_hook() callback to automatically checkpoint
113843** a database after committing a transaction if there are nFrame or
113844** more frames in the log file. Passing zero or a negative value as the
113845** nFrame parameter disables automatic checkpoints entirely.
113846**
113847** The callback registered by this function replaces any existing callback
113848** registered using sqlite3_wal_hook(). Likewise, registering a callback
113849** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
113850** configured by this function.
113851*/
113852SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
113853#ifdef SQLITE_OMIT_WAL
113854  UNUSED_PARAMETER(db);
113855  UNUSED_PARAMETER(nFrame);
113856#else
113857  if( nFrame>0 ){
113858    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
113859  }else{
113860    sqlite3_wal_hook(db, 0, 0);
113861  }
113862#endif
113863  return SQLITE_OK;
113864}
113865
113866/*
113867** Register a callback to be invoked each time a transaction is written
113868** into the write-ahead-log by this database connection.
113869*/
113870SQLITE_API void *sqlite3_wal_hook(
113871  sqlite3 *db,                    /* Attach the hook to this db handle */
113872  int(*xCallback)(void *, sqlite3*, const char*, int),
113873  void *pArg                      /* First argument passed to xCallback() */
113874){
113875#ifndef SQLITE_OMIT_WAL
113876  void *pRet;
113877  sqlite3_mutex_enter(db->mutex);
113878  pRet = db->pWalArg;
113879  db->xWalCallback = xCallback;
113880  db->pWalArg = pArg;
113881  sqlite3_mutex_leave(db->mutex);
113882  return pRet;
113883#else
113884  return 0;
113885#endif
113886}
113887
113888/*
113889** Checkpoint database zDb.
113890*/
113891SQLITE_API int sqlite3_wal_checkpoint_v2(
113892  sqlite3 *db,                    /* Database handle */
113893  const char *zDb,                /* Name of attached database (or NULL) */
113894  int eMode,                      /* SQLITE_CHECKPOINT_* value */
113895  int *pnLog,                     /* OUT: Size of WAL log in frames */
113896  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
113897){
113898#ifdef SQLITE_OMIT_WAL
113899  return SQLITE_OK;
113900#else
113901  int rc;                         /* Return code */
113902  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
113903
113904  /* Initialize the output variables to -1 in case an error occurs. */
113905  if( pnLog ) *pnLog = -1;
113906  if( pnCkpt ) *pnCkpt = -1;
113907
113908  assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
113909  assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
113910  assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
113911  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
113912    return SQLITE_MISUSE;
113913  }
113914
113915  sqlite3_mutex_enter(db->mutex);
113916  if( zDb && zDb[0] ){
113917    iDb = sqlite3FindDbName(db, zDb);
113918  }
113919  if( iDb<0 ){
113920    rc = SQLITE_ERROR;
113921    sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
113922  }else{
113923    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
113924    sqlite3Error(db, rc, 0);
113925  }
113926  rc = sqlite3ApiExit(db, rc);
113927  sqlite3_mutex_leave(db->mutex);
113928  return rc;
113929#endif
113930}
113931
113932
113933/*
113934** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
113935** to contains a zero-length string, all attached databases are
113936** checkpointed.
113937*/
113938SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
113939  return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
113940}
113941
113942#ifndef SQLITE_OMIT_WAL
113943/*
113944** Run a checkpoint on database iDb. This is a no-op if database iDb is
113945** not currently open in WAL mode.
113946**
113947** If a transaction is open on the database being checkpointed, this
113948** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
113949** an error occurs while running the checkpoint, an SQLite error code is
113950** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
113951**
113952** The mutex on database handle db should be held by the caller. The mutex
113953** associated with the specific b-tree being checkpointed is taken by
113954** this function while the checkpoint is running.
113955**
113956** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
113957** checkpointed. If an error is encountered it is returned immediately -
113958** no attempt is made to checkpoint any remaining databases.
113959**
113960** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
113961*/
113962SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
113963  int rc = SQLITE_OK;             /* Return code */
113964  int i;                          /* Used to iterate through attached dbs */
113965  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
113966
113967  assert( sqlite3_mutex_held(db->mutex) );
113968  assert( !pnLog || *pnLog==-1 );
113969  assert( !pnCkpt || *pnCkpt==-1 );
113970
113971  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
113972    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
113973      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
113974      pnLog = 0;
113975      pnCkpt = 0;
113976      if( rc==SQLITE_BUSY ){
113977        bBusy = 1;
113978        rc = SQLITE_OK;
113979      }
113980    }
113981  }
113982
113983  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
113984}
113985#endif /* SQLITE_OMIT_WAL */
113986
113987/*
113988** This function returns true if main-memory should be used instead of
113989** a temporary file for transient pager files and statement journals.
113990** The value returned depends on the value of db->temp_store (runtime
113991** parameter) and the compile time value of SQLITE_TEMP_STORE. The
113992** following table describes the relationship between these two values
113993** and this functions return value.
113994**
113995**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
113996**   -----------------     --------------     ------------------------------
113997**   0                     any                file      (return 0)
113998**   1                     1                  file      (return 0)
113999**   1                     2                  memory    (return 1)
114000**   1                     0                  file      (return 0)
114001**   2                     1                  file      (return 0)
114002**   2                     2                  memory    (return 1)
114003**   2                     0                  memory    (return 1)
114004**   3                     any                memory    (return 1)
114005*/
114006SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
114007#if SQLITE_TEMP_STORE==1
114008  return ( db->temp_store==2 );
114009#endif
114010#if SQLITE_TEMP_STORE==2
114011  return ( db->temp_store!=1 );
114012#endif
114013#if SQLITE_TEMP_STORE==3
114014  return 1;
114015#endif
114016#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
114017  return 0;
114018#endif
114019}
114020
114021/*
114022** Return UTF-8 encoded English language explanation of the most recent
114023** error.
114024*/
114025SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
114026  const char *z;
114027  if( !db ){
114028    return sqlite3ErrStr(SQLITE_NOMEM);
114029  }
114030  if( !sqlite3SafetyCheckSickOrOk(db) ){
114031    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
114032  }
114033  sqlite3_mutex_enter(db->mutex);
114034  if( db->mallocFailed ){
114035    z = sqlite3ErrStr(SQLITE_NOMEM);
114036  }else{
114037    z = (char*)sqlite3_value_text(db->pErr);
114038    assert( !db->mallocFailed );
114039    if( z==0 ){
114040      z = sqlite3ErrStr(db->errCode);
114041    }
114042  }
114043  sqlite3_mutex_leave(db->mutex);
114044  return z;
114045}
114046
114047#ifndef SQLITE_OMIT_UTF16
114048/*
114049** Return UTF-16 encoded English language explanation of the most recent
114050** error.
114051*/
114052SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
114053  static const u16 outOfMem[] = {
114054    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
114055  };
114056  static const u16 misuse[] = {
114057    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
114058    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
114059    'c', 'a', 'l', 'l', 'e', 'd', ' ',
114060    'o', 'u', 't', ' ',
114061    'o', 'f', ' ',
114062    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
114063  };
114064
114065  const void *z;
114066  if( !db ){
114067    return (void *)outOfMem;
114068  }
114069  if( !sqlite3SafetyCheckSickOrOk(db) ){
114070    return (void *)misuse;
114071  }
114072  sqlite3_mutex_enter(db->mutex);
114073  if( db->mallocFailed ){
114074    z = (void *)outOfMem;
114075  }else{
114076    z = sqlite3_value_text16(db->pErr);
114077    if( z==0 ){
114078      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
114079           SQLITE_UTF8, SQLITE_STATIC);
114080      z = sqlite3_value_text16(db->pErr);
114081    }
114082    /* A malloc() may have failed within the call to sqlite3_value_text16()
114083    ** above. If this is the case, then the db->mallocFailed flag needs to
114084    ** be cleared before returning. Do this directly, instead of via
114085    ** sqlite3ApiExit(), to avoid setting the database handle error message.
114086    */
114087    db->mallocFailed = 0;
114088  }
114089  sqlite3_mutex_leave(db->mutex);
114090  return z;
114091}
114092#endif /* SQLITE_OMIT_UTF16 */
114093
114094/*
114095** Return the most recent error code generated by an SQLite routine. If NULL is
114096** passed to this function, we assume a malloc() failed during sqlite3_open().
114097*/
114098SQLITE_API int sqlite3_errcode(sqlite3 *db){
114099  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
114100    return SQLITE_MISUSE_BKPT;
114101  }
114102  if( !db || db->mallocFailed ){
114103    return SQLITE_NOMEM;
114104  }
114105  return db->errCode & db->errMask;
114106}
114107SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
114108  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
114109    return SQLITE_MISUSE_BKPT;
114110  }
114111  if( !db || db->mallocFailed ){
114112    return SQLITE_NOMEM;
114113  }
114114  return db->errCode;
114115}
114116
114117/*
114118** Create a new collating function for database "db".  The name is zName
114119** and the encoding is enc.
114120*/
114121static int createCollation(
114122  sqlite3* db,
114123  const char *zName,
114124  u8 enc,
114125  void* pCtx,
114126  int(*xCompare)(void*,int,const void*,int,const void*),
114127  void(*xDel)(void*)
114128){
114129  CollSeq *pColl;
114130  int enc2;
114131  int nName = sqlite3Strlen30(zName);
114132
114133  assert( sqlite3_mutex_held(db->mutex) );
114134
114135  /* If SQLITE_UTF16 is specified as the encoding type, transform this
114136  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
114137  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
114138  */
114139  enc2 = enc;
114140  testcase( enc2==SQLITE_UTF16 );
114141  testcase( enc2==SQLITE_UTF16_ALIGNED );
114142  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
114143    enc2 = SQLITE_UTF16NATIVE;
114144  }
114145  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
114146    return SQLITE_MISUSE_BKPT;
114147  }
114148
114149  /* Check if this call is removing or replacing an existing collation
114150  ** sequence. If so, and there are active VMs, return busy. If there
114151  ** are no active VMs, invalidate any pre-compiled statements.
114152  */
114153  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
114154  if( pColl && pColl->xCmp ){
114155    if( db->activeVdbeCnt ){
114156      sqlite3Error(db, SQLITE_BUSY,
114157        "unable to delete/modify collation sequence due to active statements");
114158      return SQLITE_BUSY;
114159    }
114160    sqlite3ExpirePreparedStatements(db);
114161
114162    /* If collation sequence pColl was created directly by a call to
114163    ** sqlite3_create_collation, and not generated by synthCollSeq(),
114164    ** then any copies made by synthCollSeq() need to be invalidated.
114165    ** Also, collation destructor - CollSeq.xDel() - function may need
114166    ** to be called.
114167    */
114168    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
114169      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
114170      int j;
114171      for(j=0; j<3; j++){
114172        CollSeq *p = &aColl[j];
114173        if( p->enc==pColl->enc ){
114174          if( p->xDel ){
114175            p->xDel(p->pUser);
114176          }
114177          p->xCmp = 0;
114178        }
114179      }
114180    }
114181  }
114182
114183  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
114184  if( pColl==0 ) return SQLITE_NOMEM;
114185  pColl->xCmp = xCompare;
114186  pColl->pUser = pCtx;
114187  pColl->xDel = xDel;
114188  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
114189  sqlite3Error(db, SQLITE_OK, 0);
114190  return SQLITE_OK;
114191}
114192
114193
114194/*
114195** This array defines hard upper bounds on limit values.  The
114196** initializer must be kept in sync with the SQLITE_LIMIT_*
114197** #defines in sqlite3.h.
114198*/
114199static const int aHardLimit[] = {
114200  SQLITE_MAX_LENGTH,
114201  SQLITE_MAX_SQL_LENGTH,
114202  SQLITE_MAX_COLUMN,
114203  SQLITE_MAX_EXPR_DEPTH,
114204  SQLITE_MAX_COMPOUND_SELECT,
114205  SQLITE_MAX_VDBE_OP,
114206  SQLITE_MAX_FUNCTION_ARG,
114207  SQLITE_MAX_ATTACHED,
114208  SQLITE_MAX_LIKE_PATTERN_LENGTH,
114209  SQLITE_MAX_VARIABLE_NUMBER,
114210  SQLITE_MAX_TRIGGER_DEPTH,
114211};
114212
114213/*
114214** Make sure the hard limits are set to reasonable values
114215*/
114216#if SQLITE_MAX_LENGTH<100
114217# error SQLITE_MAX_LENGTH must be at least 100
114218#endif
114219#if SQLITE_MAX_SQL_LENGTH<100
114220# error SQLITE_MAX_SQL_LENGTH must be at least 100
114221#endif
114222#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
114223# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
114224#endif
114225#if SQLITE_MAX_COMPOUND_SELECT<2
114226# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
114227#endif
114228#if SQLITE_MAX_VDBE_OP<40
114229# error SQLITE_MAX_VDBE_OP must be at least 40
114230#endif
114231#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
114232# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
114233#endif
114234#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
114235# error SQLITE_MAX_ATTACHED must be between 0 and 62
114236#endif
114237#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
114238# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
114239#endif
114240#if SQLITE_MAX_COLUMN>32767
114241# error SQLITE_MAX_COLUMN must not exceed 32767
114242#endif
114243#if SQLITE_MAX_TRIGGER_DEPTH<1
114244# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
114245#endif
114246
114247
114248/*
114249** Change the value of a limit.  Report the old value.
114250** If an invalid limit index is supplied, report -1.
114251** Make no changes but still report the old value if the
114252** new limit is negative.
114253**
114254** A new lower limit does not shrink existing constructs.
114255** It merely prevents new constructs that exceed the limit
114256** from forming.
114257*/
114258SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
114259  int oldLimit;
114260
114261
114262  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
114263  ** there is a hard upper bound set at compile-time by a C preprocessor
114264  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
114265  ** "_MAX_".)
114266  */
114267  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
114268  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
114269  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
114270  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
114271  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
114272  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
114273  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
114274  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
114275  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
114276                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
114277  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
114278  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
114279  assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
114280
114281
114282  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
114283    return -1;
114284  }
114285  oldLimit = db->aLimit[limitId];
114286  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
114287    if( newLimit>aHardLimit[limitId] ){
114288      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
114289    }
114290    db->aLimit[limitId] = newLimit;
114291  }
114292  return oldLimit;                     /* IMP: R-53341-35419 */
114293}
114294
114295/*
114296** This function is used to parse both URIs and non-URI filenames passed by the
114297** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
114298** URIs specified as part of ATTACH statements.
114299**
114300** The first argument to this function is the name of the VFS to use (or
114301** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
114302** query parameter. The second argument contains the URI (or non-URI filename)
114303** itself. When this function is called the *pFlags variable should contain
114304** the default flags to open the database handle with. The value stored in
114305** *pFlags may be updated before returning if the URI filename contains
114306** "cache=xxx" or "mode=xxx" query parameters.
114307**
114308** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
114309** the VFS that should be used to open the database file. *pzFile is set to
114310** point to a buffer containing the name of the file to open. It is the
114311** responsibility of the caller to eventually call sqlite3_free() to release
114312** this buffer.
114313**
114314** If an error occurs, then an SQLite error code is returned and *pzErrMsg
114315** may be set to point to a buffer containing an English language error
114316** message. It is the responsibility of the caller to eventually release
114317** this buffer by calling sqlite3_free().
114318*/
114319SQLITE_PRIVATE int sqlite3ParseUri(
114320  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
114321  const char *zUri,               /* Nul-terminated URI to parse */
114322  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
114323  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
114324  char **pzFile,                  /* OUT: Filename component of URI */
114325  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
114326){
114327  int rc = SQLITE_OK;
114328  unsigned int flags = *pFlags;
114329  const char *zVfs = zDefaultVfs;
114330  char *zFile;
114331  char c;
114332  int nUri = sqlite3Strlen30(zUri);
114333
114334  assert( *pzErrMsg==0 );
114335
114336  if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
114337   && nUri>=5 && memcmp(zUri, "file:", 5)==0
114338  ){
114339    char *zOpt;
114340    int eState;                   /* Parser state when parsing URI */
114341    int iIn;                      /* Input character index */
114342    int iOut = 0;                 /* Output character index */
114343    int nByte = nUri+2;           /* Bytes of space to allocate */
114344
114345    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
114346    ** method that there may be extra parameters following the file-name.  */
114347    flags |= SQLITE_OPEN_URI;
114348
114349    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
114350    zFile = sqlite3_malloc(nByte);
114351    if( !zFile ) return SQLITE_NOMEM;
114352
114353    /* Discard the scheme and authority segments of the URI. */
114354    if( zUri[5]=='/' && zUri[6]=='/' ){
114355      iIn = 7;
114356      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
114357
114358      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
114359        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
114360            iIn-7, &zUri[7]);
114361        rc = SQLITE_ERROR;
114362        goto parse_uri_out;
114363      }
114364    }else{
114365      iIn = 5;
114366    }
114367
114368    /* Copy the filename and any query parameters into the zFile buffer.
114369    ** Decode %HH escape codes along the way.
114370    **
114371    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
114372    ** on the parsing context. As follows:
114373    **
114374    **   0: Parsing file-name.
114375    **   1: Parsing name section of a name=value query parameter.
114376    **   2: Parsing value section of a name=value query parameter.
114377    */
114378    eState = 0;
114379    while( (c = zUri[iIn])!=0 && c!='#' ){
114380      iIn++;
114381      if( c=='%'
114382       && sqlite3Isxdigit(zUri[iIn])
114383       && sqlite3Isxdigit(zUri[iIn+1])
114384      ){
114385        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
114386        octet += sqlite3HexToInt(zUri[iIn++]);
114387
114388        assert( octet>=0 && octet<256 );
114389        if( octet==0 ){
114390          /* This branch is taken when "%00" appears within the URI. In this
114391          ** case we ignore all text in the remainder of the path, name or
114392          ** value currently being parsed. So ignore the current character
114393          ** and skip to the next "?", "=" or "&", as appropriate. */
114394          while( (c = zUri[iIn])!=0 && c!='#'
114395              && (eState!=0 || c!='?')
114396              && (eState!=1 || (c!='=' && c!='&'))
114397              && (eState!=2 || c!='&')
114398          ){
114399            iIn++;
114400          }
114401          continue;
114402        }
114403        c = octet;
114404      }else if( eState==1 && (c=='&' || c=='=') ){
114405        if( zFile[iOut-1]==0 ){
114406          /* An empty option name. Ignore this option altogether. */
114407          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
114408          continue;
114409        }
114410        if( c=='&' ){
114411          zFile[iOut++] = '\0';
114412        }else{
114413          eState = 2;
114414        }
114415        c = 0;
114416      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
114417        c = 0;
114418        eState = 1;
114419      }
114420      zFile[iOut++] = c;
114421    }
114422    if( eState==1 ) zFile[iOut++] = '\0';
114423    zFile[iOut++] = '\0';
114424    zFile[iOut++] = '\0';
114425
114426    /* Check if there were any options specified that should be interpreted
114427    ** here. Options that are interpreted here include "vfs" and those that
114428    ** correspond to flags that may be passed to the sqlite3_open_v2()
114429    ** method. */
114430    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
114431    while( zOpt[0] ){
114432      int nOpt = sqlite3Strlen30(zOpt);
114433      char *zVal = &zOpt[nOpt+1];
114434      int nVal = sqlite3Strlen30(zVal);
114435
114436      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
114437        zVfs = zVal;
114438      }else{
114439        struct OpenMode {
114440          const char *z;
114441          int mode;
114442        } *aMode = 0;
114443        char *zModeType = 0;
114444        int mask = 0;
114445        int limit = 0;
114446
114447        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
114448          static struct OpenMode aCacheMode[] = {
114449            { "shared",  SQLITE_OPEN_SHAREDCACHE },
114450            { "private", SQLITE_OPEN_PRIVATECACHE },
114451            { 0, 0 }
114452          };
114453
114454          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
114455          aMode = aCacheMode;
114456          limit = mask;
114457          zModeType = "cache";
114458        }
114459        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
114460          static struct OpenMode aOpenMode[] = {
114461            { "ro",  SQLITE_OPEN_READONLY },
114462            { "rw",  SQLITE_OPEN_READWRITE },
114463            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
114464            { 0, 0 }
114465          };
114466
114467          mask = SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
114468          aMode = aOpenMode;
114469          limit = mask & flags;
114470          zModeType = "access";
114471        }
114472
114473        if( aMode ){
114474          int i;
114475          int mode = 0;
114476          for(i=0; aMode[i].z; i++){
114477            const char *z = aMode[i].z;
114478            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
114479              mode = aMode[i].mode;
114480              break;
114481            }
114482          }
114483          if( mode==0 ){
114484            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
114485            rc = SQLITE_ERROR;
114486            goto parse_uri_out;
114487          }
114488          if( mode>limit ){
114489            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
114490                                        zModeType, zVal);
114491            rc = SQLITE_PERM;
114492            goto parse_uri_out;
114493          }
114494          flags = (flags & ~mask) | mode;
114495        }
114496      }
114497
114498      zOpt = &zVal[nVal+1];
114499    }
114500
114501  }else{
114502    zFile = sqlite3_malloc(nUri+2);
114503    if( !zFile ) return SQLITE_NOMEM;
114504    memcpy(zFile, zUri, nUri);
114505    zFile[nUri] = '\0';
114506    zFile[nUri+1] = '\0';
114507  }
114508
114509  *ppVfs = sqlite3_vfs_find(zVfs);
114510  if( *ppVfs==0 ){
114511    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
114512    rc = SQLITE_ERROR;
114513  }
114514 parse_uri_out:
114515  if( rc!=SQLITE_OK ){
114516    sqlite3_free(zFile);
114517    zFile = 0;
114518  }
114519  *pFlags = flags;
114520  *pzFile = zFile;
114521  return rc;
114522}
114523
114524
114525/*
114526** This routine does the work of opening a database on behalf of
114527** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
114528** is UTF-8 encoded.
114529*/
114530static int openDatabase(
114531  const char *zFilename, /* Database filename UTF-8 encoded */
114532  sqlite3 **ppDb,        /* OUT: Returned database handle */
114533  unsigned int flags,    /* Operational flags */
114534  const char *zVfs       /* Name of the VFS to use */
114535){
114536  sqlite3 *db;                    /* Store allocated handle here */
114537  int rc;                         /* Return code */
114538  int isThreadsafe;               /* True for threadsafe connections */
114539  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
114540  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
114541
114542  *ppDb = 0;
114543#ifndef SQLITE_OMIT_AUTOINIT
114544  rc = sqlite3_initialize();
114545  if( rc ) return rc;
114546#endif
114547
114548  /* Only allow sensible combinations of bits in the flags argument.
114549  ** Throw an error if any non-sense combination is used.  If we
114550  ** do not block illegal combinations here, it could trigger
114551  ** assert() statements in deeper layers.  Sensible combinations
114552  ** are:
114553  **
114554  **  1:  SQLITE_OPEN_READONLY
114555  **  2:  SQLITE_OPEN_READWRITE
114556  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
114557  */
114558  assert( SQLITE_OPEN_READONLY  == 0x01 );
114559  assert( SQLITE_OPEN_READWRITE == 0x02 );
114560  assert( SQLITE_OPEN_CREATE    == 0x04 );
114561  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
114562  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
114563  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
114564  if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
114565
114566  if( sqlite3GlobalConfig.bCoreMutex==0 ){
114567    isThreadsafe = 0;
114568  }else if( flags & SQLITE_OPEN_NOMUTEX ){
114569    isThreadsafe = 0;
114570  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
114571    isThreadsafe = 1;
114572  }else{
114573    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
114574  }
114575  if( flags & SQLITE_OPEN_PRIVATECACHE ){
114576    flags &= ~SQLITE_OPEN_SHAREDCACHE;
114577  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
114578    flags |= SQLITE_OPEN_SHAREDCACHE;
114579  }
114580
114581  /* Remove harmful bits from the flags parameter
114582  **
114583  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
114584  ** dealt with in the previous code block.  Besides these, the only
114585  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
114586  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
114587  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
114588  ** off all other flags.
114589  */
114590  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
114591               SQLITE_OPEN_EXCLUSIVE |
114592               SQLITE_OPEN_MAIN_DB |
114593               SQLITE_OPEN_TEMP_DB |
114594               SQLITE_OPEN_TRANSIENT_DB |
114595               SQLITE_OPEN_MAIN_JOURNAL |
114596               SQLITE_OPEN_TEMP_JOURNAL |
114597               SQLITE_OPEN_SUBJOURNAL |
114598               SQLITE_OPEN_MASTER_JOURNAL |
114599               SQLITE_OPEN_NOMUTEX |
114600               SQLITE_OPEN_FULLMUTEX |
114601               SQLITE_OPEN_WAL
114602             );
114603
114604  /* Allocate the sqlite data structure */
114605  db = sqlite3MallocZero( sizeof(sqlite3) );
114606  if( db==0 ) goto opendb_out;
114607  if( isThreadsafe ){
114608    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
114609    if( db->mutex==0 ){
114610      sqlite3_free(db);
114611      db = 0;
114612      goto opendb_out;
114613    }
114614  }
114615  sqlite3_mutex_enter(db->mutex);
114616  db->errMask = 0xff;
114617  db->nDb = 2;
114618  db->magic = SQLITE_MAGIC_BUSY;
114619  db->aDb = db->aDbStatic;
114620
114621  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
114622  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
114623  db->autoCommit = 1;
114624  db->nextAutovac = -1;
114625  db->nextPagesize = 0;
114626  db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
114627#if SQLITE_DEFAULT_FILE_FORMAT<4
114628                 | SQLITE_LegacyFileFmt
114629#endif
114630#ifdef SQLITE_ENABLE_LOAD_EXTENSION
114631                 | SQLITE_LoadExtension
114632#endif
114633#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
114634                 | SQLITE_RecTriggers
114635#endif
114636#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
114637                 | SQLITE_ForeignKeys
114638#endif
114639      ;
114640  sqlite3HashInit(&db->aCollSeq);
114641#ifndef SQLITE_OMIT_VIRTUALTABLE
114642  sqlite3HashInit(&db->aModule);
114643#endif
114644
114645  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
114646  ** and UTF-16, so add a version for each to avoid any unnecessary
114647  ** conversions. The only error that can occur here is a malloc() failure.
114648  */
114649  createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
114650  createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
114651  createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
114652  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
114653  if( db->mallocFailed ){
114654    goto opendb_out;
114655  }
114656  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
114657  assert( db->pDfltColl!=0 );
114658
114659  /* Also add a UTF-8 case-insensitive collation sequence. */
114660  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
114661
114662  /* Parse the filename/URI argument. */
114663  db->openFlags = flags;
114664  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
114665  if( rc!=SQLITE_OK ){
114666    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
114667    sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
114668    sqlite3_free(zErrMsg);
114669    goto opendb_out;
114670  }
114671
114672  /* Open the backend database driver */
114673  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
114674                        flags | SQLITE_OPEN_MAIN_DB);
114675  if( rc!=SQLITE_OK ){
114676    if( rc==SQLITE_IOERR_NOMEM ){
114677      rc = SQLITE_NOMEM;
114678    }
114679    sqlite3Error(db, rc, 0);
114680    goto opendb_out;
114681  }
114682  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
114683  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
114684
114685
114686  /* The default safety_level for the main database is 'full'; for the temp
114687  ** database it is 'NONE'. This matches the pager layer defaults.
114688  */
114689  db->aDb[0].zName = "main";
114690  db->aDb[0].safety_level = 3;
114691  db->aDb[1].zName = "temp";
114692  db->aDb[1].safety_level = 1;
114693
114694  db->magic = SQLITE_MAGIC_OPEN;
114695  if( db->mallocFailed ){
114696    goto opendb_out;
114697  }
114698
114699  /* Register all built-in functions, but do not attempt to read the
114700  ** database schema yet. This is delayed until the first time the database
114701  ** is accessed.
114702  */
114703  sqlite3Error(db, SQLITE_OK, 0);
114704  sqlite3RegisterBuiltinFunctions(db);
114705
114706  /* Load automatic extensions - extensions that have been registered
114707  ** using the sqlite3_automatic_extension() API.
114708  */
114709  rc = sqlite3_errcode(db);
114710  if( rc==SQLITE_OK ){
114711    sqlite3AutoLoadExtensions(db);
114712    rc = sqlite3_errcode(db);
114713    if( rc!=SQLITE_OK ){
114714      goto opendb_out;
114715    }
114716  }
114717
114718#ifdef SQLITE_ENABLE_FTS1
114719  if( !db->mallocFailed ){
114720    extern int sqlite3Fts1Init(sqlite3*);
114721    rc = sqlite3Fts1Init(db);
114722  }
114723#endif
114724
114725#ifdef SQLITE_ENABLE_FTS2
114726  if( !db->mallocFailed && rc==SQLITE_OK ){
114727    extern int sqlite3Fts2Init(sqlite3*);
114728    rc = sqlite3Fts2Init(db);
114729  }
114730#endif
114731
114732#ifdef SQLITE_ENABLE_FTS3
114733  // Begin Android change
114734  #ifdef SQLITE_ENABLE_FTS3_BACKWARDS
114735    /* Also register as fts1 and fts2, for backwards compatability on
114736    ** systems known to have never seen a pre-fts3 database.
114737    */
114738    if( !db->mallocFailed && rc==SQLITE_OK ){
114739      rc = sqlite3Fts3Init(db, "fts1");
114740    }
114741
114742    if( !db->mallocFailed && rc==SQLITE_OK ){
114743      rc = sqlite3Fts3Init(db, "fts2");
114744    }
114745  #endif
114746
114747    if( !db->mallocFailed && rc==SQLITE_OK ){
114748      rc = sqlite3Fts3Init(db, "fts3");
114749    }
114750  // End Android change
114751#endif
114752
114753#ifdef SQLITE_ENABLE_ICU
114754  if( !db->mallocFailed && rc==SQLITE_OK ){
114755    rc = sqlite3IcuInit(db);
114756  }
114757#endif
114758
114759#ifdef SQLITE_ENABLE_RTREE
114760  if( !db->mallocFailed && rc==SQLITE_OK){
114761    rc = sqlite3RtreeInit(db);
114762  }
114763#endif
114764
114765  sqlite3Error(db, rc, 0);
114766
114767  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
114768  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
114769  ** mode.  Doing nothing at all also makes NORMAL the default.
114770  */
114771#ifdef SQLITE_DEFAULT_LOCKING_MODE
114772  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
114773  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
114774                          SQLITE_DEFAULT_LOCKING_MODE);
114775#endif
114776
114777  /* Enable the lookaside-malloc subsystem */
114778  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
114779                        sqlite3GlobalConfig.nLookaside);
114780
114781  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
114782
114783opendb_out:
114784  sqlite3_free(zOpen);
114785  if( db ){
114786    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
114787    sqlite3_mutex_leave(db->mutex);
114788  }
114789  rc = sqlite3_errcode(db);
114790  assert( db!=0 || rc==SQLITE_NOMEM );
114791  if( rc==SQLITE_NOMEM ){
114792    sqlite3_close(db);
114793    db = 0;
114794  }else if( rc!=SQLITE_OK ){
114795    db->magic = SQLITE_MAGIC_SICK;
114796  }
114797  *ppDb = db;
114798  return sqlite3ApiExit(0, rc);
114799}
114800
114801/*
114802** Open a new database handle.
114803*/
114804SQLITE_API int sqlite3_open(
114805  const char *zFilename,
114806  sqlite3 **ppDb
114807){
114808  return openDatabase(zFilename, ppDb,
114809                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
114810}
114811SQLITE_API int sqlite3_open_v2(
114812  const char *filename,   /* Database filename (UTF-8) */
114813  sqlite3 **ppDb,         /* OUT: SQLite db handle */
114814  int flags,              /* Flags */
114815  const char *zVfs        /* Name of VFS module to use */
114816){
114817  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
114818}
114819
114820#ifndef SQLITE_OMIT_UTF16
114821/*
114822** Open a new database handle.
114823*/
114824SQLITE_API int sqlite3_open16(
114825  const void *zFilename,
114826  sqlite3 **ppDb
114827){
114828  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
114829  sqlite3_value *pVal;
114830  int rc;
114831
114832  assert( zFilename );
114833  assert( ppDb );
114834  *ppDb = 0;
114835#ifndef SQLITE_OMIT_AUTOINIT
114836  rc = sqlite3_initialize();
114837  if( rc ) return rc;
114838#endif
114839  pVal = sqlite3ValueNew(0);
114840  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
114841  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
114842  if( zFilename8 ){
114843    rc = openDatabase(zFilename8, ppDb,
114844                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
114845    assert( *ppDb || rc==SQLITE_NOMEM );
114846    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
114847      ENC(*ppDb) = SQLITE_UTF16NATIVE;
114848    }
114849  }else{
114850    rc = SQLITE_NOMEM;
114851  }
114852  sqlite3ValueFree(pVal);
114853
114854  return sqlite3ApiExit(0, rc);
114855}
114856#endif /* SQLITE_OMIT_UTF16 */
114857
114858/*
114859** Register a new collation sequence with the database handle db.
114860*/
114861SQLITE_API int sqlite3_create_collation(
114862  sqlite3* db,
114863  const char *zName,
114864  int enc,
114865  void* pCtx,
114866  int(*xCompare)(void*,int,const void*,int,const void*)
114867){
114868  int rc;
114869  sqlite3_mutex_enter(db->mutex);
114870  assert( !db->mallocFailed );
114871  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
114872  rc = sqlite3ApiExit(db, rc);
114873  sqlite3_mutex_leave(db->mutex);
114874  return rc;
114875}
114876
114877/*
114878** Register a new collation sequence with the database handle db.
114879*/
114880SQLITE_API int sqlite3_create_collation_v2(
114881  sqlite3* db,
114882  const char *zName,
114883  int enc,
114884  void* pCtx,
114885  int(*xCompare)(void*,int,const void*,int,const void*),
114886  void(*xDel)(void*)
114887){
114888  int rc;
114889  sqlite3_mutex_enter(db->mutex);
114890  assert( !db->mallocFailed );
114891  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
114892  rc = sqlite3ApiExit(db, rc);
114893  sqlite3_mutex_leave(db->mutex);
114894  return rc;
114895}
114896
114897#ifndef SQLITE_OMIT_UTF16
114898/*
114899** Register a new collation sequence with the database handle db.
114900*/
114901SQLITE_API int sqlite3_create_collation16(
114902  sqlite3* db,
114903  const void *zName,
114904  int enc,
114905  void* pCtx,
114906  int(*xCompare)(void*,int,const void*,int,const void*)
114907){
114908  int rc = SQLITE_OK;
114909  char *zName8;
114910  sqlite3_mutex_enter(db->mutex);
114911  assert( !db->mallocFailed );
114912  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
114913  if( zName8 ){
114914    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
114915    sqlite3DbFree(db, zName8);
114916  }
114917  rc = sqlite3ApiExit(db, rc);
114918  sqlite3_mutex_leave(db->mutex);
114919  return rc;
114920}
114921#endif /* SQLITE_OMIT_UTF16 */
114922
114923/*
114924** Register a collation sequence factory callback with the database handle
114925** db. Replace any previously installed collation sequence factory.
114926*/
114927SQLITE_API int sqlite3_collation_needed(
114928  sqlite3 *db,
114929  void *pCollNeededArg,
114930  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
114931){
114932  sqlite3_mutex_enter(db->mutex);
114933  db->xCollNeeded = xCollNeeded;
114934  db->xCollNeeded16 = 0;
114935  db->pCollNeededArg = pCollNeededArg;
114936  sqlite3_mutex_leave(db->mutex);
114937  return SQLITE_OK;
114938}
114939
114940#ifndef SQLITE_OMIT_UTF16
114941/*
114942** Register a collation sequence factory callback with the database handle
114943** db. Replace any previously installed collation sequence factory.
114944*/
114945SQLITE_API int sqlite3_collation_needed16(
114946  sqlite3 *db,
114947  void *pCollNeededArg,
114948  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
114949){
114950  sqlite3_mutex_enter(db->mutex);
114951  db->xCollNeeded = 0;
114952  db->xCollNeeded16 = xCollNeeded16;
114953  db->pCollNeededArg = pCollNeededArg;
114954  sqlite3_mutex_leave(db->mutex);
114955  return SQLITE_OK;
114956}
114957#endif /* SQLITE_OMIT_UTF16 */
114958
114959#ifndef SQLITE_OMIT_DEPRECATED
114960/*
114961** This function is now an anachronism. It used to be used to recover from a
114962** malloc() failure, but SQLite now does this automatically.
114963*/
114964SQLITE_API int sqlite3_global_recover(void){
114965  return SQLITE_OK;
114966}
114967#endif
114968
114969/*
114970** Test to see whether or not the database connection is in autocommit
114971** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
114972** by default.  Autocommit is disabled by a BEGIN statement and reenabled
114973** by the next COMMIT or ROLLBACK.
114974**
114975******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
114976*/
114977SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
114978  return db->autoCommit;
114979}
114980
114981/*
114982** The following routines are subtitutes for constants SQLITE_CORRUPT,
114983** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
114984** constants.  They server two purposes:
114985**
114986**   1.  Serve as a convenient place to set a breakpoint in a debugger
114987**       to detect when version error conditions occurs.
114988**
114989**   2.  Invoke sqlite3_log() to provide the source code location where
114990**       a low-level error is first detected.
114991*/
114992SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
114993  testcase( sqlite3GlobalConfig.xLog!=0 );
114994  sqlite3_log(SQLITE_CORRUPT,
114995              "database corruption at line %d of [%.10s]",
114996              lineno, 20+sqlite3_sourceid());
114997  return SQLITE_CORRUPT;
114998}
114999SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
115000  testcase( sqlite3GlobalConfig.xLog!=0 );
115001  sqlite3_log(SQLITE_MISUSE,
115002              "misuse at line %d of [%.10s]",
115003              lineno, 20+sqlite3_sourceid());
115004  return SQLITE_MISUSE;
115005}
115006SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
115007  testcase( sqlite3GlobalConfig.xLog!=0 );
115008  sqlite3_log(SQLITE_CANTOPEN,
115009              "cannot open file at line %d of [%.10s]",
115010              lineno, 20+sqlite3_sourceid());
115011  return SQLITE_CANTOPEN;
115012}
115013
115014
115015#ifndef SQLITE_OMIT_DEPRECATED
115016/*
115017** This is a convenience routine that makes sure that all thread-specific
115018** data for this thread has been deallocated.
115019**
115020** SQLite no longer uses thread-specific data so this routine is now a
115021** no-op.  It is retained for historical compatibility.
115022*/
115023SQLITE_API void sqlite3_thread_cleanup(void){
115024}
115025#endif
115026
115027/*
115028** Return meta information about a specific column of a database table.
115029** See comment in sqlite3.h (sqlite.h.in) for details.
115030*/
115031#ifdef SQLITE_ENABLE_COLUMN_METADATA
115032SQLITE_API int sqlite3_table_column_metadata(
115033  sqlite3 *db,                /* Connection handle */
115034  const char *zDbName,        /* Database name or NULL */
115035  const char *zTableName,     /* Table name */
115036  const char *zColumnName,    /* Column name */
115037  char const **pzDataType,    /* OUTPUT: Declared data type */
115038  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
115039  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
115040  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
115041  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
115042){
115043  int rc;
115044  char *zErrMsg = 0;
115045  Table *pTab = 0;
115046  Column *pCol = 0;
115047  int iCol;
115048
115049  char const *zDataType = 0;
115050  char const *zCollSeq = 0;
115051  int notnull = 0;
115052  int primarykey = 0;
115053  int autoinc = 0;
115054
115055  /* Ensure the database schema has been loaded */
115056  sqlite3_mutex_enter(db->mutex);
115057  sqlite3BtreeEnterAll(db);
115058  rc = sqlite3Init(db, &zErrMsg);
115059  if( SQLITE_OK!=rc ){
115060    goto error_out;
115061  }
115062
115063  /* Locate the table in question */
115064  pTab = sqlite3FindTable(db, zTableName, zDbName);
115065  if( !pTab || pTab->pSelect ){
115066    pTab = 0;
115067    goto error_out;
115068  }
115069
115070  /* Find the column for which info is requested */
115071  if( sqlite3IsRowid(zColumnName) ){
115072    iCol = pTab->iPKey;
115073    if( iCol>=0 ){
115074      pCol = &pTab->aCol[iCol];
115075    }
115076  }else{
115077    for(iCol=0; iCol<pTab->nCol; iCol++){
115078      pCol = &pTab->aCol[iCol];
115079      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
115080        break;
115081      }
115082    }
115083    if( iCol==pTab->nCol ){
115084      pTab = 0;
115085      goto error_out;
115086    }
115087  }
115088
115089  /* The following block stores the meta information that will be returned
115090  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
115091  ** and autoinc. At this point there are two possibilities:
115092  **
115093  **     1. The specified column name was rowid", "oid" or "_rowid_"
115094  **        and there is no explicitly declared IPK column.
115095  **
115096  **     2. The table is not a view and the column name identified an
115097  **        explicitly declared column. Copy meta information from *pCol.
115098  */
115099  if( pCol ){
115100    zDataType = pCol->zType;
115101    zCollSeq = pCol->zColl;
115102    notnull = pCol->notNull!=0;
115103    primarykey  = pCol->isPrimKey!=0;
115104    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
115105  }else{
115106    zDataType = "INTEGER";
115107    primarykey = 1;
115108  }
115109  if( !zCollSeq ){
115110    zCollSeq = "BINARY";
115111  }
115112
115113error_out:
115114  sqlite3BtreeLeaveAll(db);
115115
115116  /* Whether the function call succeeded or failed, set the output parameters
115117  ** to whatever their local counterparts contain. If an error did occur,
115118  ** this has the effect of zeroing all output parameters.
115119  */
115120  if( pzDataType ) *pzDataType = zDataType;
115121  if( pzCollSeq ) *pzCollSeq = zCollSeq;
115122  if( pNotNull ) *pNotNull = notnull;
115123  if( pPrimaryKey ) *pPrimaryKey = primarykey;
115124  if( pAutoinc ) *pAutoinc = autoinc;
115125
115126  if( SQLITE_OK==rc && !pTab ){
115127    sqlite3DbFree(db, zErrMsg);
115128    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
115129        zColumnName);
115130    rc = SQLITE_ERROR;
115131  }
115132  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
115133  sqlite3DbFree(db, zErrMsg);
115134  rc = sqlite3ApiExit(db, rc);
115135  sqlite3_mutex_leave(db->mutex);
115136  return rc;
115137}
115138#endif
115139
115140/*
115141** Sleep for a little while.  Return the amount of time slept.
115142*/
115143SQLITE_API int sqlite3_sleep(int ms){
115144  sqlite3_vfs *pVfs;
115145  int rc;
115146  pVfs = sqlite3_vfs_find(0);
115147  if( pVfs==0 ) return 0;
115148
115149  /* This function works in milliseconds, but the underlying OsSleep()
115150  ** API uses microseconds. Hence the 1000's.
115151  */
115152  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
115153  return rc;
115154}
115155
115156/*
115157** Enable or disable the extended result codes.
115158*/
115159SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
115160  sqlite3_mutex_enter(db->mutex);
115161  db->errMask = onoff ? 0xffffffff : 0xff;
115162  sqlite3_mutex_leave(db->mutex);
115163  return SQLITE_OK;
115164}
115165
115166/*
115167** Invoke the xFileControl method on a particular database.
115168*/
115169SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
115170  int rc = SQLITE_ERROR;
115171  Btree *pBtree;
115172
115173  sqlite3_mutex_enter(db->mutex);
115174  pBtree = sqlite3DbNameToBtree(db, zDbName);
115175  if( pBtree ){
115176    Pager *pPager;
115177    sqlite3_file *fd;
115178    sqlite3BtreeEnter(pBtree);
115179    pPager = sqlite3BtreePager(pBtree);
115180    assert( pPager!=0 );
115181    fd = sqlite3PagerFile(pPager);
115182    assert( fd!=0 );
115183    if( op==SQLITE_FCNTL_FILE_POINTER ){
115184      *(sqlite3_file**)pArg = fd;
115185      rc = SQLITE_OK;
115186    }else if( fd->pMethods ){
115187      rc = sqlite3OsFileControl(fd, op, pArg);
115188    }else{
115189      rc = SQLITE_NOTFOUND;
115190    }
115191    sqlite3BtreeLeave(pBtree);
115192  }
115193  sqlite3_mutex_leave(db->mutex);
115194  return rc;
115195}
115196
115197/*
115198** Interface to the testing logic.
115199*/
115200SQLITE_API int sqlite3_test_control(int op, ...){
115201  int rc = 0;
115202#ifndef SQLITE_OMIT_BUILTIN_TEST
115203  va_list ap;
115204  va_start(ap, op);
115205  switch( op ){
115206
115207    /*
115208    ** Save the current state of the PRNG.
115209    */
115210    case SQLITE_TESTCTRL_PRNG_SAVE: {
115211      sqlite3PrngSaveState();
115212      break;
115213    }
115214
115215    /*
115216    ** Restore the state of the PRNG to the last state saved using
115217    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
115218    ** this verb acts like PRNG_RESET.
115219    */
115220    case SQLITE_TESTCTRL_PRNG_RESTORE: {
115221      sqlite3PrngRestoreState();
115222      break;
115223    }
115224
115225    /*
115226    ** Reset the PRNG back to its uninitialized state.  The next call
115227    ** to sqlite3_randomness() will reseed the PRNG using a single call
115228    ** to the xRandomness method of the default VFS.
115229    */
115230    case SQLITE_TESTCTRL_PRNG_RESET: {
115231      sqlite3PrngResetState();
115232      break;
115233    }
115234
115235    /*
115236    **  sqlite3_test_control(BITVEC_TEST, size, program)
115237    **
115238    ** Run a test against a Bitvec object of size.  The program argument
115239    ** is an array of integers that defines the test.  Return -1 on a
115240    ** memory allocation error, 0 on success, or non-zero for an error.
115241    ** See the sqlite3BitvecBuiltinTest() for additional information.
115242    */
115243    case SQLITE_TESTCTRL_BITVEC_TEST: {
115244      int sz = va_arg(ap, int);
115245      int *aProg = va_arg(ap, int*);
115246      rc = sqlite3BitvecBuiltinTest(sz, aProg);
115247      break;
115248    }
115249
115250    /*
115251    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
115252    **
115253    ** Register hooks to call to indicate which malloc() failures
115254    ** are benign.
115255    */
115256    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
115257      typedef void (*void_function)(void);
115258      void_function xBenignBegin;
115259      void_function xBenignEnd;
115260      xBenignBegin = va_arg(ap, void_function);
115261      xBenignEnd = va_arg(ap, void_function);
115262      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
115263      break;
115264    }
115265
115266    /*
115267    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
115268    **
115269    ** Set the PENDING byte to the value in the argument, if X>0.
115270    ** Make no changes if X==0.  Return the value of the pending byte
115271    ** as it existing before this routine was called.
115272    **
115273    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
115274    ** an incompatible database file format.  Changing the PENDING byte
115275    ** while any database connection is open results in undefined and
115276    ** dileterious behavior.
115277    */
115278    case SQLITE_TESTCTRL_PENDING_BYTE: {
115279      rc = PENDING_BYTE;
115280#ifndef SQLITE_OMIT_WSD
115281      {
115282        unsigned int newVal = va_arg(ap, unsigned int);
115283        if( newVal ) sqlite3PendingByte = newVal;
115284      }
115285#endif
115286      break;
115287    }
115288
115289    /*
115290    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
115291    **
115292    ** This action provides a run-time test to see whether or not
115293    ** assert() was enabled at compile-time.  If X is true and assert()
115294    ** is enabled, then the return value is true.  If X is true and
115295    ** assert() is disabled, then the return value is zero.  If X is
115296    ** false and assert() is enabled, then the assertion fires and the
115297    ** process aborts.  If X is false and assert() is disabled, then the
115298    ** return value is zero.
115299    */
115300    case SQLITE_TESTCTRL_ASSERT: {
115301      volatile int x = 0;
115302      assert( (x = va_arg(ap,int))!=0 );
115303      rc = x;
115304      break;
115305    }
115306
115307
115308    /*
115309    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
115310    **
115311    ** This action provides a run-time test to see how the ALWAYS and
115312    ** NEVER macros were defined at compile-time.
115313    **
115314    ** The return value is ALWAYS(X).
115315    **
115316    ** The recommended test is X==2.  If the return value is 2, that means
115317    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
115318    ** default setting.  If the return value is 1, then ALWAYS() is either
115319    ** hard-coded to true or else it asserts if its argument is false.
115320    ** The first behavior (hard-coded to true) is the case if
115321    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
115322    ** behavior (assert if the argument to ALWAYS() is false) is the case if
115323    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
115324    **
115325    ** The run-time test procedure might look something like this:
115326    **
115327    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
115328    **      // ALWAYS() and NEVER() are no-op pass-through macros
115329    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
115330    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
115331    **    }else{
115332    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
115333    **    }
115334    */
115335    case SQLITE_TESTCTRL_ALWAYS: {
115336      int x = va_arg(ap,int);
115337      rc = ALWAYS(x);
115338      break;
115339    }
115340
115341    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
115342    **
115343    ** Set the nReserve size to N for the main database on the database
115344    ** connection db.
115345    */
115346    case SQLITE_TESTCTRL_RESERVE: {
115347      sqlite3 *db = va_arg(ap, sqlite3*);
115348      int x = va_arg(ap,int);
115349      sqlite3_mutex_enter(db->mutex);
115350      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
115351      sqlite3_mutex_leave(db->mutex);
115352      break;
115353    }
115354
115355    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
115356    **
115357    ** Enable or disable various optimizations for testing purposes.  The
115358    ** argument N is a bitmask of optimizations to be disabled.  For normal
115359    ** operation N should be 0.  The idea is that a test program (like the
115360    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
115361    ** with various optimizations disabled to verify that the same answer
115362    ** is obtained in every case.
115363    */
115364    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
115365      sqlite3 *db = va_arg(ap, sqlite3*);
115366      int x = va_arg(ap,int);
115367      db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
115368      break;
115369    }
115370
115371#ifdef SQLITE_N_KEYWORD
115372    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
115373    **
115374    ** If zWord is a keyword recognized by the parser, then return the
115375    ** number of keywords.  Or if zWord is not a keyword, return 0.
115376    **
115377    ** This test feature is only available in the amalgamation since
115378    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
115379    ** is built using separate source files.
115380    */
115381    case SQLITE_TESTCTRL_ISKEYWORD: {
115382      const char *zWord = va_arg(ap, const char*);
115383      int n = sqlite3Strlen30(zWord);
115384      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
115385      break;
115386    }
115387#endif
115388
115389    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
115390    **
115391    ** Pass pFree into sqlite3ScratchFree().
115392    ** If sz>0 then allocate a scratch buffer into pNew.
115393    */
115394    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
115395      void *pFree, **ppNew;
115396      int sz;
115397      sz = va_arg(ap, int);
115398      ppNew = va_arg(ap, void**);
115399      pFree = va_arg(ap, void*);
115400      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
115401      sqlite3ScratchFree(pFree);
115402      break;
115403    }
115404
115405    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
115406    **
115407    ** If parameter onoff is non-zero, configure the wrappers so that all
115408    ** subsequent calls to localtime() and variants fail. If onoff is zero,
115409    ** undo this setting.
115410    */
115411    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
115412      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
115413      break;
115414    }
115415
115416#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
115417    /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
115418    **                        sqlite3_stmt*,const char**);
115419    **
115420    ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
115421    ** a string that describes the optimized parse tree.  This test-control
115422    ** returns a pointer to that string.
115423    */
115424    case SQLITE_TESTCTRL_EXPLAIN_STMT: {
115425      sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
115426      const char **pzRet = va_arg(ap, const char**);
115427      *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
115428      break;
115429    }
115430#endif
115431
115432  }
115433  va_end(ap);
115434#endif /* SQLITE_OMIT_BUILTIN_TEST */
115435  return rc;
115436}
115437
115438/*
115439** This is a utility routine, useful to VFS implementations, that checks
115440** to see if a database file was a URI that contained a specific query
115441** parameter, and if so obtains the value of the query parameter.
115442**
115443** The zFilename argument is the filename pointer passed into the xOpen()
115444** method of a VFS implementation.  The zParam argument is the name of the
115445** query parameter we seek.  This routine returns the value of the zParam
115446** parameter if it exists.  If the parameter does not exist, this routine
115447** returns a NULL pointer.
115448*/
115449SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
115450  if( zFilename==0 ) return 0;
115451  zFilename += sqlite3Strlen30(zFilename) + 1;
115452  while( zFilename[0] ){
115453    int x = strcmp(zFilename, zParam);
115454    zFilename += sqlite3Strlen30(zFilename) + 1;
115455    if( x==0 ) return zFilename;
115456    zFilename += sqlite3Strlen30(zFilename) + 1;
115457  }
115458  return 0;
115459}
115460
115461/*
115462** Return a boolean value for a query parameter.
115463*/
115464SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
115465  const char *z = sqlite3_uri_parameter(zFilename, zParam);
115466  bDflt = bDflt!=0;
115467  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
115468}
115469
115470/*
115471** Return a 64-bit integer value for a query parameter.
115472*/
115473SQLITE_API sqlite3_int64 sqlite3_uri_int64(
115474  const char *zFilename,    /* Filename as passed to xOpen */
115475  const char *zParam,       /* URI parameter sought */
115476  sqlite3_int64 bDflt       /* return if parameter is missing */
115477){
115478  const char *z = sqlite3_uri_parameter(zFilename, zParam);
115479  sqlite3_int64 v;
115480  if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
115481    bDflt = v;
115482  }
115483  return bDflt;
115484}
115485
115486/*
115487** Return the Btree pointer identified by zDbName.  Return NULL if not found.
115488*/
115489SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
115490  int i;
115491  for(i=0; i<db->nDb; i++){
115492    if( db->aDb[i].pBt
115493     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
115494    ){
115495      return db->aDb[i].pBt;
115496    }
115497  }
115498  return 0;
115499}
115500
115501/*
115502** Return the filename of the database associated with a database
115503** connection.
115504*/
115505SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
115506  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
115507  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
115508}
115509
115510/*
115511** Return 1 if database is read-only or 0 if read/write.  Return -1 if
115512** no such database exists.
115513*/
115514SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
115515  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
115516  return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
115517}
115518
115519/************** End of main.c ************************************************/
115520/************** Begin file notify.c ******************************************/
115521/*
115522** 2009 March 3
115523**
115524** The author disclaims copyright to this source code.  In place of
115525** a legal notice, here is a blessing:
115526**
115527**    May you do good and not evil.
115528**    May you find forgiveness for yourself and forgive others.
115529**    May you share freely, never taking more than you give.
115530**
115531*************************************************************************
115532**
115533** This file contains the implementation of the sqlite3_unlock_notify()
115534** API method and its associated functionality.
115535*/
115536
115537/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
115538#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
115539
115540/*
115541** Public interfaces:
115542**
115543**   sqlite3ConnectionBlocked()
115544**   sqlite3ConnectionUnlocked()
115545**   sqlite3ConnectionClosed()
115546**   sqlite3_unlock_notify()
115547*/
115548
115549#define assertMutexHeld() \
115550  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
115551
115552/*
115553** Head of a linked list of all sqlite3 objects created by this process
115554** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
115555** is not NULL. This variable may only accessed while the STATIC_MASTER
115556** mutex is held.
115557*/
115558static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
115559
115560#ifndef NDEBUG
115561/*
115562** This function is a complex assert() that verifies the following
115563** properties of the blocked connections list:
115564**
115565**   1) Each entry in the list has a non-NULL value for either
115566**      pUnlockConnection or pBlockingConnection, or both.
115567**
115568**   2) All entries in the list that share a common value for
115569**      xUnlockNotify are grouped together.
115570**
115571**   3) If the argument db is not NULL, then none of the entries in the
115572**      blocked connections list have pUnlockConnection or pBlockingConnection
115573**      set to db. This is used when closing connection db.
115574*/
115575static void checkListProperties(sqlite3 *db){
115576  sqlite3 *p;
115577  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
115578    int seen = 0;
115579    sqlite3 *p2;
115580
115581    /* Verify property (1) */
115582    assert( p->pUnlockConnection || p->pBlockingConnection );
115583
115584    /* Verify property (2) */
115585    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
115586      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
115587      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
115588      assert( db==0 || p->pUnlockConnection!=db );
115589      assert( db==0 || p->pBlockingConnection!=db );
115590    }
115591  }
115592}
115593#else
115594# define checkListProperties(x)
115595#endif
115596
115597/*
115598** Remove connection db from the blocked connections list. If connection
115599** db is not currently a part of the list, this function is a no-op.
115600*/
115601static void removeFromBlockedList(sqlite3 *db){
115602  sqlite3 **pp;
115603  assertMutexHeld();
115604  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
115605    if( *pp==db ){
115606      *pp = (*pp)->pNextBlocked;
115607      break;
115608    }
115609  }
115610}
115611
115612/*
115613** Add connection db to the blocked connections list. It is assumed
115614** that it is not already a part of the list.
115615*/
115616static void addToBlockedList(sqlite3 *db){
115617  sqlite3 **pp;
115618  assertMutexHeld();
115619  for(
115620    pp=&sqlite3BlockedList;
115621    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
115622    pp=&(*pp)->pNextBlocked
115623  );
115624  db->pNextBlocked = *pp;
115625  *pp = db;
115626}
115627
115628/*
115629** Obtain the STATIC_MASTER mutex.
115630*/
115631static void enterMutex(void){
115632  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
115633  checkListProperties(0);
115634}
115635
115636/*
115637** Release the STATIC_MASTER mutex.
115638*/
115639static void leaveMutex(void){
115640  assertMutexHeld();
115641  checkListProperties(0);
115642  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
115643}
115644
115645/*
115646** Register an unlock-notify callback.
115647**
115648** This is called after connection "db" has attempted some operation
115649** but has received an SQLITE_LOCKED error because another connection
115650** (call it pOther) in the same process was busy using the same shared
115651** cache.  pOther is found by looking at db->pBlockingConnection.
115652**
115653** If there is no blocking connection, the callback is invoked immediately,
115654** before this routine returns.
115655**
115656** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
115657** a deadlock.
115658**
115659** Otherwise, make arrangements to invoke xNotify when pOther drops
115660** its locks.
115661**
115662** Each call to this routine overrides any prior callbacks registered
115663** on the same "db".  If xNotify==0 then any prior callbacks are immediately
115664** cancelled.
115665*/
115666SQLITE_API int sqlite3_unlock_notify(
115667  sqlite3 *db,
115668  void (*xNotify)(void **, int),
115669  void *pArg
115670){
115671  int rc = SQLITE_OK;
115672
115673  sqlite3_mutex_enter(db->mutex);
115674  enterMutex();
115675
115676  if( xNotify==0 ){
115677    removeFromBlockedList(db);
115678    db->pBlockingConnection = 0;
115679    db->pUnlockConnection = 0;
115680    db->xUnlockNotify = 0;
115681    db->pUnlockArg = 0;
115682  }else if( 0==db->pBlockingConnection ){
115683    /* The blocking transaction has been concluded. Or there never was a
115684    ** blocking transaction. In either case, invoke the notify callback
115685    ** immediately.
115686    */
115687    xNotify(&pArg, 1);
115688  }else{
115689    sqlite3 *p;
115690
115691    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
115692    if( p ){
115693      rc = SQLITE_LOCKED;              /* Deadlock detected. */
115694    }else{
115695      db->pUnlockConnection = db->pBlockingConnection;
115696      db->xUnlockNotify = xNotify;
115697      db->pUnlockArg = pArg;
115698      removeFromBlockedList(db);
115699      addToBlockedList(db);
115700    }
115701  }
115702
115703  leaveMutex();
115704  assert( !db->mallocFailed );
115705  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
115706  sqlite3_mutex_leave(db->mutex);
115707  return rc;
115708}
115709
115710/*
115711** This function is called while stepping or preparing a statement
115712** associated with connection db. The operation will return SQLITE_LOCKED
115713** to the user because it requires a lock that will not be available
115714** until connection pBlocker concludes its current transaction.
115715*/
115716SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
115717  enterMutex();
115718  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
115719    addToBlockedList(db);
115720  }
115721  db->pBlockingConnection = pBlocker;
115722  leaveMutex();
115723}
115724
115725/*
115726** This function is called when
115727** the transaction opened by database db has just finished. Locks held
115728** by database connection db have been released.
115729**
115730** This function loops through each entry in the blocked connections
115731** list and does the following:
115732**
115733**   1) If the sqlite3.pBlockingConnection member of a list entry is
115734**      set to db, then set pBlockingConnection=0.
115735**
115736**   2) If the sqlite3.pUnlockConnection member of a list entry is
115737**      set to db, then invoke the configured unlock-notify callback and
115738**      set pUnlockConnection=0.
115739**
115740**   3) If the two steps above mean that pBlockingConnection==0 and
115741**      pUnlockConnection==0, remove the entry from the blocked connections
115742**      list.
115743*/
115744SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
115745  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
115746  int nArg = 0;                            /* Number of entries in aArg[] */
115747  sqlite3 **pp;                            /* Iterator variable */
115748  void **aArg;               /* Arguments to the unlock callback */
115749  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
115750  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
115751
115752  aArg = aStatic;
115753  enterMutex();         /* Enter STATIC_MASTER mutex */
115754
115755  /* This loop runs once for each entry in the blocked-connections list. */
115756  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
115757    sqlite3 *p = *pp;
115758
115759    /* Step 1. */
115760    if( p->pBlockingConnection==db ){
115761      p->pBlockingConnection = 0;
115762    }
115763
115764    /* Step 2. */
115765    if( p->pUnlockConnection==db ){
115766      assert( p->xUnlockNotify );
115767      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
115768        xUnlockNotify(aArg, nArg);
115769        nArg = 0;
115770      }
115771
115772      sqlite3BeginBenignMalloc();
115773      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
115774      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
115775      if( (!aDyn && nArg==(int)ArraySize(aStatic))
115776       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
115777      ){
115778        /* The aArg[] array needs to grow. */
115779        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
115780        if( pNew ){
115781          memcpy(pNew, aArg, nArg*sizeof(void *));
115782          sqlite3_free(aDyn);
115783          aDyn = aArg = pNew;
115784        }else{
115785          /* This occurs when the array of context pointers that need to
115786          ** be passed to the unlock-notify callback is larger than the
115787          ** aStatic[] array allocated on the stack and the attempt to
115788          ** allocate a larger array from the heap has failed.
115789          **
115790          ** This is a difficult situation to handle. Returning an error
115791          ** code to the caller is insufficient, as even if an error code
115792          ** is returned the transaction on connection db will still be
115793          ** closed and the unlock-notify callbacks on blocked connections
115794          ** will go unissued. This might cause the application to wait
115795          ** indefinitely for an unlock-notify callback that will never
115796          ** arrive.
115797          **
115798          ** Instead, invoke the unlock-notify callback with the context
115799          ** array already accumulated. We can then clear the array and
115800          ** begin accumulating any further context pointers without
115801          ** requiring any dynamic allocation. This is sub-optimal because
115802          ** it means that instead of one callback with a large array of
115803          ** context pointers the application will receive two or more
115804          ** callbacks with smaller arrays of context pointers, which will
115805          ** reduce the applications ability to prioritize multiple
115806          ** connections. But it is the best that can be done under the
115807          ** circumstances.
115808          */
115809          xUnlockNotify(aArg, nArg);
115810          nArg = 0;
115811        }
115812      }
115813      sqlite3EndBenignMalloc();
115814
115815      aArg[nArg++] = p->pUnlockArg;
115816      xUnlockNotify = p->xUnlockNotify;
115817      p->pUnlockConnection = 0;
115818      p->xUnlockNotify = 0;
115819      p->pUnlockArg = 0;
115820    }
115821
115822    /* Step 3. */
115823    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
115824      /* Remove connection p from the blocked connections list. */
115825      *pp = p->pNextBlocked;
115826      p->pNextBlocked = 0;
115827    }else{
115828      pp = &p->pNextBlocked;
115829    }
115830  }
115831
115832  if( nArg!=0 ){
115833    xUnlockNotify(aArg, nArg);
115834  }
115835  sqlite3_free(aDyn);
115836  leaveMutex();         /* Leave STATIC_MASTER mutex */
115837}
115838
115839/*
115840** This is called when the database connection passed as an argument is
115841** being closed. The connection is removed from the blocked list.
115842*/
115843SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
115844  sqlite3ConnectionUnlocked(db);
115845  enterMutex();
115846  removeFromBlockedList(db);
115847  checkListProperties(db);
115848  leaveMutex();
115849}
115850#endif
115851
115852/************** End of notify.c **********************************************/
115853/************** Begin file fts3.c ********************************************/
115854/*
115855** 2006 Oct 10
115856**
115857** The author disclaims copyright to this source code.  In place of
115858** a legal notice, here is a blessing:
115859**
115860**    May you do good and not evil.
115861**    May you find forgiveness for yourself and forgive others.
115862**    May you share freely, never taking more than you give.
115863**
115864******************************************************************************
115865**
115866** This is an SQLite module implementing full-text search.
115867*/
115868
115869/*
115870** The code in this file is only compiled if:
115871**
115872**     * The FTS3 module is being built as an extension
115873**       (in which case SQLITE_CORE is not defined), or
115874**
115875**     * The FTS3 module is being built into the core of
115876**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
115877*/
115878
115879/* The full-text index is stored in a series of b+tree (-like)
115880** structures called segments which map terms to doclists.  The
115881** structures are like b+trees in layout, but are constructed from the
115882** bottom up in optimal fashion and are not updatable.  Since trees
115883** are built from the bottom up, things will be described from the
115884** bottom up.
115885**
115886**
115887**** Varints ****
115888** The basic unit of encoding is a variable-length integer called a
115889** varint.  We encode variable-length integers in little-endian order
115890** using seven bits * per byte as follows:
115891**
115892** KEY:
115893**         A = 0xxxxxxx    7 bits of data and one flag bit
115894**         B = 1xxxxxxx    7 bits of data and one flag bit
115895**
115896**  7 bits - A
115897** 14 bits - BA
115898** 21 bits - BBA
115899** and so on.
115900**
115901** This is similar in concept to how sqlite encodes "varints" but
115902** the encoding is not the same.  SQLite varints are big-endian
115903** are are limited to 9 bytes in length whereas FTS3 varints are
115904** little-endian and can be up to 10 bytes in length (in theory).
115905**
115906** Example encodings:
115907**
115908**     1:    0x01
115909**   127:    0x7f
115910**   128:    0x81 0x00
115911**
115912**
115913**** Document lists ****
115914** A doclist (document list) holds a docid-sorted list of hits for a
115915** given term.  Doclists hold docids and associated token positions.
115916** A docid is the unique integer identifier for a single document.
115917** A position is the index of a word within the document.  The first
115918** word of the document has a position of 0.
115919**
115920** FTS3 used to optionally store character offsets using a compile-time
115921** option.  But that functionality is no longer supported.
115922**
115923** A doclist is stored like this:
115924**
115925** array {
115926**   varint docid;
115927**   array {                (position list for column 0)
115928**     varint position;     (2 more than the delta from previous position)
115929**   }
115930**   array {
115931**     varint POS_COLUMN;   (marks start of position list for new column)
115932**     varint column;       (index of new column)
115933**     array {
115934**       varint position;   (2 more than the delta from previous position)
115935**     }
115936**   }
115937**   varint POS_END;        (marks end of positions for this document.
115938** }
115939**
115940** Here, array { X } means zero or more occurrences of X, adjacent in
115941** memory.  A "position" is an index of a token in the token stream
115942** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
115943** in the same logical place as the position element, and act as sentinals
115944** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
115945** The positions numbers are not stored literally but rather as two more
115946** than the difference from the prior position, or the just the position plus
115947** 2 for the first position.  Example:
115948**
115949**   label:       A B C D E  F  G H   I  J K
115950**   value:     123 5 9 1 1 14 35 0 234 72 0
115951**
115952** The 123 value is the first docid.  For column zero in this document
115953** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
115954** at D signals the start of a new column; the 1 at E indicates that the
115955** new column is column number 1.  There are two positions at 12 and 45
115956** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
115957** 234 at I is the next docid.  It has one position 72 (72-2) and then
115958** terminates with the 0 at K.
115959**
115960** A "position-list" is the list of positions for multiple columns for
115961** a single docid.  A "column-list" is the set of positions for a single
115962** column.  Hence, a position-list consists of one or more column-lists,
115963** a document record consists of a docid followed by a position-list and
115964** a doclist consists of one or more document records.
115965**
115966** A bare doclist omits the position information, becoming an
115967** array of varint-encoded docids.
115968**
115969**** Segment leaf nodes ****
115970** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
115971** nodes are written using LeafWriter, and read using LeafReader (to
115972** iterate through a single leaf node's data) and LeavesReader (to
115973** iterate through a segment's entire leaf layer).  Leaf nodes have
115974** the format:
115975**
115976** varint iHeight;             (height from leaf level, always 0)
115977** varint nTerm;               (length of first term)
115978** char pTerm[nTerm];          (content of first term)
115979** varint nDoclist;            (length of term's associated doclist)
115980** char pDoclist[nDoclist];    (content of doclist)
115981** array {
115982**                             (further terms are delta-encoded)
115983**   varint nPrefix;           (length of prefix shared with previous term)
115984**   varint nSuffix;           (length of unshared suffix)
115985**   char pTermSuffix[nSuffix];(unshared suffix of next term)
115986**   varint nDoclist;          (length of term's associated doclist)
115987**   char pDoclist[nDoclist];  (content of doclist)
115988** }
115989**
115990** Here, array { X } means zero or more occurrences of X, adjacent in
115991** memory.
115992**
115993** Leaf nodes are broken into blocks which are stored contiguously in
115994** the %_segments table in sorted order.  This means that when the end
115995** of a node is reached, the next term is in the node with the next
115996** greater node id.
115997**
115998** New data is spilled to a new leaf node when the current node
115999** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
116000** larger than STANDALONE_MIN (default 1024) is placed in a standalone
116001** node (a leaf node with a single term and doclist).  The goal of
116002** these settings is to pack together groups of small doclists while
116003** making it efficient to directly access large doclists.  The
116004** assumption is that large doclists represent terms which are more
116005** likely to be query targets.
116006**
116007** TODO(shess) It may be useful for blocking decisions to be more
116008** dynamic.  For instance, it may make more sense to have a 2.5k leaf
116009** node rather than splitting into 2k and .5k nodes.  My intuition is
116010** that this might extend through 2x or 4x the pagesize.
116011**
116012**
116013**** Segment interior nodes ****
116014** Segment interior nodes store blockids for subtree nodes and terms
116015** to describe what data is stored by the each subtree.  Interior
116016** nodes are written using InteriorWriter, and read using
116017** InteriorReader.  InteriorWriters are created as needed when
116018** SegmentWriter creates new leaf nodes, or when an interior node
116019** itself grows too big and must be split.  The format of interior
116020** nodes:
116021**
116022** varint iHeight;           (height from leaf level, always >0)
116023** varint iBlockid;          (block id of node's leftmost subtree)
116024** optional {
116025**   varint nTerm;           (length of first term)
116026**   char pTerm[nTerm];      (content of first term)
116027**   array {
116028**                                (further terms are delta-encoded)
116029**     varint nPrefix;            (length of shared prefix with previous term)
116030**     varint nSuffix;            (length of unshared suffix)
116031**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
116032**   }
116033** }
116034**
116035** Here, optional { X } means an optional element, while array { X }
116036** means zero or more occurrences of X, adjacent in memory.
116037**
116038** An interior node encodes n terms separating n+1 subtrees.  The
116039** subtree blocks are contiguous, so only the first subtree's blockid
116040** is encoded.  The subtree at iBlockid will contain all terms less
116041** than the first term encoded (or all terms if no term is encoded).
116042** Otherwise, for terms greater than or equal to pTerm[i] but less
116043** than pTerm[i+1], the subtree for that term will be rooted at
116044** iBlockid+i.  Interior nodes only store enough term data to
116045** distinguish adjacent children (if the rightmost term of the left
116046** child is "something", and the leftmost term of the right child is
116047** "wicked", only "w" is stored).
116048**
116049** New data is spilled to a new interior node at the same height when
116050** the current node exceeds INTERIOR_MAX bytes (default 2048).
116051** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
116052** interior nodes and making the tree too skinny.  The interior nodes
116053** at a given height are naturally tracked by interior nodes at
116054** height+1, and so on.
116055**
116056**
116057**** Segment directory ****
116058** The segment directory in table %_segdir stores meta-information for
116059** merging and deleting segments, and also the root node of the
116060** segment's tree.
116061**
116062** The root node is the top node of the segment's tree after encoding
116063** the entire segment, restricted to ROOT_MAX bytes (default 1024).
116064** This could be either a leaf node or an interior node.  If the top
116065** node requires more than ROOT_MAX bytes, it is flushed to %_segments
116066** and a new root interior node is generated (which should always fit
116067** within ROOT_MAX because it only needs space for 2 varints, the
116068** height and the blockid of the previous root).
116069**
116070** The meta-information in the segment directory is:
116071**   level               - segment level (see below)
116072**   idx                 - index within level
116073**                       - (level,idx uniquely identify a segment)
116074**   start_block         - first leaf node
116075**   leaves_end_block    - last leaf node
116076**   end_block           - last block (including interior nodes)
116077**   root                - contents of root node
116078**
116079** If the root node is a leaf node, then start_block,
116080** leaves_end_block, and end_block are all 0.
116081**
116082**
116083**** Segment merging ****
116084** To amortize update costs, segments are grouped into levels and
116085** merged in batches.  Each increase in level represents exponentially
116086** more documents.
116087**
116088** New documents (actually, document updates) are tokenized and
116089** written individually (using LeafWriter) to a level 0 segment, with
116090** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
116091** level 0 segments are merged into a single level 1 segment.  Level 1
116092** is populated like level 0, and eventually MERGE_COUNT level 1
116093** segments are merged to a single level 2 segment (representing
116094** MERGE_COUNT^2 updates), and so on.
116095**
116096** A segment merge traverses all segments at a given level in
116097** parallel, performing a straightforward sorted merge.  Since segment
116098** leaf nodes are written in to the %_segments table in order, this
116099** merge traverses the underlying sqlite disk structures efficiently.
116100** After the merge, all segment blocks from the merged level are
116101** deleted.
116102**
116103** MERGE_COUNT controls how often we merge segments.  16 seems to be
116104** somewhat of a sweet spot for insertion performance.  32 and 64 show
116105** very similar performance numbers to 16 on insertion, though they're
116106** a tiny bit slower (perhaps due to more overhead in merge-time
116107** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
116108** 16, 2 about 66% slower than 16.
116109**
116110** At query time, high MERGE_COUNT increases the number of segments
116111** which need to be scanned and merged.  For instance, with 100k docs
116112** inserted:
116113**
116114**    MERGE_COUNT   segments
116115**       16           25
116116**        8           12
116117**        4           10
116118**        2            6
116119**
116120** This appears to have only a moderate impact on queries for very
116121** frequent terms (which are somewhat dominated by segment merge
116122** costs), and infrequent and non-existent terms still seem to be fast
116123** even with many segments.
116124**
116125** TODO(shess) That said, it would be nice to have a better query-side
116126** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
116127** optimizations to things like doclist merging will swing the sweet
116128** spot around.
116129**
116130**
116131**
116132**** Handling of deletions and updates ****
116133** Since we're using a segmented structure, with no docid-oriented
116134** index into the term index, we clearly cannot simply update the term
116135** index when a document is deleted or updated.  For deletions, we
116136** write an empty doclist (varint(docid) varint(POS_END)), for updates
116137** we simply write the new doclist.  Segment merges overwrite older
116138** data for a particular docid with newer data, so deletes or updates
116139** will eventually overtake the earlier data and knock it out.  The
116140** query logic likewise merges doclists so that newer data knocks out
116141** older data.
116142*/
116143
116144/************** Include fts3Int.h in the middle of fts3.c ********************/
116145/************** Begin file fts3Int.h *****************************************/
116146/*
116147** 2009 Nov 12
116148**
116149** The author disclaims copyright to this source code.  In place of
116150** a legal notice, here is a blessing:
116151**
116152**    May you do good and not evil.
116153**    May you find forgiveness for yourself and forgive others.
116154**    May you share freely, never taking more than you give.
116155**
116156******************************************************************************
116157**
116158*/
116159#ifndef _FTSINT_H
116160#define _FTSINT_H
116161
116162#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
116163# define NDEBUG 1
116164#endif
116165
116166/*
116167** FTS4 is really an extension for FTS3.  It is enabled using the
116168** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
116169** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
116170*/
116171#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
116172# define SQLITE_ENABLE_FTS3
116173#endif
116174
116175#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116176
116177/* If not building as part of the core, include sqlite3ext.h. */
116178#ifndef SQLITE_CORE
116179SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
116180#endif
116181
116182/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
116183/************** Begin file fts3_tokenizer.h **********************************/
116184/*
116185** 2006 July 10
116186**
116187** The author disclaims copyright to this source code.
116188**
116189*************************************************************************
116190** Defines the interface to tokenizers used by fulltext-search.  There
116191** are three basic components:
116192**
116193** sqlite3_tokenizer_module is a singleton defining the tokenizer
116194** interface functions.  This is essentially the class structure for
116195** tokenizers.
116196**
116197** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
116198** including customization information defined at creation time.
116199**
116200** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
116201** tokens from a particular input.
116202*/
116203#ifndef _FTS3_TOKENIZER_H_
116204#define _FTS3_TOKENIZER_H_
116205
116206/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
116207** If tokenizers are to be allowed to call sqlite3_*() functions, then
116208** we will need a way to register the API consistently.
116209*/
116210
116211/*
116212** Structures used by the tokenizer interface. When a new tokenizer
116213** implementation is registered, the caller provides a pointer to
116214** an sqlite3_tokenizer_module containing pointers to the callback
116215** functions that make up an implementation.
116216**
116217** When an fts3 table is created, it passes any arguments passed to
116218** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
116219** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
116220** implementation. The xCreate() function in turn returns an
116221** sqlite3_tokenizer structure representing the specific tokenizer to
116222** be used for the fts3 table (customized by the tokenizer clause arguments).
116223**
116224** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
116225** method is called. It returns an sqlite3_tokenizer_cursor object
116226** that may be used to tokenize a specific input buffer based on
116227** the tokenization rules supplied by a specific sqlite3_tokenizer
116228** object.
116229*/
116230typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
116231typedef struct sqlite3_tokenizer sqlite3_tokenizer;
116232typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
116233
116234struct sqlite3_tokenizer_module {
116235
116236  /*
116237  ** Structure version. Should always be set to 0 or 1.
116238  */
116239  int iVersion;
116240
116241  /*
116242  ** Create a new tokenizer. The values in the argv[] array are the
116243  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
116244  ** TABLE statement that created the fts3 table. For example, if
116245  ** the following SQL is executed:
116246  **
116247  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
116248  **
116249  ** then argc is set to 2, and the argv[] array contains pointers
116250  ** to the strings "arg1" and "arg2".
116251  **
116252  ** This method should return either SQLITE_OK (0), or an SQLite error
116253  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
116254  ** to point at the newly created tokenizer structure. The generic
116255  ** sqlite3_tokenizer.pModule variable should not be initialised by
116256  ** this callback. The caller will do so.
116257  */
116258  int (*xCreate)(
116259    int argc,                           /* Size of argv array */
116260    const char *const*argv,             /* Tokenizer argument strings */
116261    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
116262  );
116263
116264  /*
116265  ** Destroy an existing tokenizer. The fts3 module calls this method
116266  ** exactly once for each successful call to xCreate().
116267  */
116268  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
116269
116270  /*
116271  ** Create a tokenizer cursor to tokenize an input buffer. The caller
116272  ** is responsible for ensuring that the input buffer remains valid
116273  ** until the cursor is closed (using the xClose() method).
116274  */
116275  int (*xOpen)(
116276    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
116277    const char *pInput, int nBytes,      /* Input buffer */
116278    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
116279  );
116280
116281  /*
116282  ** Destroy an existing tokenizer cursor. The fts3 module calls this
116283  ** method exactly once for each successful call to xOpen().
116284  */
116285  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
116286
116287  /*
116288  ** Retrieve the next token from the tokenizer cursor pCursor. This
116289  ** method should either return SQLITE_OK and set the values of the
116290  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
116291  ** the end of the buffer has been reached, or an SQLite error code.
116292  **
116293  ** *ppToken should be set to point at a buffer containing the
116294  ** normalized version of the token (i.e. after any case-folding and/or
116295  ** stemming has been performed). *pnBytes should be set to the length
116296  ** of this buffer in bytes. The input text that generated the token is
116297  ** identified by the byte offsets returned in *piStartOffset and
116298  ** *piEndOffset. *piStartOffset should be set to the index of the first
116299  ** byte of the token in the input buffer. *piEndOffset should be set
116300  ** to the index of the first byte just past the end of the token in
116301  ** the input buffer.
116302  **
116303  ** The buffer *ppToken is set to point at is managed by the tokenizer
116304  ** implementation. It is only required to be valid until the next call
116305  ** to xNext() or xClose().
116306  */
116307  /* TODO(shess) current implementation requires pInput to be
116308  ** nul-terminated.  This should either be fixed, or pInput/nBytes
116309  ** should be converted to zInput.
116310  */
116311  int (*xNext)(
116312    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
116313    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
116314    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
116315    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
116316    int *piPosition      /* OUT: Number of tokens returned before this one */
116317  );
116318
116319  /***********************************************************************
116320  ** Methods below this point are only available if iVersion>=1.
116321  */
116322
116323  /*
116324  ** Configure the language id of a tokenizer cursor.
116325  */
116326  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
116327};
116328
116329struct sqlite3_tokenizer {
116330  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
116331  /* Tokenizer implementations will typically add additional fields */
116332};
116333
116334struct sqlite3_tokenizer_cursor {
116335  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
116336  /* Tokenizer implementations will typically add additional fields */
116337};
116338
116339int fts3_global_term_cnt(int iTerm, int iCol);
116340int fts3_term_cnt(int iTerm, int iCol);
116341
116342
116343#endif /* _FTS3_TOKENIZER_H_ */
116344
116345/************** End of fts3_tokenizer.h **************************************/
116346/************** Continuing where we left off in fts3Int.h ********************/
116347/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
116348/************** Begin file fts3_hash.h ***************************************/
116349/*
116350** 2001 September 22
116351**
116352** The author disclaims copyright to this source code.  In place of
116353** a legal notice, here is a blessing:
116354**
116355**    May you do good and not evil.
116356**    May you find forgiveness for yourself and forgive others.
116357**    May you share freely, never taking more than you give.
116358**
116359*************************************************************************
116360** This is the header file for the generic hash-table implemenation
116361** used in SQLite.  We've modified it slightly to serve as a standalone
116362** hash table implementation for the full-text indexing module.
116363**
116364*/
116365#ifndef _FTS3_HASH_H_
116366#define _FTS3_HASH_H_
116367
116368/* Forward declarations of structures. */
116369typedef struct Fts3Hash Fts3Hash;
116370typedef struct Fts3HashElem Fts3HashElem;
116371
116372/* A complete hash table is an instance of the following structure.
116373** The internals of this structure are intended to be opaque -- client
116374** code should not attempt to access or modify the fields of this structure
116375** directly.  Change this structure only by using the routines below.
116376** However, many of the "procedures" and "functions" for modifying and
116377** accessing this structure are really macros, so we can't really make
116378** this structure opaque.
116379*/
116380struct Fts3Hash {
116381  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
116382  char copyKey;           /* True if copy of key made on insert */
116383  int count;              /* Number of entries in this table */
116384  Fts3HashElem *first;    /* The first element of the array */
116385  int htsize;             /* Number of buckets in the hash table */
116386  struct _fts3ht {        /* the hash table */
116387    int count;               /* Number of entries with this hash */
116388    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
116389  } *ht;
116390};
116391
116392/* Each element in the hash table is an instance of the following
116393** structure.  All elements are stored on a single doubly-linked list.
116394**
116395** Again, this structure is intended to be opaque, but it can't really
116396** be opaque because it is used by macros.
116397*/
116398struct Fts3HashElem {
116399  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
116400  void *data;                /* Data associated with this element */
116401  void *pKey; int nKey;      /* Key associated with this element */
116402};
116403
116404/*
116405** There are 2 different modes of operation for a hash table:
116406**
116407**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
116408**                           (including the null-terminator, if any).  Case
116409**                           is respected in comparisons.
116410**
116411**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
116412**                           memcmp() is used to compare keys.
116413**
116414** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
116415*/
116416#define FTS3_HASH_STRING    1
116417#define FTS3_HASH_BINARY    2
116418
116419/*
116420** Access routines.  To delete, insert a NULL pointer.
116421*/
116422SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
116423SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
116424SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
116425SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
116426SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
116427
116428/*
116429** Shorthand for the functions above
116430*/
116431#define fts3HashInit     sqlite3Fts3HashInit
116432#define fts3HashInsert   sqlite3Fts3HashInsert
116433#define fts3HashFind     sqlite3Fts3HashFind
116434#define fts3HashClear    sqlite3Fts3HashClear
116435#define fts3HashFindElem sqlite3Fts3HashFindElem
116436
116437/*
116438** Macros for looping over all elements of a hash table.  The idiom is
116439** like this:
116440**
116441**   Fts3Hash h;
116442**   Fts3HashElem *p;
116443**   ...
116444**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
116445**     SomeStructure *pData = fts3HashData(p);
116446**     // do something with pData
116447**   }
116448*/
116449#define fts3HashFirst(H)  ((H)->first)
116450#define fts3HashNext(E)   ((E)->next)
116451#define fts3HashData(E)   ((E)->data)
116452#define fts3HashKey(E)    ((E)->pKey)
116453#define fts3HashKeysize(E) ((E)->nKey)
116454
116455/*
116456** Number of entries in a hash table
116457*/
116458#define fts3HashCount(H)  ((H)->count)
116459
116460#endif /* _FTS3_HASH_H_ */
116461
116462/************** End of fts3_hash.h *******************************************/
116463/************** Continuing where we left off in fts3Int.h ********************/
116464
116465/*
116466** This constant controls how often segments are merged. Once there are
116467** FTS3_MERGE_COUNT segments of level N, they are merged into a single
116468** segment of level N+1.
116469*/
116470#define FTS3_MERGE_COUNT 16
116471
116472/*
116473** This is the maximum amount of data (in bytes) to store in the
116474** Fts3Table.pendingTerms hash table. Normally, the hash table is
116475** populated as documents are inserted/updated/deleted in a transaction
116476** and used to create a new segment when the transaction is committed.
116477** However if this limit is reached midway through a transaction, a new
116478** segment is created and the hash table cleared immediately.
116479*/
116480#define FTS3_MAX_PENDING_DATA (1*1024*1024)
116481
116482/*
116483** Macro to return the number of elements in an array. SQLite has a
116484** similar macro called ArraySize(). Use a different name to avoid
116485** a collision when building an amalgamation with built-in FTS3.
116486*/
116487#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
116488
116489
116490#ifndef MIN
116491# define MIN(x,y) ((x)<(y)?(x):(y))
116492#endif
116493
116494/*
116495** Maximum length of a varint encoded integer. The varint format is different
116496** from that used by SQLite, so the maximum length is 10, not 9.
116497*/
116498#define FTS3_VARINT_MAX 10
116499
116500/*
116501** FTS4 virtual tables may maintain multiple indexes - one index of all terms
116502** in the document set and zero or more prefix indexes. All indexes are stored
116503** as one or more b+-trees in the %_segments and %_segdir tables.
116504**
116505** It is possible to determine which index a b+-tree belongs to based on the
116506** value stored in the "%_segdir.level" column. Given this value L, the index
116507** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
116508** level values between 0 and 1023 (inclusive) belong to index 0, all levels
116509** between 1024 and 2047 to index 1, and so on.
116510**
116511** It is considered impossible for an index to use more than 1024 levels. In
116512** theory though this may happen, but only after at least
116513** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
116514*/
116515#define FTS3_SEGDIR_MAXLEVEL      1024
116516#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
116517
116518/*
116519** The testcase() macro is only used by the amalgamation.  If undefined,
116520** make it a no-op.
116521*/
116522#ifndef testcase
116523# define testcase(X)
116524#endif
116525
116526/*
116527** Terminator values for position-lists and column-lists.
116528*/
116529#define POS_COLUMN  (1)     /* Column-list terminator */
116530#define POS_END     (0)     /* Position-list terminator */
116531
116532/*
116533** This section provides definitions to allow the
116534** FTS3 extension to be compiled outside of the
116535** amalgamation.
116536*/
116537#ifndef SQLITE_AMALGAMATION
116538/*
116539** Macros indicating that conditional expressions are always true or
116540** false.
116541*/
116542#ifdef SQLITE_COVERAGE_TEST
116543# define ALWAYS(x) (1)
116544# define NEVER(X)  (0)
116545#else
116546# define ALWAYS(x) (x)
116547# define NEVER(X)  (x)
116548#endif
116549
116550/*
116551** Internal types used by SQLite.
116552*/
116553typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
116554typedef short int i16;            /* 2-byte (or larger) signed integer */
116555typedef unsigned int u32;         /* 4-byte unsigned integer */
116556typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
116557
116558/*
116559** Macro used to suppress compiler warnings for unused parameters.
116560*/
116561#define UNUSED_PARAMETER(x) (void)(x)
116562
116563/*
116564** Activate assert() only if SQLITE_TEST is enabled.
116565*/
116566#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
116567# define NDEBUG 1
116568#endif
116569
116570/*
116571** The TESTONLY macro is used to enclose variable declarations or
116572** other bits of code that are needed to support the arguments
116573** within testcase() and assert() macros.
116574*/
116575#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
116576# define TESTONLY(X)  X
116577#else
116578# define TESTONLY(X)
116579#endif
116580
116581#endif /* SQLITE_AMALGAMATION */
116582
116583#ifdef SQLITE_DEBUG
116584SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
116585# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
116586#else
116587# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
116588#endif
116589
116590typedef struct Fts3Table Fts3Table;
116591typedef struct Fts3Cursor Fts3Cursor;
116592typedef struct Fts3Expr Fts3Expr;
116593typedef struct Fts3Phrase Fts3Phrase;
116594typedef struct Fts3PhraseToken Fts3PhraseToken;
116595
116596typedef struct Fts3Doclist Fts3Doclist;
116597typedef struct Fts3SegFilter Fts3SegFilter;
116598typedef struct Fts3DeferredToken Fts3DeferredToken;
116599typedef struct Fts3SegReader Fts3SegReader;
116600typedef struct Fts3MultiSegReader Fts3MultiSegReader;
116601
116602/*
116603** A connection to a fulltext index is an instance of the following
116604** structure. The xCreate and xConnect methods create an instance
116605** of this structure and xDestroy and xDisconnect free that instance.
116606** All other methods receive a pointer to the structure as one of their
116607** arguments.
116608*/
116609struct Fts3Table {
116610  sqlite3_vtab base;              /* Base class used by SQLite core */
116611  sqlite3 *db;                    /* The database connection */
116612  const char *zDb;                /* logical database name */
116613  const char *zName;              /* virtual table name */
116614  int nColumn;                    /* number of named columns in virtual table */
116615  char **azColumn;                /* column names.  malloced */
116616  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
116617  char *zContentTbl;              /* content=xxx option, or NULL */
116618  char *zLanguageid;              /* languageid=xxx option, or NULL */
116619
116620  /* Precompiled statements used by the implementation. Each of these
116621  ** statements is run and reset within a single virtual table API call.
116622  */
116623  sqlite3_stmt *aStmt[28];
116624
116625  char *zReadExprlist;
116626  char *zWriteExprlist;
116627
116628  int nNodeSize;                  /* Soft limit for node size */
116629  u8 bHasStat;                    /* True if %_stat table exists */
116630  u8 bHasDocsize;                 /* True if %_docsize table exists */
116631  u8 bDescIdx;                    /* True if doclists are in reverse order */
116632  int nPgsz;                      /* Page size for host database */
116633  char *zSegmentsTbl;             /* Name of %_segments table */
116634  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
116635
116636  /* TODO: Fix the first paragraph of this comment.
116637  **
116638  ** The following array of hash tables is used to buffer pending index
116639  ** updates during transactions. Variable nPendingData estimates the memory
116640  ** size of the pending data, including hash table overhead, not including
116641  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, the buffer
116642  ** is flushed automatically. Variable iPrevDocid is the docid of the most
116643  ** recently inserted record.
116644  **
116645  ** A single FTS4 table may have multiple full-text indexes. For each index
116646  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
116647  ** terms that appear in the document set. Each subsequent index in aIndex[]
116648  ** is an index of prefixes of a specific length.
116649  */
116650  int nIndex;                     /* Size of aIndex[] */
116651  struct Fts3Index {
116652    int nPrefix;                  /* Prefix length (0 for main terms index) */
116653    Fts3Hash hPending;            /* Pending terms table for this index */
116654  } *aIndex;
116655  int nMaxPendingData;            /* Max pending data before flush to disk */
116656  int nPendingData;               /* Current bytes of pending data */
116657  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
116658  int iPrevLangid;                /* Langid of recently inserted document */
116659
116660#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
116661  /* State variables used for validating that the transaction control
116662  ** methods of the virtual table are called at appropriate times.  These
116663  ** values do not contribute to FTS functionality; they are used for
116664  ** verifying the operation of the SQLite core.
116665  */
116666  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
116667  int mxSavepoint;       /* Largest valid xSavepoint integer */
116668#endif
116669};
116670
116671/*
116672** When the core wants to read from the virtual table, it creates a
116673** virtual table cursor (an instance of the following structure) using
116674** the xOpen method. Cursors are destroyed using the xClose method.
116675*/
116676struct Fts3Cursor {
116677  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
116678  i16 eSearch;                    /* Search strategy (see below) */
116679  u8 isEof;                       /* True if at End Of Results */
116680  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
116681  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
116682  Fts3Expr *pExpr;                /* Parsed MATCH query string */
116683  int iLangid;                    /* Language being queried for */
116684  int nPhrase;                    /* Number of matchable phrases in query */
116685  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
116686  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
116687  char *pNextId;                  /* Pointer into the body of aDoclist */
116688  char *aDoclist;                 /* List of docids for full-text queries */
116689  int nDoclist;                   /* Size of buffer at aDoclist */
116690  u8 bDesc;                       /* True to sort in descending order */
116691  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
116692  int nRowAvg;                    /* Average size of database rows, in pages */
116693  sqlite3_int64 nDoc;             /* Documents in table */
116694
116695  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
116696  u32 *aMatchinfo;                /* Information about most recent match */
116697  int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
116698  char *zMatchinfo;               /* Matchinfo specification */
116699};
116700
116701#define FTS3_EVAL_FILTER    0
116702#define FTS3_EVAL_NEXT      1
116703#define FTS3_EVAL_MATCHINFO 2
116704
116705/*
116706** The Fts3Cursor.eSearch member is always set to one of the following.
116707** Actualy, Fts3Cursor.eSearch can be greater than or equal to
116708** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
116709** of the column to be searched.  For example, in
116710**
116711**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
116712**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
116713**
116714** Because the LHS of the MATCH operator is 2nd column "b",
116715** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
116716** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
116717** indicating that all columns should be searched,
116718** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
116719*/
116720#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
116721#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
116722#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
116723
116724
116725struct Fts3Doclist {
116726  char *aAll;                    /* Array containing doclist (or NULL) */
116727  int nAll;                      /* Size of a[] in bytes */
116728  char *pNextDocid;              /* Pointer to next docid */
116729
116730  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
116731  int bFreeList;                 /* True if pList should be sqlite3_free()d */
116732  char *pList;                   /* Pointer to position list following iDocid */
116733  int nList;                     /* Length of position list */
116734};
116735
116736/*
116737** A "phrase" is a sequence of one or more tokens that must match in
116738** sequence.  A single token is the base case and the most common case.
116739** For a sequence of tokens contained in double-quotes (i.e. "one two three")
116740** nToken will be the number of tokens in the string.
116741*/
116742struct Fts3PhraseToken {
116743  char *z;                        /* Text of the token */
116744  int n;                          /* Number of bytes in buffer z */
116745  int isPrefix;                   /* True if token ends with a "*" character */
116746  int bFirst;                     /* True if token must appear at position 0 */
116747
116748  /* Variables above this point are populated when the expression is
116749  ** parsed (by code in fts3_expr.c). Below this point the variables are
116750  ** used when evaluating the expression. */
116751  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
116752  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
116753};
116754
116755struct Fts3Phrase {
116756  /* Cache of doclist for this phrase. */
116757  Fts3Doclist doclist;
116758  int bIncr;                 /* True if doclist is loaded incrementally */
116759  int iDoclistToken;
116760
116761  /* Variables below this point are populated by fts3_expr.c when parsing
116762  ** a MATCH expression. Everything above is part of the evaluation phase.
116763  */
116764  int nToken;                /* Number of tokens in the phrase */
116765  int iColumn;               /* Index of column this phrase must match */
116766  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
116767};
116768
116769/*
116770** A tree of these objects forms the RHS of a MATCH operator.
116771**
116772** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
116773** points to a malloced buffer, size nDoclist bytes, containing the results
116774** of this phrase query in FTS3 doclist format. As usual, the initial
116775** "Length" field found in doclists stored on disk is omitted from this
116776** buffer.
116777**
116778** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
116779** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
116780** where nCol is the number of columns in the queried FTS table. The array
116781** is populated as follows:
116782**
116783**   aMI[iCol*3 + 0] = Undefined
116784**   aMI[iCol*3 + 1] = Number of occurrences
116785**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
116786**
116787** The aMI array is allocated using sqlite3_malloc(). It should be freed
116788** when the expression node is.
116789*/
116790struct Fts3Expr {
116791  int eType;                 /* One of the FTSQUERY_XXX values defined below */
116792  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
116793  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
116794  Fts3Expr *pLeft;           /* Left operand */
116795  Fts3Expr *pRight;          /* Right operand */
116796  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
116797
116798  /* The following are used by the fts3_eval.c module. */
116799  sqlite3_int64 iDocid;      /* Current docid */
116800  u8 bEof;                   /* True this expression is at EOF already */
116801  u8 bStart;                 /* True if iDocid is valid */
116802  u8 bDeferred;              /* True if this expression is entirely deferred */
116803
116804  u32 *aMI;
116805};
116806
116807/*
116808** Candidate values for Fts3Query.eType. Note that the order of the first
116809** four values is in order of precedence when parsing expressions. For
116810** example, the following:
116811**
116812**   "a OR b AND c NOT d NEAR e"
116813**
116814** is equivalent to:
116815**
116816**   "a OR (b AND (c NOT (d NEAR e)))"
116817*/
116818#define FTSQUERY_NEAR   1
116819#define FTSQUERY_NOT    2
116820#define FTSQUERY_AND    3
116821#define FTSQUERY_OR     4
116822#define FTSQUERY_PHRASE 5
116823
116824
116825/* fts3_write.c */
116826SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
116827SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
116828SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
116829SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
116830SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
116831  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
116832SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
116833  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
116834SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
116835SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
116836SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
116837SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
116838
116839SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
116840SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
116841
116842SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
116843SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
116844SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
116845SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
116846SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
116847
116848/* Special values interpreted by sqlite3SegReaderCursor() */
116849#define FTS3_SEGCURSOR_PENDING        -1
116850#define FTS3_SEGCURSOR_ALL            -2
116851
116852SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
116853SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
116854SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
116855
116856SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
116857    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
116858
116859/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
116860#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
116861#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
116862#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
116863#define FTS3_SEGMENT_PREFIX        0x00000008
116864#define FTS3_SEGMENT_SCAN          0x00000010
116865#define FTS3_SEGMENT_FIRST         0x00000020
116866
116867/* Type passed as 4th argument to SegmentReaderIterate() */
116868struct Fts3SegFilter {
116869  const char *zTerm;
116870  int nTerm;
116871  int iCol;
116872  int flags;
116873};
116874
116875struct Fts3MultiSegReader {
116876  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
116877  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
116878  int nSegment;                   /* Size of apSegment array */
116879  int nAdvance;                   /* How many seg-readers to advance */
116880  Fts3SegFilter *pFilter;         /* Pointer to filter object */
116881  char *aBuffer;                  /* Buffer to merge doclists in */
116882  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
116883
116884  int iColFilter;                 /* If >=0, filter for this column */
116885  int bRestart;
116886
116887  /* Used by fts3.c only. */
116888  int nCost;                      /* Cost of running iterator */
116889  int bLookup;                    /* True if a lookup of a single entry. */
116890
116891  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
116892  char *zTerm;                    /* Pointer to term buffer */
116893  int nTerm;                      /* Size of zTerm in bytes */
116894  char *aDoclist;                 /* Pointer to doclist buffer */
116895  int nDoclist;                   /* Size of aDoclist[] in bytes */
116896};
116897
116898/* fts3.c */
116899SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
116900SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
116901SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
116902SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
116903SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
116904SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
116905SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
116906SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
116907
116908/* fts3_tokenizer.c */
116909SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
116910SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
116911SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
116912    sqlite3_tokenizer **, char **
116913);
116914SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
116915
116916/* fts3_snippet.c */
116917SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
116918SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
116919  const char *, const char *, int, int
116920);
116921SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
116922
116923/* fts3_expr.c */
116924SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
116925  char **, int, int, int, const char *, int, Fts3Expr **
116926);
116927SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
116928#ifdef SQLITE_TEST
116929SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
116930SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
116931#endif
116932
116933SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
116934  sqlite3_tokenizer_cursor **
116935);
116936
116937/* fts3_aux.c */
116938SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
116939
116940SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
116941
116942SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
116943    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
116944SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
116945    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
116946SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol);
116947SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
116948SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
116949
116950SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
116951
116952#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
116953#endif /* _FTSINT_H */
116954
116955/************** End of fts3Int.h *********************************************/
116956/************** Continuing where we left off in fts3.c ***********************/
116957#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116958
116959#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
116960# define SQLITE_CORE 1
116961#endif
116962
116963/* #include <assert.h> */
116964/* #include <stdlib.h> */
116965/* #include <stddef.h> */
116966/* #include <stdio.h> */
116967/* #include <string.h> */
116968/* #include <stdarg.h> */
116969
116970#ifndef SQLITE_CORE
116971  SQLITE_EXTENSION_INIT1
116972#endif
116973
116974static int fts3EvalNext(Fts3Cursor *pCsr);
116975static int fts3EvalStart(Fts3Cursor *pCsr);
116976static int fts3TermSegReaderCursor(
116977    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
116978
116979/*
116980** Write a 64-bit variable-length integer to memory starting at p[0].
116981** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
116982** The number of bytes written is returned.
116983*/
116984SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
116985  unsigned char *q = (unsigned char *) p;
116986  sqlite_uint64 vu = v;
116987  do{
116988    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
116989    vu >>= 7;
116990  }while( vu!=0 );
116991  q[-1] &= 0x7f;  /* turn off high bit in final byte */
116992  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
116993  return (int) (q - (unsigned char *)p);
116994}
116995
116996/*
116997** Read a 64-bit variable-length integer from memory starting at p[0].
116998** Return the number of bytes read, or 0 on error.
116999** The value is stored in *v.
117000*/
117001SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
117002  const unsigned char *q = (const unsigned char *) p;
117003  sqlite_uint64 x = 0, y = 1;
117004  while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
117005    x += y * (*q++ & 0x7f);
117006    y <<= 7;
117007  }
117008  x += y * (*q++);
117009  *v = (sqlite_int64) x;
117010  return (int) (q - (unsigned char *)p);
117011}
117012
117013/*
117014** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
117015** 32-bit integer before it is returned.
117016*/
117017SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
117018 sqlite_int64 i;
117019 int ret = sqlite3Fts3GetVarint(p, &i);
117020 *pi = (int) i;
117021 return ret;
117022}
117023
117024/*
117025** Return the number of bytes required to encode v as a varint
117026*/
117027SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
117028  int i = 0;
117029  do{
117030    i++;
117031    v >>= 7;
117032  }while( v!=0 );
117033  return i;
117034}
117035
117036/*
117037** Convert an SQL-style quoted string into a normal string by removing
117038** the quote characters.  The conversion is done in-place.  If the
117039** input does not begin with a quote character, then this routine
117040** is a no-op.
117041**
117042** Examples:
117043**
117044**     "abc"   becomes   abc
117045**     'xyz'   becomes   xyz
117046**     [pqr]   becomes   pqr
117047**     `mno`   becomes   mno
117048**
117049*/
117050SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
117051  char quote;                     /* Quote character (if any ) */
117052
117053  quote = z[0];
117054  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
117055    int iIn = 1;                  /* Index of next byte to read from input */
117056    int iOut = 0;                 /* Index of next byte to write to output */
117057
117058    /* If the first byte was a '[', then the close-quote character is a ']' */
117059    if( quote=='[' ) quote = ']';
117060
117061    while( ALWAYS(z[iIn]) ){
117062      if( z[iIn]==quote ){
117063        if( z[iIn+1]!=quote ) break;
117064        z[iOut++] = quote;
117065        iIn += 2;
117066      }else{
117067        z[iOut++] = z[iIn++];
117068      }
117069    }
117070    z[iOut] = '\0';
117071  }
117072}
117073
117074/*
117075** Read a single varint from the doclist at *pp and advance *pp to point
117076** to the first byte past the end of the varint.  Add the value of the varint
117077** to *pVal.
117078*/
117079static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
117080  sqlite3_int64 iVal;
117081  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
117082  *pVal += iVal;
117083}
117084
117085/*
117086** When this function is called, *pp points to the first byte following a
117087** varint that is part of a doclist (or position-list, or any other list
117088** of varints). This function moves *pp to point to the start of that varint,
117089** and sets *pVal by the varint value.
117090**
117091** Argument pStart points to the first byte of the doclist that the
117092** varint is part of.
117093*/
117094static void fts3GetReverseVarint(
117095  char **pp,
117096  char *pStart,
117097  sqlite3_int64 *pVal
117098){
117099  sqlite3_int64 iVal;
117100  char *p;
117101
117102  /* Pointer p now points at the first byte past the varint we are
117103  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
117104  ** clear on character p[-1]. */
117105  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
117106  p++;
117107  *pp = p;
117108
117109  sqlite3Fts3GetVarint(p, &iVal);
117110  *pVal = iVal;
117111}
117112
117113/*
117114** The xDisconnect() virtual table method.
117115*/
117116static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
117117  Fts3Table *p = (Fts3Table *)pVtab;
117118  int i;
117119
117120  assert( p->nPendingData==0 );
117121  assert( p->pSegments==0 );
117122
117123  /* Free any prepared statements held */
117124  for(i=0; i<SizeofArray(p->aStmt); i++){
117125    sqlite3_finalize(p->aStmt[i]);
117126  }
117127  sqlite3_free(p->zSegmentsTbl);
117128  sqlite3_free(p->zReadExprlist);
117129  sqlite3_free(p->zWriteExprlist);
117130  sqlite3_free(p->zContentTbl);
117131  sqlite3_free(p->zLanguageid);
117132
117133  /* Invoke the tokenizer destructor to free the tokenizer. */
117134  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
117135
117136  sqlite3_free(p);
117137  return SQLITE_OK;
117138}
117139
117140/*
117141** Construct one or more SQL statements from the format string given
117142** and then evaluate those statements. The success code is written
117143** into *pRc.
117144**
117145** If *pRc is initially non-zero then this routine is a no-op.
117146*/
117147static void fts3DbExec(
117148  int *pRc,              /* Success code */
117149  sqlite3 *db,           /* Database in which to run SQL */
117150  const char *zFormat,   /* Format string for SQL */
117151  ...                    /* Arguments to the format string */
117152){
117153  va_list ap;
117154  char *zSql;
117155  if( *pRc ) return;
117156  va_start(ap, zFormat);
117157  zSql = sqlite3_vmprintf(zFormat, ap);
117158  va_end(ap);
117159  if( zSql==0 ){
117160    *pRc = SQLITE_NOMEM;
117161  }else{
117162    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
117163    sqlite3_free(zSql);
117164  }
117165}
117166
117167/*
117168** The xDestroy() virtual table method.
117169*/
117170static int fts3DestroyMethod(sqlite3_vtab *pVtab){
117171  Fts3Table *p = (Fts3Table *)pVtab;
117172  int rc = SQLITE_OK;              /* Return code */
117173  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
117174  sqlite3 *db = p->db;             /* Database handle */
117175
117176  /* Drop the shadow tables */
117177  if( p->zContentTbl==0 ){
117178    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
117179  }
117180  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
117181  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
117182  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
117183  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
117184
117185  /* If everything has worked, invoke fts3DisconnectMethod() to free the
117186  ** memory associated with the Fts3Table structure and return SQLITE_OK.
117187  ** Otherwise, return an SQLite error code.
117188  */
117189  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
117190}
117191
117192
117193/*
117194** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
117195** passed as the first argument. This is done as part of the xConnect()
117196** and xCreate() methods.
117197**
117198** If *pRc is non-zero when this function is called, it is a no-op.
117199** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
117200** before returning.
117201*/
117202static void fts3DeclareVtab(int *pRc, Fts3Table *p){
117203  if( *pRc==SQLITE_OK ){
117204    int i;                        /* Iterator variable */
117205    int rc;                       /* Return code */
117206    char *zSql;                   /* SQL statement passed to declare_vtab() */
117207    char *zCols;                  /* List of user defined columns */
117208    const char *zLanguageid;
117209
117210    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
117211    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
117212
117213    /* Create a list of user columns for the virtual table */
117214    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
117215    for(i=1; zCols && i<p->nColumn; i++){
117216      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
117217    }
117218
117219    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
117220    zSql = sqlite3_mprintf(
117221        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
117222        zCols, p->zName, zLanguageid
117223    );
117224    if( !zCols || !zSql ){
117225      rc = SQLITE_NOMEM;
117226    }else{
117227      rc = sqlite3_declare_vtab(p->db, zSql);
117228    }
117229
117230    sqlite3_free(zSql);
117231    sqlite3_free(zCols);
117232    *pRc = rc;
117233  }
117234}
117235
117236/*
117237** Create the backing store tables (%_content, %_segments and %_segdir)
117238** required by the FTS3 table passed as the only argument. This is done
117239** as part of the vtab xCreate() method.
117240**
117241** If the p->bHasDocsize boolean is true (indicating that this is an
117242** FTS4 table, not an FTS3 table) then also create the %_docsize and
117243** %_stat tables required by FTS4.
117244*/
117245static int fts3CreateTables(Fts3Table *p){
117246  int rc = SQLITE_OK;             /* Return code */
117247  int i;                          /* Iterator variable */
117248  sqlite3 *db = p->db;            /* The database connection */
117249
117250  if( p->zContentTbl==0 ){
117251    const char *zLanguageid = p->zLanguageid;
117252    char *zContentCols;           /* Columns of %_content table */
117253
117254    /* Create a list of user columns for the content table */
117255    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
117256    for(i=0; zContentCols && i<p->nColumn; i++){
117257      char *z = p->azColumn[i];
117258      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
117259    }
117260    if( zLanguageid && zContentCols ){
117261      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
117262    }
117263    if( zContentCols==0 ) rc = SQLITE_NOMEM;
117264
117265    /* Create the content table */
117266    fts3DbExec(&rc, db,
117267       "CREATE TABLE %Q.'%q_content'(%s)",
117268       p->zDb, p->zName, zContentCols
117269    );
117270    sqlite3_free(zContentCols);
117271  }
117272
117273  /* Create other tables */
117274  fts3DbExec(&rc, db,
117275      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
117276      p->zDb, p->zName
117277  );
117278  fts3DbExec(&rc, db,
117279      "CREATE TABLE %Q.'%q_segdir'("
117280        "level INTEGER,"
117281        "idx INTEGER,"
117282        "start_block INTEGER,"
117283        "leaves_end_block INTEGER,"
117284        "end_block INTEGER,"
117285        "root BLOB,"
117286        "PRIMARY KEY(level, idx)"
117287      ");",
117288      p->zDb, p->zName
117289  );
117290  if( p->bHasDocsize ){
117291    fts3DbExec(&rc, db,
117292        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
117293        p->zDb, p->zName
117294    );
117295  }
117296  if( p->bHasStat ){
117297    fts3DbExec(&rc, db,
117298        "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
117299        p->zDb, p->zName
117300    );
117301  }
117302  return rc;
117303}
117304
117305/*
117306** Store the current database page-size in bytes in p->nPgsz.
117307**
117308** If *pRc is non-zero when this function is called, it is a no-op.
117309** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
117310** before returning.
117311*/
117312static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
117313  if( *pRc==SQLITE_OK ){
117314    int rc;                       /* Return code */
117315    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
117316    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
117317
117318    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
117319    if( !zSql ){
117320      rc = SQLITE_NOMEM;
117321    }else{
117322      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
117323      if( rc==SQLITE_OK ){
117324        sqlite3_step(pStmt);
117325        p->nPgsz = sqlite3_column_int(pStmt, 0);
117326        rc = sqlite3_finalize(pStmt);
117327      }else if( rc==SQLITE_AUTH ){
117328        p->nPgsz = 1024;
117329        rc = SQLITE_OK;
117330      }
117331    }
117332    assert( p->nPgsz>0 || rc!=SQLITE_OK );
117333    sqlite3_free(zSql);
117334    *pRc = rc;
117335  }
117336}
117337
117338/*
117339** "Special" FTS4 arguments are column specifications of the following form:
117340**
117341**   <key> = <value>
117342**
117343** There may not be whitespace surrounding the "=" character. The <value>
117344** term may be quoted, but the <key> may not.
117345*/
117346static int fts3IsSpecialColumn(
117347  const char *z,
117348  int *pnKey,
117349  char **pzValue
117350){
117351  char *zValue;
117352  const char *zCsr = z;
117353
117354  while( *zCsr!='=' ){
117355    if( *zCsr=='\0' ) return 0;
117356    zCsr++;
117357  }
117358
117359  *pnKey = (int)(zCsr-z);
117360  zValue = sqlite3_mprintf("%s", &zCsr[1]);
117361  if( zValue ){
117362    sqlite3Fts3Dequote(zValue);
117363  }
117364  *pzValue = zValue;
117365  return 1;
117366}
117367
117368/*
117369** Append the output of a printf() style formatting to an existing string.
117370*/
117371static void fts3Appendf(
117372  int *pRc,                       /* IN/OUT: Error code */
117373  char **pz,                      /* IN/OUT: Pointer to string buffer */
117374  const char *zFormat,            /* Printf format string to append */
117375  ...                             /* Arguments for printf format string */
117376){
117377  if( *pRc==SQLITE_OK ){
117378    va_list ap;
117379    char *z;
117380    va_start(ap, zFormat);
117381    z = sqlite3_vmprintf(zFormat, ap);
117382    va_end(ap);
117383    if( z && *pz ){
117384      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
117385      sqlite3_free(z);
117386      z = z2;
117387    }
117388    if( z==0 ) *pRc = SQLITE_NOMEM;
117389    sqlite3_free(*pz);
117390    *pz = z;
117391  }
117392}
117393
117394/*
117395** Return a copy of input string zInput enclosed in double-quotes (") and
117396** with all double quote characters escaped. For example:
117397**
117398**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
117399**
117400** The pointer returned points to memory obtained from sqlite3_malloc(). It
117401** is the callers responsibility to call sqlite3_free() to release this
117402** memory.
117403*/
117404static char *fts3QuoteId(char const *zInput){
117405  int nRet;
117406  char *zRet;
117407  nRet = 2 + (int)strlen(zInput)*2 + 1;
117408  zRet = sqlite3_malloc(nRet);
117409  if( zRet ){
117410    int i;
117411    char *z = zRet;
117412    *(z++) = '"';
117413    for(i=0; zInput[i]; i++){
117414      if( zInput[i]=='"' ) *(z++) = '"';
117415      *(z++) = zInput[i];
117416    }
117417    *(z++) = '"';
117418    *(z++) = '\0';
117419  }
117420  return zRet;
117421}
117422
117423/*
117424** Return a list of comma separated SQL expressions and a FROM clause that
117425** could be used in a SELECT statement such as the following:
117426**
117427**     SELECT <list of expressions> FROM %_content AS x ...
117428**
117429** to return the docid, followed by each column of text data in order
117430** from left to write. If parameter zFunc is not NULL, then instead of
117431** being returned directly each column of text data is passed to an SQL
117432** function named zFunc first. For example, if zFunc is "unzip" and the
117433** table has the three user-defined columns "a", "b", and "c", the following
117434** string is returned:
117435**
117436**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
117437**
117438** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
117439** is the responsibility of the caller to eventually free it.
117440**
117441** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
117442** a NULL pointer is returned). Otherwise, if an OOM error is encountered
117443** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
117444** no error occurs, *pRc is left unmodified.
117445*/
117446static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
117447  char *zRet = 0;
117448  char *zFree = 0;
117449  char *zFunction;
117450  int i;
117451
117452  if( p->zContentTbl==0 ){
117453    if( !zFunc ){
117454      zFunction = "";
117455    }else{
117456      zFree = zFunction = fts3QuoteId(zFunc);
117457    }
117458    fts3Appendf(pRc, &zRet, "docid");
117459    for(i=0; i<p->nColumn; i++){
117460      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
117461    }
117462    if( p->zLanguageid ){
117463      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
117464    }
117465    sqlite3_free(zFree);
117466  }else{
117467    fts3Appendf(pRc, &zRet, "rowid");
117468    for(i=0; i<p->nColumn; i++){
117469      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
117470    }
117471    if( p->zLanguageid ){
117472      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
117473    }
117474  }
117475  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
117476      p->zDb,
117477      (p->zContentTbl ? p->zContentTbl : p->zName),
117478      (p->zContentTbl ? "" : "_content")
117479  );
117480  return zRet;
117481}
117482
117483/*
117484** Return a list of N comma separated question marks, where N is the number
117485** of columns in the %_content table (one for the docid plus one for each
117486** user-defined text column).
117487**
117488** If argument zFunc is not NULL, then all but the first question mark
117489** is preceded by zFunc and an open bracket, and followed by a closed
117490** bracket. For example, if zFunc is "zip" and the FTS3 table has three
117491** user-defined text columns, the following string is returned:
117492**
117493**     "?, zip(?), zip(?), zip(?)"
117494**
117495** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
117496** is the responsibility of the caller to eventually free it.
117497**
117498** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
117499** a NULL pointer is returned). Otherwise, if an OOM error is encountered
117500** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
117501** no error occurs, *pRc is left unmodified.
117502*/
117503static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
117504  char *zRet = 0;
117505  char *zFree = 0;
117506  char *zFunction;
117507  int i;
117508
117509  if( !zFunc ){
117510    zFunction = "";
117511  }else{
117512    zFree = zFunction = fts3QuoteId(zFunc);
117513  }
117514  fts3Appendf(pRc, &zRet, "?");
117515  for(i=0; i<p->nColumn; i++){
117516    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
117517  }
117518  if( p->zLanguageid ){
117519    fts3Appendf(pRc, &zRet, ", ?");
117520  }
117521  sqlite3_free(zFree);
117522  return zRet;
117523}
117524
117525/*
117526** This function interprets the string at (*pp) as a non-negative integer
117527** value. It reads the integer and sets *pnOut to the value read, then
117528** sets *pp to point to the byte immediately following the last byte of
117529** the integer value.
117530**
117531** Only decimal digits ('0'..'9') may be part of an integer value.
117532**
117533** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
117534** the output value undefined. Otherwise SQLITE_OK is returned.
117535**
117536** This function is used when parsing the "prefix=" FTS4 parameter.
117537*/
117538static int fts3GobbleInt(const char **pp, int *pnOut){
117539  const char *p;                  /* Iterator pointer */
117540  int nInt = 0;                   /* Output value */
117541
117542  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
117543    nInt = nInt * 10 + (p[0] - '0');
117544  }
117545  if( p==*pp ) return SQLITE_ERROR;
117546  *pnOut = nInt;
117547  *pp = p;
117548  return SQLITE_OK;
117549}
117550
117551/*
117552** This function is called to allocate an array of Fts3Index structures
117553** representing the indexes maintained by the current FTS table. FTS tables
117554** always maintain the main "terms" index, but may also maintain one or
117555** more "prefix" indexes, depending on the value of the "prefix=" parameter
117556** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
117557**
117558** Argument zParam is passed the value of the "prefix=" option if one was
117559** specified, or NULL otherwise.
117560**
117561** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
117562** the allocated array. *pnIndex is set to the number of elements in the
117563** array. If an error does occur, an SQLite error code is returned.
117564**
117565** Regardless of whether or not an error is returned, it is the responsibility
117566** of the caller to call sqlite3_free() on the output array to free it.
117567*/
117568static int fts3PrefixParameter(
117569  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
117570  int *pnIndex,                   /* OUT: size of *apIndex[] array */
117571  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
117572){
117573  struct Fts3Index *aIndex;       /* Allocated array */
117574  int nIndex = 1;                 /* Number of entries in array */
117575
117576  if( zParam && zParam[0] ){
117577    const char *p;
117578    nIndex++;
117579    for(p=zParam; *p; p++){
117580      if( *p==',' ) nIndex++;
117581    }
117582  }
117583
117584  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
117585  *apIndex = aIndex;
117586  *pnIndex = nIndex;
117587  if( !aIndex ){
117588    return SQLITE_NOMEM;
117589  }
117590
117591  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
117592  if( zParam ){
117593    const char *p = zParam;
117594    int i;
117595    for(i=1; i<nIndex; i++){
117596      int nPrefix;
117597      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
117598      aIndex[i].nPrefix = nPrefix;
117599      p++;
117600    }
117601  }
117602
117603  return SQLITE_OK;
117604}
117605
117606/*
117607** This function is called when initializing an FTS4 table that uses the
117608** content=xxx option. It determines the number of and names of the columns
117609** of the new FTS4 table.
117610**
117611** The third argument passed to this function is the value passed to the
117612** config=xxx option (i.e. "xxx"). This function queries the database for
117613** a table of that name. If found, the output variables are populated
117614** as follows:
117615**
117616**   *pnCol:   Set to the number of columns table xxx has,
117617**
117618**   *pnStr:   Set to the total amount of space required to store a copy
117619**             of each columns name, including the nul-terminator.
117620**
117621**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
117622**             the name of the corresponding column in table xxx. The array
117623**             and its contents are allocated using a single allocation. It
117624**             is the responsibility of the caller to free this allocation
117625**             by eventually passing the *pazCol value to sqlite3_free().
117626**
117627** If the table cannot be found, an error code is returned and the output
117628** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
117629** returned (and the output variables are undefined).
117630*/
117631static int fts3ContentColumns(
117632  sqlite3 *db,                    /* Database handle */
117633  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
117634  const char *zTbl,               /* Name of content table */
117635  const char ***pazCol,           /* OUT: Malloc'd array of column names */
117636  int *pnCol,                     /* OUT: Size of array *pazCol */
117637  int *pnStr                      /* OUT: Bytes of string content */
117638){
117639  int rc = SQLITE_OK;             /* Return code */
117640  char *zSql;                     /* "SELECT *" statement on zTbl */
117641  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
117642
117643  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
117644  if( !zSql ){
117645    rc = SQLITE_NOMEM;
117646  }else{
117647    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
117648  }
117649  sqlite3_free(zSql);
117650
117651  if( rc==SQLITE_OK ){
117652    const char **azCol;           /* Output array */
117653    int nStr = 0;                 /* Size of all column names (incl. 0x00) */
117654    int nCol;                     /* Number of table columns */
117655    int i;                        /* Used to iterate through columns */
117656
117657    /* Loop through the returned columns. Set nStr to the number of bytes of
117658    ** space required to store a copy of each column name, including the
117659    ** nul-terminator byte.  */
117660    nCol = sqlite3_column_count(pStmt);
117661    for(i=0; i<nCol; i++){
117662      const char *zCol = sqlite3_column_name(pStmt, i);
117663      nStr += (int)strlen(zCol) + 1;
117664    }
117665
117666    /* Allocate and populate the array to return. */
117667    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
117668    if( azCol==0 ){
117669      rc = SQLITE_NOMEM;
117670    }else{
117671      char *p = (char *)&azCol[nCol];
117672      for(i=0; i<nCol; i++){
117673        const char *zCol = sqlite3_column_name(pStmt, i);
117674        int n = (int)strlen(zCol)+1;
117675        memcpy(p, zCol, n);
117676        azCol[i] = p;
117677        p += n;
117678      }
117679    }
117680    sqlite3_finalize(pStmt);
117681
117682    /* Set the output variables. */
117683    *pnCol = nCol;
117684    *pnStr = nStr;
117685    *pazCol = azCol;
117686  }
117687
117688  return rc;
117689}
117690
117691/*
117692** This function is the implementation of both the xConnect and xCreate
117693** methods of the FTS3 virtual table.
117694**
117695** The argv[] array contains the following:
117696**
117697**   argv[0]   -> module name  ("fts3" or "fts4")
117698**   argv[1]   -> database name
117699**   argv[2]   -> table name
117700**   argv[...] -> "column name" and other module argument fields.
117701*/
117702static int fts3InitVtab(
117703  int isCreate,                   /* True for xCreate, false for xConnect */
117704  sqlite3 *db,                    /* The SQLite database connection */
117705  void *pAux,                     /* Hash table containing tokenizers */
117706  int argc,                       /* Number of elements in argv array */
117707  const char * const *argv,       /* xCreate/xConnect argument array */
117708  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
117709  char **pzErr                    /* Write any error message here */
117710){
117711  Fts3Hash *pHash = (Fts3Hash *)pAux;
117712  Fts3Table *p = 0;               /* Pointer to allocated vtab */
117713  int rc = SQLITE_OK;             /* Return code */
117714  int i;                          /* Iterator variable */
117715  int nByte;                      /* Size of allocation used for *p */
117716  int iCol;                       /* Column index */
117717  int nString = 0;                /* Bytes required to hold all column names */
117718  int nCol = 0;                   /* Number of columns in the FTS table */
117719  char *zCsr;                     /* Space for holding column names */
117720  int nDb;                        /* Bytes required to hold database name */
117721  int nName;                      /* Bytes required to hold table name */
117722  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
117723  const char **aCol;              /* Array of column names */
117724  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
117725
117726  int nIndex;                     /* Size of aIndex[] array */
117727  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
117728
117729  /* The results of parsing supported FTS4 key=value options: */
117730  int bNoDocsize = 0;             /* True to omit %_docsize table */
117731  int bDescIdx = 0;               /* True to store descending indexes */
117732  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
117733  char *zCompress = 0;            /* compress=? parameter (or NULL) */
117734  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
117735  char *zContent = 0;             /* content=? parameter (or NULL) */
117736  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
117737
117738  assert( strlen(argv[0])==4 );
117739  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
117740       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
117741  );
117742
117743  nDb = (int)strlen(argv[1]) + 1;
117744  nName = (int)strlen(argv[2]) + 1;
117745
117746  aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
117747  if( !aCol ) return SQLITE_NOMEM;
117748  memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
117749
117750  /* Loop through all of the arguments passed by the user to the FTS3/4
117751  ** module (i.e. all the column names and special arguments). This loop
117752  ** does the following:
117753  **
117754  **   + Figures out the number of columns the FTSX table will have, and
117755  **     the number of bytes of space that must be allocated to store copies
117756  **     of the column names.
117757  **
117758  **   + If there is a tokenizer specification included in the arguments,
117759  **     initializes the tokenizer pTokenizer.
117760  */
117761  for(i=3; rc==SQLITE_OK && i<argc; i++){
117762    char const *z = argv[i];
117763    int nKey;
117764    char *zVal;
117765
117766    /* Check if this is a tokenizer specification */
117767    if( !pTokenizer
117768     && strlen(z)>8
117769     && 0==sqlite3_strnicmp(z, "tokenize", 8)
117770     && 0==sqlite3Fts3IsIdChar(z[8])
117771    ){
117772      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
117773    }
117774
117775    /* Check if it is an FTS4 special argument. */
117776    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
117777      struct Fts4Option {
117778        const char *zOpt;
117779        int nOpt;
117780      } aFts4Opt[] = {
117781        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
117782        { "prefix",      6 },     /* 1 -> PREFIX */
117783        { "compress",    8 },     /* 2 -> COMPRESS */
117784        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
117785        { "order",       5 },     /* 4 -> ORDER */
117786        { "content",     7 },     /* 5 -> CONTENT */
117787        { "languageid", 10 }      /* 6 -> LANGUAGEID */
117788      };
117789
117790      int iOpt;
117791      if( !zVal ){
117792        rc = SQLITE_NOMEM;
117793      }else{
117794        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
117795          struct Fts4Option *pOp = &aFts4Opt[iOpt];
117796          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
117797            break;
117798          }
117799        }
117800        if( iOpt==SizeofArray(aFts4Opt) ){
117801          *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
117802          rc = SQLITE_ERROR;
117803        }else{
117804          switch( iOpt ){
117805            case 0:               /* MATCHINFO */
117806              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
117807                *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
117808                rc = SQLITE_ERROR;
117809              }
117810              bNoDocsize = 1;
117811              break;
117812
117813            case 1:               /* PREFIX */
117814              sqlite3_free(zPrefix);
117815              zPrefix = zVal;
117816              zVal = 0;
117817              break;
117818
117819            case 2:               /* COMPRESS */
117820              sqlite3_free(zCompress);
117821              zCompress = zVal;
117822              zVal = 0;
117823              break;
117824
117825            case 3:               /* UNCOMPRESS */
117826              sqlite3_free(zUncompress);
117827              zUncompress = zVal;
117828              zVal = 0;
117829              break;
117830
117831            case 4:               /* ORDER */
117832              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
117833               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
117834              ){
117835                *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
117836                rc = SQLITE_ERROR;
117837              }
117838              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
117839              break;
117840
117841            case 5:              /* CONTENT */
117842              sqlite3_free(zContent);
117843              zContent = zVal;
117844              zVal = 0;
117845              break;
117846
117847            case 6:              /* LANGUAGEID */
117848              assert( iOpt==6 );
117849              sqlite3_free(zLanguageid);
117850              zLanguageid = zVal;
117851              zVal = 0;
117852              break;
117853          }
117854        }
117855        sqlite3_free(zVal);
117856      }
117857    }
117858
117859    /* Otherwise, the argument is a column name. */
117860    else {
117861      nString += (int)(strlen(z) + 1);
117862      aCol[nCol++] = z;
117863    }
117864  }
117865
117866  /* If a content=xxx option was specified, the following:
117867  **
117868  **   1. Ignore any compress= and uncompress= options.
117869  **
117870  **   2. If no column names were specified as part of the CREATE VIRTUAL
117871  **      TABLE statement, use all columns from the content table.
117872  */
117873  if( rc==SQLITE_OK && zContent ){
117874    sqlite3_free(zCompress);
117875    sqlite3_free(zUncompress);
117876    zCompress = 0;
117877    zUncompress = 0;
117878    if( nCol==0 ){
117879      sqlite3_free((void*)aCol);
117880      aCol = 0;
117881      rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
117882
117883      /* If a languageid= option was specified, remove the language id
117884      ** column from the aCol[] array. */
117885      if( rc==SQLITE_OK && zLanguageid ){
117886        int j;
117887        for(j=0; j<nCol; j++){
117888          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
117889            int k;
117890            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
117891            nCol--;
117892            break;
117893          }
117894        }
117895      }
117896    }
117897  }
117898  if( rc!=SQLITE_OK ) goto fts3_init_out;
117899
117900  if( nCol==0 ){
117901    assert( nString==0 );
117902    aCol[0] = "content";
117903    nString = 8;
117904    nCol = 1;
117905  }
117906
117907  if( pTokenizer==0 ){
117908    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
117909    if( rc!=SQLITE_OK ) goto fts3_init_out;
117910  }
117911  assert( pTokenizer );
117912
117913  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
117914  if( rc==SQLITE_ERROR ){
117915    assert( zPrefix );
117916    *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
117917  }
117918  if( rc!=SQLITE_OK ) goto fts3_init_out;
117919
117920  /* Allocate and populate the Fts3Table structure. */
117921  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
117922          nCol * sizeof(char *) +              /* azColumn */
117923          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
117924          nName +                              /* zName */
117925          nDb +                                /* zDb */
117926          nString;                             /* Space for azColumn strings */
117927  p = (Fts3Table*)sqlite3_malloc(nByte);
117928  if( p==0 ){
117929    rc = SQLITE_NOMEM;
117930    goto fts3_init_out;
117931  }
117932  memset(p, 0, nByte);
117933  p->db = db;
117934  p->nColumn = nCol;
117935  p->nPendingData = 0;
117936  p->azColumn = (char **)&p[1];
117937  p->pTokenizer = pTokenizer;
117938  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
117939  p->bHasDocsize = (isFts4 && bNoDocsize==0);
117940  p->bHasStat = isFts4;
117941  p->bDescIdx = bDescIdx;
117942  p->zContentTbl = zContent;
117943  p->zLanguageid = zLanguageid;
117944  zContent = 0;
117945  zLanguageid = 0;
117946  TESTONLY( p->inTransaction = -1 );
117947  TESTONLY( p->mxSavepoint = -1 );
117948
117949  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
117950  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
117951  p->nIndex = nIndex;
117952  for(i=0; i<nIndex; i++){
117953    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
117954  }
117955
117956  /* Fill in the zName and zDb fields of the vtab structure. */
117957  zCsr = (char *)&p->aIndex[nIndex];
117958  p->zName = zCsr;
117959  memcpy(zCsr, argv[2], nName);
117960  zCsr += nName;
117961  p->zDb = zCsr;
117962  memcpy(zCsr, argv[1], nDb);
117963  zCsr += nDb;
117964
117965  /* Fill in the azColumn array */
117966  for(iCol=0; iCol<nCol; iCol++){
117967    char *z;
117968    int n = 0;
117969    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
117970    memcpy(zCsr, z, n);
117971    zCsr[n] = '\0';
117972    sqlite3Fts3Dequote(zCsr);
117973    p->azColumn[iCol] = zCsr;
117974    zCsr += n+1;
117975    assert( zCsr <= &((char *)p)[nByte] );
117976  }
117977
117978  if( (zCompress==0)!=(zUncompress==0) ){
117979    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
117980    rc = SQLITE_ERROR;
117981    *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
117982  }
117983  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
117984  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
117985  if( rc!=SQLITE_OK ) goto fts3_init_out;
117986
117987  /* If this is an xCreate call, create the underlying tables in the
117988  ** database. TODO: For xConnect(), it could verify that said tables exist.
117989  */
117990  if( isCreate ){
117991    rc = fts3CreateTables(p);
117992  }
117993
117994  /* Figure out the page-size for the database. This is required in order to
117995  ** estimate the cost of loading large doclists from the database.  */
117996  fts3DatabasePageSize(&rc, p);
117997  p->nNodeSize = p->nPgsz-35;
117998
117999  /* Declare the table schema to SQLite. */
118000  fts3DeclareVtab(&rc, p);
118001
118002fts3_init_out:
118003  sqlite3_free(zPrefix);
118004  sqlite3_free(aIndex);
118005  sqlite3_free(zCompress);
118006  sqlite3_free(zUncompress);
118007  sqlite3_free(zContent);
118008  sqlite3_free(zLanguageid);
118009  sqlite3_free((void *)aCol);
118010  if( rc!=SQLITE_OK ){
118011    if( p ){
118012      fts3DisconnectMethod((sqlite3_vtab *)p);
118013    }else if( pTokenizer ){
118014      pTokenizer->pModule->xDestroy(pTokenizer);
118015    }
118016  }else{
118017    assert( p->pSegments==0 );
118018    *ppVTab = &p->base;
118019  }
118020  return rc;
118021}
118022
118023/*
118024** The xConnect() and xCreate() methods for the virtual table. All the
118025** work is done in function fts3InitVtab().
118026*/
118027static int fts3ConnectMethod(
118028  sqlite3 *db,                    /* Database connection */
118029  void *pAux,                     /* Pointer to tokenizer hash table */
118030  int argc,                       /* Number of elements in argv array */
118031  const char * const *argv,       /* xCreate/xConnect argument array */
118032  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
118033  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
118034){
118035  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
118036}
118037static int fts3CreateMethod(
118038  sqlite3 *db,                    /* Database connection */
118039  void *pAux,                     /* Pointer to tokenizer hash table */
118040  int argc,                       /* Number of elements in argv array */
118041  const char * const *argv,       /* xCreate/xConnect argument array */
118042  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
118043  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
118044){
118045  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
118046}
118047
118048/*
118049** Implementation of the xBestIndex method for FTS3 tables. There
118050** are three possible strategies, in order of preference:
118051**
118052**   1. Direct lookup by rowid or docid.
118053**   2. Full-text search using a MATCH operator on a non-docid column.
118054**   3. Linear scan of %_content table.
118055*/
118056static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
118057  Fts3Table *p = (Fts3Table *)pVTab;
118058  int i;                          /* Iterator variable */
118059  int iCons = -1;                 /* Index of constraint to use */
118060  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
118061
118062  /* By default use a full table scan. This is an expensive option,
118063  ** so search through the constraints to see if a more efficient
118064  ** strategy is possible.
118065  */
118066  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
118067  pInfo->estimatedCost = 500000;
118068  for(i=0; i<pInfo->nConstraint; i++){
118069    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
118070    if( pCons->usable==0 ) continue;
118071
118072    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
118073    if( iCons<0
118074     && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
118075     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
118076    ){
118077      pInfo->idxNum = FTS3_DOCID_SEARCH;
118078      pInfo->estimatedCost = 1.0;
118079      iCons = i;
118080    }
118081
118082    /* A MATCH constraint. Use a full-text search.
118083    **
118084    ** If there is more than one MATCH constraint available, use the first
118085    ** one encountered. If there is both a MATCH constraint and a direct
118086    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
118087    ** though the rowid/docid lookup is faster than a MATCH query, selecting
118088    ** it would lead to an "unable to use function MATCH in the requested
118089    ** context" error.
118090    */
118091    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
118092     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
118093    ){
118094      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
118095      pInfo->estimatedCost = 2.0;
118096      iCons = i;
118097    }
118098
118099    /* Equality constraint on the langid column */
118100    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
118101     && pCons->iColumn==p->nColumn + 2
118102    ){
118103      iLangidCons = i;
118104    }
118105  }
118106
118107  if( iCons>=0 ){
118108    pInfo->aConstraintUsage[iCons].argvIndex = 1;
118109    pInfo->aConstraintUsage[iCons].omit = 1;
118110  }
118111  if( iLangidCons>=0 ){
118112    pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
118113  }
118114
118115  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
118116  ** docid) order. Both ascending and descending are possible.
118117  */
118118  if( pInfo->nOrderBy==1 ){
118119    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
118120    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
118121      if( pOrder->desc ){
118122        pInfo->idxStr = "DESC";
118123      }else{
118124        pInfo->idxStr = "ASC";
118125      }
118126      pInfo->orderByConsumed = 1;
118127    }
118128  }
118129
118130  assert( p->pSegments==0 );
118131  return SQLITE_OK;
118132}
118133
118134/*
118135** Implementation of xOpen method.
118136*/
118137static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
118138  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
118139
118140  UNUSED_PARAMETER(pVTab);
118141
118142  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
118143  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
118144  ** if the allocation fails, return SQLITE_NOMEM.
118145  */
118146  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
118147  if( !pCsr ){
118148    return SQLITE_NOMEM;
118149  }
118150  memset(pCsr, 0, sizeof(Fts3Cursor));
118151  return SQLITE_OK;
118152}
118153
118154/*
118155** Close the cursor.  For additional information see the documentation
118156** on the xClose method of the virtual table interface.
118157*/
118158static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
118159  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
118160  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
118161  sqlite3_finalize(pCsr->pStmt);
118162  sqlite3Fts3ExprFree(pCsr->pExpr);
118163  sqlite3Fts3FreeDeferredTokens(pCsr);
118164  sqlite3_free(pCsr->aDoclist);
118165  sqlite3_free(pCsr->aMatchinfo);
118166  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
118167  sqlite3_free(pCsr);
118168  return SQLITE_OK;
118169}
118170
118171/*
118172** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
118173** compose and prepare an SQL statement of the form:
118174**
118175**    "SELECT <columns> FROM %_content WHERE rowid = ?"
118176**
118177** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
118178** it. If an error occurs, return an SQLite error code.
118179**
118180** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
118181*/
118182static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
118183  int rc = SQLITE_OK;
118184  if( pCsr->pStmt==0 ){
118185    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
118186    char *zSql;
118187    zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
118188    if( !zSql ) return SQLITE_NOMEM;
118189    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
118190    sqlite3_free(zSql);
118191  }
118192  *ppStmt = pCsr->pStmt;
118193  return rc;
118194}
118195
118196/*
118197** Position the pCsr->pStmt statement so that it is on the row
118198** of the %_content table that contains the last match.  Return
118199** SQLITE_OK on success.
118200*/
118201static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
118202  int rc = SQLITE_OK;
118203  if( pCsr->isRequireSeek ){
118204    sqlite3_stmt *pStmt = 0;
118205
118206    rc = fts3CursorSeekStmt(pCsr, &pStmt);
118207    if( rc==SQLITE_OK ){
118208      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
118209      pCsr->isRequireSeek = 0;
118210      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
118211        return SQLITE_OK;
118212      }else{
118213        rc = sqlite3_reset(pCsr->pStmt);
118214        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
118215          /* If no row was found and no error has occured, then the %_content
118216          ** table is missing a row that is present in the full-text index.
118217          ** The data structures are corrupt.  */
118218          rc = FTS_CORRUPT_VTAB;
118219          pCsr->isEof = 1;
118220        }
118221      }
118222    }
118223  }
118224
118225  if( rc!=SQLITE_OK && pContext ){
118226    sqlite3_result_error_code(pContext, rc);
118227  }
118228  return rc;
118229}
118230
118231/*
118232** This function is used to process a single interior node when searching
118233** a b-tree for a term or term prefix. The node data is passed to this
118234** function via the zNode/nNode parameters. The term to search for is
118235** passed in zTerm/nTerm.
118236**
118237** If piFirst is not NULL, then this function sets *piFirst to the blockid
118238** of the child node that heads the sub-tree that may contain the term.
118239**
118240** If piLast is not NULL, then *piLast is set to the right-most child node
118241** that heads a sub-tree that may contain a term for which zTerm/nTerm is
118242** a prefix.
118243**
118244** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
118245*/
118246static int fts3ScanInteriorNode(
118247  const char *zTerm,              /* Term to select leaves for */
118248  int nTerm,                      /* Size of term zTerm in bytes */
118249  const char *zNode,              /* Buffer containing segment interior node */
118250  int nNode,                      /* Size of buffer at zNode */
118251  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
118252  sqlite3_int64 *piLast           /* OUT: Selected child node */
118253){
118254  int rc = SQLITE_OK;             /* Return code */
118255  const char *zCsr = zNode;       /* Cursor to iterate through node */
118256  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
118257  char *zBuffer = 0;              /* Buffer to load terms into */
118258  int nAlloc = 0;                 /* Size of allocated buffer */
118259  int isFirstTerm = 1;            /* True when processing first term on page */
118260  sqlite3_int64 iChild;           /* Block id of child node to descend to */
118261
118262  /* Skip over the 'height' varint that occurs at the start of every
118263  ** interior node. Then load the blockid of the left-child of the b-tree
118264  ** node into variable iChild.
118265  **
118266  ** Even if the data structure on disk is corrupted, this (reading two
118267  ** varints from the buffer) does not risk an overread. If zNode is a
118268  ** root node, then the buffer comes from a SELECT statement. SQLite does
118269  ** not make this guarantee explicitly, but in practice there are always
118270  ** either more than 20 bytes of allocated space following the nNode bytes of
118271  ** contents, or two zero bytes. Or, if the node is read from the %_segments
118272  ** table, then there are always 20 bytes of zeroed padding following the
118273  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
118274  */
118275  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
118276  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
118277  if( zCsr>zEnd ){
118278    return FTS_CORRUPT_VTAB;
118279  }
118280
118281  while( zCsr<zEnd && (piFirst || piLast) ){
118282    int cmp;                      /* memcmp() result */
118283    int nSuffix;                  /* Size of term suffix */
118284    int nPrefix = 0;              /* Size of term prefix */
118285    int nBuffer;                  /* Total term size */
118286
118287    /* Load the next term on the node into zBuffer. Use realloc() to expand
118288    ** the size of zBuffer if required.  */
118289    if( !isFirstTerm ){
118290      zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
118291    }
118292    isFirstTerm = 0;
118293    zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
118294
118295    if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
118296      rc = FTS_CORRUPT_VTAB;
118297      goto finish_scan;
118298    }
118299    if( nPrefix+nSuffix>nAlloc ){
118300      char *zNew;
118301      nAlloc = (nPrefix+nSuffix) * 2;
118302      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
118303      if( !zNew ){
118304        rc = SQLITE_NOMEM;
118305        goto finish_scan;
118306      }
118307      zBuffer = zNew;
118308    }
118309    assert( zBuffer );
118310    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
118311    nBuffer = nPrefix + nSuffix;
118312    zCsr += nSuffix;
118313
118314    /* Compare the term we are searching for with the term just loaded from
118315    ** the interior node. If the specified term is greater than or equal
118316    ** to the term from the interior node, then all terms on the sub-tree
118317    ** headed by node iChild are smaller than zTerm. No need to search
118318    ** iChild.
118319    **
118320    ** If the interior node term is larger than the specified term, then
118321    ** the tree headed by iChild may contain the specified term.
118322    */
118323    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
118324    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
118325      *piFirst = iChild;
118326      piFirst = 0;
118327    }
118328
118329    if( piLast && cmp<0 ){
118330      *piLast = iChild;
118331      piLast = 0;
118332    }
118333
118334    iChild++;
118335  };
118336
118337  if( piFirst ) *piFirst = iChild;
118338  if( piLast ) *piLast = iChild;
118339
118340 finish_scan:
118341  sqlite3_free(zBuffer);
118342  return rc;
118343}
118344
118345
118346/*
118347** The buffer pointed to by argument zNode (size nNode bytes) contains an
118348** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
118349** contains a term. This function searches the sub-tree headed by the zNode
118350** node for the range of leaf nodes that may contain the specified term
118351** or terms for which the specified term is a prefix.
118352**
118353** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
118354** left-most leaf node in the tree that may contain the specified term.
118355** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
118356** right-most leaf node that may contain a term for which the specified
118357** term is a prefix.
118358**
118359** It is possible that the range of returned leaf nodes does not contain
118360** the specified term or any terms for which it is a prefix. However, if the
118361** segment does contain any such terms, they are stored within the identified
118362** range. Because this function only inspects interior segment nodes (and
118363** never loads leaf nodes into memory), it is not possible to be sure.
118364**
118365** If an error occurs, an error code other than SQLITE_OK is returned.
118366*/
118367static int fts3SelectLeaf(
118368  Fts3Table *p,                   /* Virtual table handle */
118369  const char *zTerm,              /* Term to select leaves for */
118370  int nTerm,                      /* Size of term zTerm in bytes */
118371  const char *zNode,              /* Buffer containing segment interior node */
118372  int nNode,                      /* Size of buffer at zNode */
118373  sqlite3_int64 *piLeaf,          /* Selected leaf node */
118374  sqlite3_int64 *piLeaf2          /* Selected leaf node */
118375){
118376  int rc;                         /* Return code */
118377  int iHeight;                    /* Height of this node in tree */
118378
118379  assert( piLeaf || piLeaf2 );
118380
118381  sqlite3Fts3GetVarint32(zNode, &iHeight);
118382  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
118383  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
118384
118385  if( rc==SQLITE_OK && iHeight>1 ){
118386    char *zBlob = 0;              /* Blob read from %_segments table */
118387    int nBlob;                    /* Size of zBlob in bytes */
118388
118389    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
118390      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
118391      if( rc==SQLITE_OK ){
118392        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
118393      }
118394      sqlite3_free(zBlob);
118395      piLeaf = 0;
118396      zBlob = 0;
118397    }
118398
118399    if( rc==SQLITE_OK ){
118400      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
118401    }
118402    if( rc==SQLITE_OK ){
118403      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
118404    }
118405    sqlite3_free(zBlob);
118406  }
118407
118408  return rc;
118409}
118410
118411/*
118412** This function is used to create delta-encoded serialized lists of FTS3
118413** varints. Each call to this function appends a single varint to a list.
118414*/
118415static void fts3PutDeltaVarint(
118416  char **pp,                      /* IN/OUT: Output pointer */
118417  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
118418  sqlite3_int64 iVal              /* Write this value to the list */
118419){
118420  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
118421  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
118422  *piPrev = iVal;
118423}
118424
118425/*
118426** When this function is called, *ppPoslist is assumed to point to the
118427** start of a position-list. After it returns, *ppPoslist points to the
118428** first byte after the position-list.
118429**
118430** A position list is list of positions (delta encoded) and columns for
118431** a single document record of a doclist.  So, in other words, this
118432** routine advances *ppPoslist so that it points to the next docid in
118433** the doclist, or to the first byte past the end of the doclist.
118434**
118435** If pp is not NULL, then the contents of the position list are copied
118436** to *pp. *pp is set to point to the first byte past the last byte copied
118437** before this function returns.
118438*/
118439static void fts3PoslistCopy(char **pp, char **ppPoslist){
118440  char *pEnd = *ppPoslist;
118441  char c = 0;
118442
118443  /* The end of a position list is marked by a zero encoded as an FTS3
118444  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
118445  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
118446  ** of some other, multi-byte, value.
118447  **
118448  ** The following while-loop moves pEnd to point to the first byte that is not
118449  ** immediately preceded by a byte with the 0x80 bit set. Then increments
118450  ** pEnd once more so that it points to the byte immediately following the
118451  ** last byte in the position-list.
118452  */
118453  while( *pEnd | c ){
118454    c = *pEnd++ & 0x80;
118455    testcase( c!=0 && (*pEnd)==0 );
118456  }
118457  pEnd++;  /* Advance past the POS_END terminator byte */
118458
118459  if( pp ){
118460    int n = (int)(pEnd - *ppPoslist);
118461    char *p = *pp;
118462    memcpy(p, *ppPoslist, n);
118463    p += n;
118464    *pp = p;
118465  }
118466  *ppPoslist = pEnd;
118467}
118468
118469/*
118470** When this function is called, *ppPoslist is assumed to point to the
118471** start of a column-list. After it returns, *ppPoslist points to the
118472** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
118473**
118474** A column-list is list of delta-encoded positions for a single column
118475** within a single document within a doclist.
118476**
118477** The column-list is terminated either by a POS_COLUMN varint (1) or
118478** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
118479** the POS_COLUMN or POS_END that terminates the column-list.
118480**
118481** If pp is not NULL, then the contents of the column-list are copied
118482** to *pp. *pp is set to point to the first byte past the last byte copied
118483** before this function returns.  The POS_COLUMN or POS_END terminator
118484** is not copied into *pp.
118485*/
118486static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
118487  char *pEnd = *ppPoslist;
118488  char c = 0;
118489
118490  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
118491  ** not part of a multi-byte varint.
118492  */
118493  while( 0xFE & (*pEnd | c) ){
118494    c = *pEnd++ & 0x80;
118495    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
118496  }
118497  if( pp ){
118498    int n = (int)(pEnd - *ppPoslist);
118499    char *p = *pp;
118500    memcpy(p, *ppPoslist, n);
118501    p += n;
118502    *pp = p;
118503  }
118504  *ppPoslist = pEnd;
118505}
118506
118507/*
118508** Value used to signify the end of an position-list. This is safe because
118509** it is not possible to have a document with 2^31 terms.
118510*/
118511#define POSITION_LIST_END 0x7fffffff
118512
118513/*
118514** This function is used to help parse position-lists. When this function is
118515** called, *pp may point to the start of the next varint in the position-list
118516** being parsed, or it may point to 1 byte past the end of the position-list
118517** (in which case **pp will be a terminator bytes POS_END (0) or
118518** (1)).
118519**
118520** If *pp points past the end of the current position-list, set *pi to
118521** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
118522** increment the current value of *pi by the value read, and set *pp to
118523** point to the next value before returning.
118524**
118525** Before calling this routine *pi must be initialized to the value of
118526** the previous position, or zero if we are reading the first position
118527** in the position-list.  Because positions are delta-encoded, the value
118528** of the previous position is needed in order to compute the value of
118529** the next position.
118530*/
118531static void fts3ReadNextPos(
118532  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
118533  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
118534){
118535  if( (**pp)&0xFE ){
118536    fts3GetDeltaVarint(pp, pi);
118537    *pi -= 2;
118538  }else{
118539    *pi = POSITION_LIST_END;
118540  }
118541}
118542
118543/*
118544** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
118545** the value of iCol encoded as a varint to *pp.   This will start a new
118546** column list.
118547**
118548** Set *pp to point to the byte just after the last byte written before
118549** returning (do not modify it if iCol==0). Return the total number of bytes
118550** written (0 if iCol==0).
118551*/
118552static int fts3PutColNumber(char **pp, int iCol){
118553  int n = 0;                      /* Number of bytes written */
118554  if( iCol ){
118555    char *p = *pp;                /* Output pointer */
118556    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
118557    *p = 0x01;
118558    *pp = &p[n];
118559  }
118560  return n;
118561}
118562
118563/*
118564** Compute the union of two position lists.  The output written
118565** into *pp contains all positions of both *pp1 and *pp2 in sorted
118566** order and with any duplicates removed.  All pointers are
118567** updated appropriately.   The caller is responsible for insuring
118568** that there is enough space in *pp to hold the complete output.
118569*/
118570static void fts3PoslistMerge(
118571  char **pp,                      /* Output buffer */
118572  char **pp1,                     /* Left input list */
118573  char **pp2                      /* Right input list */
118574){
118575  char *p = *pp;
118576  char *p1 = *pp1;
118577  char *p2 = *pp2;
118578
118579  while( *p1 || *p2 ){
118580    int iCol1;         /* The current column index in pp1 */
118581    int iCol2;         /* The current column index in pp2 */
118582
118583    if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
118584    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
118585    else iCol1 = 0;
118586
118587    if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
118588    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
118589    else iCol2 = 0;
118590
118591    if( iCol1==iCol2 ){
118592      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
118593      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
118594      sqlite3_int64 iPrev = 0;
118595      int n = fts3PutColNumber(&p, iCol1);
118596      p1 += n;
118597      p2 += n;
118598
118599      /* At this point, both p1 and p2 point to the start of column-lists
118600      ** for the same column (the column with index iCol1 and iCol2).
118601      ** A column-list is a list of non-negative delta-encoded varints, each
118602      ** incremented by 2 before being stored. Each list is terminated by a
118603      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
118604      ** and writes the results to buffer p. p is left pointing to the byte
118605      ** after the list written. No terminator (POS_END or POS_COLUMN) is
118606      ** written to the output.
118607      */
118608      fts3GetDeltaVarint(&p1, &i1);
118609      fts3GetDeltaVarint(&p2, &i2);
118610      do {
118611        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
118612        iPrev -= 2;
118613        if( i1==i2 ){
118614          fts3ReadNextPos(&p1, &i1);
118615          fts3ReadNextPos(&p2, &i2);
118616        }else if( i1<i2 ){
118617          fts3ReadNextPos(&p1, &i1);
118618        }else{
118619          fts3ReadNextPos(&p2, &i2);
118620        }
118621      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
118622    }else if( iCol1<iCol2 ){
118623      p1 += fts3PutColNumber(&p, iCol1);
118624      fts3ColumnlistCopy(&p, &p1);
118625    }else{
118626      p2 += fts3PutColNumber(&p, iCol2);
118627      fts3ColumnlistCopy(&p, &p2);
118628    }
118629  }
118630
118631  *p++ = POS_END;
118632  *pp = p;
118633  *pp1 = p1 + 1;
118634  *pp2 = p2 + 1;
118635}
118636
118637/*
118638** This function is used to merge two position lists into one. When it is
118639** called, *pp1 and *pp2 must both point to position lists. A position-list is
118640** the part of a doclist that follows each document id. For example, if a row
118641** contains:
118642**
118643**     'a b c'|'x y z'|'a b b a'
118644**
118645** Then the position list for this row for token 'b' would consist of:
118646**
118647**     0x02 0x01 0x02 0x03 0x03 0x00
118648**
118649** When this function returns, both *pp1 and *pp2 are left pointing to the
118650** byte following the 0x00 terminator of their respective position lists.
118651**
118652** If isSaveLeft is 0, an entry is added to the output position list for
118653** each position in *pp2 for which there exists one or more positions in
118654** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
118655** when the *pp1 token appears before the *pp2 token, but not more than nToken
118656** slots before it.
118657**
118658** e.g. nToken==1 searches for adjacent positions.
118659*/
118660static int fts3PoslistPhraseMerge(
118661  char **pp,                      /* IN/OUT: Preallocated output buffer */
118662  int nToken,                     /* Maximum difference in token positions */
118663  int isSaveLeft,                 /* Save the left position */
118664  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
118665  char **pp1,                     /* IN/OUT: Left input list */
118666  char **pp2                      /* IN/OUT: Right input list */
118667){
118668  char *p = *pp;
118669  char *p1 = *pp1;
118670  char *p2 = *pp2;
118671  int iCol1 = 0;
118672  int iCol2 = 0;
118673
118674  /* Never set both isSaveLeft and isExact for the same invocation. */
118675  assert( isSaveLeft==0 || isExact==0 );
118676
118677  assert( p!=0 && *p1!=0 && *p2!=0 );
118678  if( *p1==POS_COLUMN ){
118679    p1++;
118680    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
118681  }
118682  if( *p2==POS_COLUMN ){
118683    p2++;
118684    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
118685  }
118686
118687  while( 1 ){
118688    if( iCol1==iCol2 ){
118689      char *pSave = p;
118690      sqlite3_int64 iPrev = 0;
118691      sqlite3_int64 iPos1 = 0;
118692      sqlite3_int64 iPos2 = 0;
118693
118694      if( iCol1 ){
118695        *p++ = POS_COLUMN;
118696        p += sqlite3Fts3PutVarint(p, iCol1);
118697      }
118698
118699      assert( *p1!=POS_END && *p1!=POS_COLUMN );
118700      assert( *p2!=POS_END && *p2!=POS_COLUMN );
118701      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
118702      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
118703
118704      while( 1 ){
118705        if( iPos2==iPos1+nToken
118706         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
118707        ){
118708          sqlite3_int64 iSave;
118709          iSave = isSaveLeft ? iPos1 : iPos2;
118710          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
118711          pSave = 0;
118712          assert( p );
118713        }
118714        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
118715          if( (*p2&0xFE)==0 ) break;
118716          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
118717        }else{
118718          if( (*p1&0xFE)==0 ) break;
118719          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
118720        }
118721      }
118722
118723      if( pSave ){
118724        assert( pp && p );
118725        p = pSave;
118726      }
118727
118728      fts3ColumnlistCopy(0, &p1);
118729      fts3ColumnlistCopy(0, &p2);
118730      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
118731      if( 0==*p1 || 0==*p2 ) break;
118732
118733      p1++;
118734      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
118735      p2++;
118736      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
118737    }
118738
118739    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
118740    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
118741    ** end of the position list, or the 0x01 that precedes the next
118742    ** column-number in the position list.
118743    */
118744    else if( iCol1<iCol2 ){
118745      fts3ColumnlistCopy(0, &p1);
118746      if( 0==*p1 ) break;
118747      p1++;
118748      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
118749    }else{
118750      fts3ColumnlistCopy(0, &p2);
118751      if( 0==*p2 ) break;
118752      p2++;
118753      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
118754    }
118755  }
118756
118757  fts3PoslistCopy(0, &p2);
118758  fts3PoslistCopy(0, &p1);
118759  *pp1 = p1;
118760  *pp2 = p2;
118761  if( *pp==p ){
118762    return 0;
118763  }
118764  *p++ = 0x00;
118765  *pp = p;
118766  return 1;
118767}
118768
118769/*
118770** Merge two position-lists as required by the NEAR operator. The argument
118771** position lists correspond to the left and right phrases of an expression
118772** like:
118773**
118774**     "phrase 1" NEAR "phrase number 2"
118775**
118776** Position list *pp1 corresponds to the left-hand side of the NEAR
118777** expression and *pp2 to the right. As usual, the indexes in the position
118778** lists are the offsets of the last token in each phrase (tokens "1" and "2"
118779** in the example above).
118780**
118781** The output position list - written to *pp - is a copy of *pp2 with those
118782** entries that are not sufficiently NEAR entries in *pp1 removed.
118783*/
118784static int fts3PoslistNearMerge(
118785  char **pp,                      /* Output buffer */
118786  char *aTmp,                     /* Temporary buffer space */
118787  int nRight,                     /* Maximum difference in token positions */
118788  int nLeft,                      /* Maximum difference in token positions */
118789  char **pp1,                     /* IN/OUT: Left input list */
118790  char **pp2                      /* IN/OUT: Right input list */
118791){
118792  char *p1 = *pp1;
118793  char *p2 = *pp2;
118794
118795  char *pTmp1 = aTmp;
118796  char *pTmp2;
118797  char *aTmp2;
118798  int res = 1;
118799
118800  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
118801  aTmp2 = pTmp2 = pTmp1;
118802  *pp1 = p1;
118803  *pp2 = p2;
118804  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
118805  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
118806    fts3PoslistMerge(pp, &aTmp, &aTmp2);
118807  }else if( pTmp1!=aTmp ){
118808    fts3PoslistCopy(pp, &aTmp);
118809  }else if( pTmp2!=aTmp2 ){
118810    fts3PoslistCopy(pp, &aTmp2);
118811  }else{
118812    res = 0;
118813  }
118814
118815  return res;
118816}
118817
118818/*
118819** An instance of this function is used to merge together the (potentially
118820** large number of) doclists for each term that matches a prefix query.
118821** See function fts3TermSelectMerge() for details.
118822*/
118823typedef struct TermSelect TermSelect;
118824struct TermSelect {
118825  char *aaOutput[16];             /* Malloc'd output buffers */
118826  int anOutput[16];               /* Size each output buffer in bytes */
118827};
118828
118829/*
118830** This function is used to read a single varint from a buffer. Parameter
118831** pEnd points 1 byte past the end of the buffer. When this function is
118832** called, if *pp points to pEnd or greater, then the end of the buffer
118833** has been reached. In this case *pp is set to 0 and the function returns.
118834**
118835** If *pp does not point to or past pEnd, then a single varint is read
118836** from *pp. *pp is then set to point 1 byte past the end of the read varint.
118837**
118838** If bDescIdx is false, the value read is added to *pVal before returning.
118839** If it is true, the value read is subtracted from *pVal before this
118840** function returns.
118841*/
118842static void fts3GetDeltaVarint3(
118843  char **pp,                      /* IN/OUT: Point to read varint from */
118844  char *pEnd,                     /* End of buffer */
118845  int bDescIdx,                   /* True if docids are descending */
118846  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
118847){
118848  if( *pp>=pEnd ){
118849    *pp = 0;
118850  }else{
118851    sqlite3_int64 iVal;
118852    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
118853    if( bDescIdx ){
118854      *pVal -= iVal;
118855    }else{
118856      *pVal += iVal;
118857    }
118858  }
118859}
118860
118861/*
118862** This function is used to write a single varint to a buffer. The varint
118863** is written to *pp. Before returning, *pp is set to point 1 byte past the
118864** end of the value written.
118865**
118866** If *pbFirst is zero when this function is called, the value written to
118867** the buffer is that of parameter iVal.
118868**
118869** If *pbFirst is non-zero when this function is called, then the value
118870** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
118871** (if bDescIdx is non-zero).
118872**
118873** Before returning, this function always sets *pbFirst to 1 and *piPrev
118874** to the value of parameter iVal.
118875*/
118876static void fts3PutDeltaVarint3(
118877  char **pp,                      /* IN/OUT: Output pointer */
118878  int bDescIdx,                   /* True for descending docids */
118879  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
118880  int *pbFirst,                   /* IN/OUT: True after first int written */
118881  sqlite3_int64 iVal              /* Write this value to the list */
118882){
118883  sqlite3_int64 iWrite;
118884  if( bDescIdx==0 || *pbFirst==0 ){
118885    iWrite = iVal - *piPrev;
118886  }else{
118887    iWrite = *piPrev - iVal;
118888  }
118889  assert( *pbFirst || *piPrev==0 );
118890  assert( *pbFirst==0 || iWrite>0 );
118891  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
118892  *piPrev = iVal;
118893  *pbFirst = 1;
118894}
118895
118896
118897/*
118898** This macro is used by various functions that merge doclists. The two
118899** arguments are 64-bit docid values. If the value of the stack variable
118900** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
118901** Otherwise, (i2-i1).
118902**
118903** Using this makes it easier to write code that can merge doclists that are
118904** sorted in either ascending or descending order.
118905*/
118906#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
118907
118908/*
118909** This function does an "OR" merge of two doclists (output contains all
118910** positions contained in either argument doclist). If the docids in the
118911** input doclists are sorted in ascending order, parameter bDescDoclist
118912** should be false. If they are sorted in ascending order, it should be
118913** passed a non-zero value.
118914**
118915** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
118916** containing the output doclist and SQLITE_OK is returned. In this case
118917** *pnOut is set to the number of bytes in the output doclist.
118918**
118919** If an error occurs, an SQLite error code is returned. The output values
118920** are undefined in this case.
118921*/
118922static int fts3DoclistOrMerge(
118923  int bDescDoclist,               /* True if arguments are desc */
118924  char *a1, int n1,               /* First doclist */
118925  char *a2, int n2,               /* Second doclist */
118926  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
118927){
118928  sqlite3_int64 i1 = 0;
118929  sqlite3_int64 i2 = 0;
118930  sqlite3_int64 iPrev = 0;
118931  char *pEnd1 = &a1[n1];
118932  char *pEnd2 = &a2[n2];
118933  char *p1 = a1;
118934  char *p2 = a2;
118935  char *p;
118936  char *aOut;
118937  int bFirstOut = 0;
118938
118939  *paOut = 0;
118940  *pnOut = 0;
118941
118942  /* Allocate space for the output. Both the input and output doclists
118943  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
118944  ** then the first docid in each list is simply encoded as a varint. For
118945  ** each subsequent docid, the varint stored is the difference between the
118946  ** current and previous docid (a positive number - since the list is in
118947  ** ascending order).
118948  **
118949  ** The first docid written to the output is therefore encoded using the
118950  ** same number of bytes as it is in whichever of the input lists it is
118951  ** read from. And each subsequent docid read from the same input list
118952  ** consumes either the same or less bytes as it did in the input (since
118953  ** the difference between it and the previous value in the output must
118954  ** be a positive value less than or equal to the delta value read from
118955  ** the input list). The same argument applies to all but the first docid
118956  ** read from the 'other' list. And to the contents of all position lists
118957  ** that will be copied and merged from the input to the output.
118958  **
118959  ** However, if the first docid copied to the output is a negative number,
118960  ** then the encoding of the first docid from the 'other' input list may
118961  ** be larger in the output than it was in the input (since the delta value
118962  ** may be a larger positive integer than the actual docid).
118963  **
118964  ** The space required to store the output is therefore the sum of the
118965  ** sizes of the two inputs, plus enough space for exactly one of the input
118966  ** docids to grow.
118967  **
118968  ** A symetric argument may be made if the doclists are in descending
118969  ** order.
118970  */
118971  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
118972  if( !aOut ) return SQLITE_NOMEM;
118973
118974  p = aOut;
118975  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
118976  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
118977  while( p1 || p2 ){
118978    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
118979
118980    if( p2 && p1 && iDiff==0 ){
118981      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118982      fts3PoslistMerge(&p, &p1, &p2);
118983      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118984      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118985    }else if( !p2 || (p1 && iDiff<0) ){
118986      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118987      fts3PoslistCopy(&p, &p1);
118988      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118989    }else{
118990      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
118991      fts3PoslistCopy(&p, &p2);
118992      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118993    }
118994  }
118995
118996  *paOut = aOut;
118997  *pnOut = (int)(p-aOut);
118998  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
118999  return SQLITE_OK;
119000}
119001
119002/*
119003** This function does a "phrase" merge of two doclists. In a phrase merge,
119004** the output contains a copy of each position from the right-hand input
119005** doclist for which there is a position in the left-hand input doclist
119006** exactly nDist tokens before it.
119007**
119008** If the docids in the input doclists are sorted in ascending order,
119009** parameter bDescDoclist should be false. If they are sorted in ascending
119010** order, it should be passed a non-zero value.
119011**
119012** The right-hand input doclist is overwritten by this function.
119013*/
119014static void fts3DoclistPhraseMerge(
119015  int bDescDoclist,               /* True if arguments are desc */
119016  int nDist,                      /* Distance from left to right (1=adjacent) */
119017  char *aLeft, int nLeft,         /* Left doclist */
119018  char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
119019){
119020  sqlite3_int64 i1 = 0;
119021  sqlite3_int64 i2 = 0;
119022  sqlite3_int64 iPrev = 0;
119023  char *pEnd1 = &aLeft[nLeft];
119024  char *pEnd2 = &aRight[*pnRight];
119025  char *p1 = aLeft;
119026  char *p2 = aRight;
119027  char *p;
119028  int bFirstOut = 0;
119029  char *aOut = aRight;
119030
119031  assert( nDist>0 );
119032
119033  p = aOut;
119034  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
119035  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
119036
119037  while( p1 && p2 ){
119038    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
119039    if( iDiff==0 ){
119040      char *pSave = p;
119041      sqlite3_int64 iPrevSave = iPrev;
119042      int bFirstOutSave = bFirstOut;
119043
119044      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
119045      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
119046        p = pSave;
119047        iPrev = iPrevSave;
119048        bFirstOut = bFirstOutSave;
119049      }
119050      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
119051      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
119052    }else if( iDiff<0 ){
119053      fts3PoslistCopy(0, &p1);
119054      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
119055    }else{
119056      fts3PoslistCopy(0, &p2);
119057      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
119058    }
119059  }
119060
119061  *pnRight = (int)(p - aOut);
119062}
119063
119064/*
119065** Argument pList points to a position list nList bytes in size. This
119066** function checks to see if the position list contains any entries for
119067** a token in position 0 (of any column). If so, it writes argument iDelta
119068** to the output buffer pOut, followed by a position list consisting only
119069** of the entries from pList at position 0, and terminated by an 0x00 byte.
119070** The value returned is the number of bytes written to pOut (if any).
119071*/
119072SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
119073  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
119074  char *pList,                    /* Position list (no 0x00 term) */
119075  int nList,                      /* Size of pList in bytes */
119076  char *pOut                      /* Write output here */
119077){
119078  int nOut = 0;
119079  int bWritten = 0;               /* True once iDelta has been written */
119080  char *p = pList;
119081  char *pEnd = &pList[nList];
119082
119083  if( *p!=0x01 ){
119084    if( *p==0x02 ){
119085      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
119086      pOut[nOut++] = 0x02;
119087      bWritten = 1;
119088    }
119089    fts3ColumnlistCopy(0, &p);
119090  }
119091
119092  while( p<pEnd && *p==0x01 ){
119093    sqlite3_int64 iCol;
119094    p++;
119095    p += sqlite3Fts3GetVarint(p, &iCol);
119096    if( *p==0x02 ){
119097      if( bWritten==0 ){
119098        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
119099        bWritten = 1;
119100      }
119101      pOut[nOut++] = 0x01;
119102      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
119103      pOut[nOut++] = 0x02;
119104    }
119105    fts3ColumnlistCopy(0, &p);
119106  }
119107  if( bWritten ){
119108    pOut[nOut++] = 0x00;
119109  }
119110
119111  return nOut;
119112}
119113
119114
119115/*
119116** Merge all doclists in the TermSelect.aaOutput[] array into a single
119117** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
119118** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
119119**
119120** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
119121** the responsibility of the caller to free any doclists left in the
119122** TermSelect.aaOutput[] array.
119123*/
119124static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
119125  char *aOut = 0;
119126  int nOut = 0;
119127  int i;
119128
119129  /* Loop through the doclists in the aaOutput[] array. Merge them all
119130  ** into a single doclist.
119131  */
119132  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
119133    if( pTS->aaOutput[i] ){
119134      if( !aOut ){
119135        aOut = pTS->aaOutput[i];
119136        nOut = pTS->anOutput[i];
119137        pTS->aaOutput[i] = 0;
119138      }else{
119139        int nNew;
119140        char *aNew;
119141
119142        int rc = fts3DoclistOrMerge(p->bDescIdx,
119143            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
119144        );
119145        if( rc!=SQLITE_OK ){
119146          sqlite3_free(aOut);
119147          return rc;
119148        }
119149
119150        sqlite3_free(pTS->aaOutput[i]);
119151        sqlite3_free(aOut);
119152        pTS->aaOutput[i] = 0;
119153        aOut = aNew;
119154        nOut = nNew;
119155      }
119156    }
119157  }
119158
119159  pTS->aaOutput[0] = aOut;
119160  pTS->anOutput[0] = nOut;
119161  return SQLITE_OK;
119162}
119163
119164/*
119165** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
119166** as the first argument. The merge is an "OR" merge (see function
119167** fts3DoclistOrMerge() for details).
119168**
119169** This function is called with the doclist for each term that matches
119170** a queried prefix. It merges all these doclists into one, the doclist
119171** for the specified prefix. Since there can be a very large number of
119172** doclists to merge, the merging is done pair-wise using the TermSelect
119173** object.
119174**
119175** This function returns SQLITE_OK if the merge is successful, or an
119176** SQLite error code (SQLITE_NOMEM) if an error occurs.
119177*/
119178static int fts3TermSelectMerge(
119179  Fts3Table *p,                   /* FTS table handle */
119180  TermSelect *pTS,                /* TermSelect object to merge into */
119181  char *aDoclist,                 /* Pointer to doclist */
119182  int nDoclist                    /* Size of aDoclist in bytes */
119183){
119184  if( pTS->aaOutput[0]==0 ){
119185    /* If this is the first term selected, copy the doclist to the output
119186    ** buffer using memcpy(). */
119187    pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
119188    pTS->anOutput[0] = nDoclist;
119189    if( pTS->aaOutput[0] ){
119190      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
119191    }else{
119192      return SQLITE_NOMEM;
119193    }
119194  }else{
119195    char *aMerge = aDoclist;
119196    int nMerge = nDoclist;
119197    int iOut;
119198
119199    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
119200      if( pTS->aaOutput[iOut]==0 ){
119201        assert( iOut>0 );
119202        pTS->aaOutput[iOut] = aMerge;
119203        pTS->anOutput[iOut] = nMerge;
119204        break;
119205      }else{
119206        char *aNew;
119207        int nNew;
119208
119209        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
119210            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
119211        );
119212        if( rc!=SQLITE_OK ){
119213          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
119214          return rc;
119215        }
119216
119217        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
119218        sqlite3_free(pTS->aaOutput[iOut]);
119219        pTS->aaOutput[iOut] = 0;
119220
119221        aMerge = aNew;
119222        nMerge = nNew;
119223        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
119224          pTS->aaOutput[iOut] = aMerge;
119225          pTS->anOutput[iOut] = nMerge;
119226        }
119227      }
119228    }
119229  }
119230  return SQLITE_OK;
119231}
119232
119233/*
119234** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
119235*/
119236static int fts3SegReaderCursorAppend(
119237  Fts3MultiSegReader *pCsr,
119238  Fts3SegReader *pNew
119239){
119240  if( (pCsr->nSegment%16)==0 ){
119241    Fts3SegReader **apNew;
119242    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
119243    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
119244    if( !apNew ){
119245      sqlite3Fts3SegReaderFree(pNew);
119246      return SQLITE_NOMEM;
119247    }
119248    pCsr->apSegment = apNew;
119249  }
119250  pCsr->apSegment[pCsr->nSegment++] = pNew;
119251  return SQLITE_OK;
119252}
119253
119254/*
119255** Add seg-reader objects to the Fts3MultiSegReader object passed as the
119256** 8th argument.
119257**
119258** This function returns SQLITE_OK if successful, or an SQLite error code
119259** otherwise.
119260*/
119261static int fts3SegReaderCursor(
119262  Fts3Table *p,                   /* FTS3 table handle */
119263  int iLangid,                    /* Language id */
119264  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
119265  int iLevel,                     /* Level of segments to scan */
119266  const char *zTerm,              /* Term to query for */
119267  int nTerm,                      /* Size of zTerm in bytes */
119268  int isPrefix,                   /* True for a prefix search */
119269  int isScan,                     /* True to scan from zTerm to EOF */
119270  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
119271){
119272  int rc = SQLITE_OK;             /* Error code */
119273  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
119274  int rc2;                        /* Result of sqlite3_reset() */
119275
119276  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
119277  ** for the pending-terms. If this is a scan, then this call must be being
119278  ** made by an fts4aux module, not an FTS table. In this case calling
119279  ** Fts3SegReaderPending might segfault, as the data structures used by
119280  ** fts4aux are not completely populated. So it's easiest to filter these
119281  ** calls out here.  */
119282  if( iLevel<0 && p->aIndex ){
119283    Fts3SegReader *pSeg = 0;
119284    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
119285    if( rc==SQLITE_OK && pSeg ){
119286      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
119287    }
119288  }
119289
119290  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
119291    if( rc==SQLITE_OK ){
119292      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
119293    }
119294
119295    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
119296      Fts3SegReader *pSeg = 0;
119297
119298      /* Read the values returned by the SELECT into local variables. */
119299      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
119300      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
119301      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
119302      int nRoot = sqlite3_column_bytes(pStmt, 4);
119303      char const *zRoot = sqlite3_column_blob(pStmt, 4);
119304
119305      /* If zTerm is not NULL, and this segment is not stored entirely on its
119306      ** root node, the range of leaves scanned can be reduced. Do this. */
119307      if( iStartBlock && zTerm ){
119308        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
119309        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
119310        if( rc!=SQLITE_OK ) goto finished;
119311        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
119312      }
119313
119314      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
119315          (isPrefix==0 && isScan==0),
119316          iStartBlock, iLeavesEndBlock,
119317          iEndBlock, zRoot, nRoot, &pSeg
119318      );
119319      if( rc!=SQLITE_OK ) goto finished;
119320      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
119321    }
119322  }
119323
119324 finished:
119325  rc2 = sqlite3_reset(pStmt);
119326  if( rc==SQLITE_DONE ) rc = rc2;
119327
119328  return rc;
119329}
119330
119331/*
119332** Set up a cursor object for iterating through a full-text index or a
119333** single level therein.
119334*/
119335SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
119336  Fts3Table *p,                   /* FTS3 table handle */
119337  int iLangid,
119338  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
119339  int iLevel,                     /* Level of segments to scan */
119340  const char *zTerm,              /* Term to query for */
119341  int nTerm,                      /* Size of zTerm in bytes */
119342  int isPrefix,                   /* True for a prefix search */
119343  int isScan,                     /* True to scan from zTerm to EOF */
119344  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
119345){
119346  assert( iIndex>=0 && iIndex<p->nIndex );
119347  assert( iLevel==FTS3_SEGCURSOR_ALL
119348      ||  iLevel==FTS3_SEGCURSOR_PENDING
119349      ||  iLevel>=0
119350  );
119351  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
119352  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
119353  assert( isPrefix==0 || isScan==0 );
119354
119355  /* "isScan" is only set to true by the ft4aux module, an ordinary
119356  ** full-text tables. */
119357  assert( isScan==0 || p->aIndex==0 );
119358
119359  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
119360
119361  return fts3SegReaderCursor(
119362      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
119363  );
119364}
119365
119366/*
119367** In addition to its current configuration, have the Fts3MultiSegReader
119368** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
119369**
119370** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
119371*/
119372static int fts3SegReaderCursorAddZero(
119373  Fts3Table *p,                   /* FTS virtual table handle */
119374  int iLangid,
119375  const char *zTerm,              /* Term to scan doclist of */
119376  int nTerm,                      /* Number of bytes in zTerm */
119377  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
119378){
119379  return fts3SegReaderCursor(p,
119380      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
119381  );
119382}
119383
119384/*
119385** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
119386** if isPrefix is true, to scan the doclist for all terms for which
119387** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
119388** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
119389** an SQLite error code.
119390**
119391** It is the responsibility of the caller to free this object by eventually
119392** passing it to fts3SegReaderCursorFree()
119393**
119394** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
119395** Output parameter *ppSegcsr is set to 0 if an error occurs.
119396*/
119397static int fts3TermSegReaderCursor(
119398  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
119399  const char *zTerm,              /* Term to query for */
119400  int nTerm,                      /* Size of zTerm in bytes */
119401  int isPrefix,                   /* True for a prefix search */
119402  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
119403){
119404  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
119405  int rc = SQLITE_NOMEM;          /* Return code */
119406
119407  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
119408  if( pSegcsr ){
119409    int i;
119410    int bFound = 0;               /* True once an index has been found */
119411    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
119412
119413    if( isPrefix ){
119414      for(i=1; bFound==0 && i<p->nIndex; i++){
119415        if( p->aIndex[i].nPrefix==nTerm ){
119416          bFound = 1;
119417          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
119418              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
119419          );
119420          pSegcsr->bLookup = 1;
119421        }
119422      }
119423
119424      for(i=1; bFound==0 && i<p->nIndex; i++){
119425        if( p->aIndex[i].nPrefix==nTerm+1 ){
119426          bFound = 1;
119427          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
119428              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
119429          );
119430          if( rc==SQLITE_OK ){
119431            rc = fts3SegReaderCursorAddZero(
119432                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
119433            );
119434          }
119435        }
119436      }
119437    }
119438
119439    if( bFound==0 ){
119440      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
119441          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
119442      );
119443      pSegcsr->bLookup = !isPrefix;
119444    }
119445  }
119446
119447  *ppSegcsr = pSegcsr;
119448  return rc;
119449}
119450
119451/*
119452** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
119453*/
119454static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
119455  sqlite3Fts3SegReaderFinish(pSegcsr);
119456  sqlite3_free(pSegcsr);
119457}
119458
119459/*
119460** This function retreives the doclist for the specified term (or term
119461** prefix) from the database.
119462*/
119463static int fts3TermSelect(
119464  Fts3Table *p,                   /* Virtual table handle */
119465  Fts3PhraseToken *pTok,          /* Token to query for */
119466  int iColumn,                    /* Column to query (or -ve for all columns) */
119467  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
119468  char **ppOut                    /* OUT: Malloced result buffer */
119469){
119470  int rc;                         /* Return code */
119471  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
119472  TermSelect tsc;                 /* Object for pair-wise doclist merging */
119473  Fts3SegFilter filter;           /* Segment term filter configuration */
119474
119475  pSegcsr = pTok->pSegcsr;
119476  memset(&tsc, 0, sizeof(TermSelect));
119477
119478  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
119479        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
119480        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
119481        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
119482  filter.iCol = iColumn;
119483  filter.zTerm = pTok->z;
119484  filter.nTerm = pTok->n;
119485
119486  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
119487  while( SQLITE_OK==rc
119488      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
119489  ){
119490    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
119491  }
119492
119493  if( rc==SQLITE_OK ){
119494    rc = fts3TermSelectFinishMerge(p, &tsc);
119495  }
119496  if( rc==SQLITE_OK ){
119497    *ppOut = tsc.aaOutput[0];
119498    *pnOut = tsc.anOutput[0];
119499  }else{
119500    int i;
119501    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
119502      sqlite3_free(tsc.aaOutput[i]);
119503    }
119504  }
119505
119506  fts3SegReaderCursorFree(pSegcsr);
119507  pTok->pSegcsr = 0;
119508  return rc;
119509}
119510
119511/*
119512** This function counts the total number of docids in the doclist stored
119513** in buffer aList[], size nList bytes.
119514**
119515** If the isPoslist argument is true, then it is assumed that the doclist
119516** contains a position-list following each docid. Otherwise, it is assumed
119517** that the doclist is simply a list of docids stored as delta encoded
119518** varints.
119519*/
119520static int fts3DoclistCountDocids(char *aList, int nList){
119521  int nDoc = 0;                   /* Return value */
119522  if( aList ){
119523    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
119524    char *p = aList;              /* Cursor */
119525    while( p<aEnd ){
119526      nDoc++;
119527      while( (*p++)&0x80 );     /* Skip docid varint */
119528      fts3PoslistCopy(0, &p);   /* Skip over position list */
119529    }
119530  }
119531
119532  return nDoc;
119533}
119534
119535/*
119536** Advance the cursor to the next row in the %_content table that
119537** matches the search criteria.  For a MATCH search, this will be
119538** the next row that matches. For a full-table scan, this will be
119539** simply the next row in the %_content table.  For a docid lookup,
119540** this routine simply sets the EOF flag.
119541**
119542** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
119543** even if we reach end-of-file.  The fts3EofMethod() will be called
119544** subsequently to determine whether or not an EOF was hit.
119545*/
119546static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
119547  int rc;
119548  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
119549  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
119550    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
119551      pCsr->isEof = 1;
119552      rc = sqlite3_reset(pCsr->pStmt);
119553    }else{
119554      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
119555      rc = SQLITE_OK;
119556    }
119557  }else{
119558    rc = fts3EvalNext((Fts3Cursor *)pCursor);
119559  }
119560  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119561  return rc;
119562}
119563
119564/*
119565** This is the xFilter interface for the virtual table.  See
119566** the virtual table xFilter method documentation for additional
119567** information.
119568**
119569** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
119570** the %_content table.
119571**
119572** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
119573** in the %_content table.
119574**
119575** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
119576** column on the left-hand side of the MATCH operator is column
119577** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
119578** side of the MATCH operator.
119579*/
119580static int fts3FilterMethod(
119581  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
119582  int idxNum,                     /* Strategy index */
119583  const char *idxStr,             /* Unused */
119584  int nVal,                       /* Number of elements in apVal */
119585  sqlite3_value **apVal           /* Arguments for the indexing scheme */
119586){
119587  int rc;
119588  char *zSql;                     /* SQL statement used to access %_content */
119589  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
119590  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
119591
119592  UNUSED_PARAMETER(idxStr);
119593  UNUSED_PARAMETER(nVal);
119594
119595  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
119596  assert( nVal==0 || nVal==1 || nVal==2 );
119597  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
119598  assert( p->pSegments==0 );
119599
119600  /* In case the cursor has been used before, clear it now. */
119601  sqlite3_finalize(pCsr->pStmt);
119602  sqlite3_free(pCsr->aDoclist);
119603  sqlite3Fts3ExprFree(pCsr->pExpr);
119604  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
119605
119606  if( idxStr ){
119607    pCsr->bDesc = (idxStr[0]=='D');
119608  }else{
119609    pCsr->bDesc = p->bDescIdx;
119610  }
119611  pCsr->eSearch = (i16)idxNum;
119612
119613  if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
119614    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
119615    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
119616
119617    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
119618      return SQLITE_NOMEM;
119619    }
119620
119621    pCsr->iLangid = 0;
119622    if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
119623
119624    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
119625        p->azColumn, p->bHasStat, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
119626    );
119627    if( rc!=SQLITE_OK ){
119628      if( rc==SQLITE_ERROR ){
119629        static const char *zErr = "malformed MATCH expression: [%s]";
119630        p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
119631      }
119632      return rc;
119633    }
119634
119635    rc = sqlite3Fts3ReadLock(p);
119636    if( rc!=SQLITE_OK ) return rc;
119637
119638    rc = fts3EvalStart(pCsr);
119639
119640    sqlite3Fts3SegmentsClose(p);
119641    if( rc!=SQLITE_OK ) return rc;
119642    pCsr->pNextId = pCsr->aDoclist;
119643    pCsr->iPrevId = 0;
119644  }
119645
119646  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
119647  ** statement loops through all rows of the %_content table. For a
119648  ** full-text query or docid lookup, the statement retrieves a single
119649  ** row by docid.
119650  */
119651  if( idxNum==FTS3_FULLSCAN_SEARCH ){
119652    zSql = sqlite3_mprintf(
119653        "SELECT %s ORDER BY rowid %s",
119654        p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
119655    );
119656    if( zSql ){
119657      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
119658      sqlite3_free(zSql);
119659    }else{
119660      rc = SQLITE_NOMEM;
119661    }
119662  }else if( idxNum==FTS3_DOCID_SEARCH ){
119663    rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
119664    if( rc==SQLITE_OK ){
119665      rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
119666    }
119667  }
119668  if( rc!=SQLITE_OK ) return rc;
119669
119670  return fts3NextMethod(pCursor);
119671}
119672
119673/*
119674** This is the xEof method of the virtual table. SQLite calls this
119675** routine to find out if it has reached the end of a result set.
119676*/
119677static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
119678  return ((Fts3Cursor *)pCursor)->isEof;
119679}
119680
119681/*
119682** This is the xRowid method. The SQLite core calls this routine to
119683** retrieve the rowid for the current row of the result set. fts3
119684** exposes %_content.docid as the rowid for the virtual table. The
119685** rowid should be written to *pRowid.
119686*/
119687static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
119688  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
119689  *pRowid = pCsr->iPrevId;
119690  return SQLITE_OK;
119691}
119692
119693/*
119694** This is the xColumn method, called by SQLite to request a value from
119695** the row that the supplied cursor currently points to.
119696**
119697** If:
119698**
119699**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
119700**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
119701**   (iCol == p->nColumn+1) -> Docid column
119702**   (iCol == p->nColumn+2) -> Langid column
119703*/
119704static int fts3ColumnMethod(
119705  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
119706  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
119707  int iCol                        /* Index of column to read value from */
119708){
119709  int rc = SQLITE_OK;             /* Return Code */
119710  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
119711  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
119712
119713  /* The column value supplied by SQLite must be in range. */
119714  assert( iCol>=0 && iCol<=p->nColumn+2 );
119715
119716  if( iCol==p->nColumn+1 ){
119717    /* This call is a request for the "docid" column. Since "docid" is an
119718    ** alias for "rowid", use the xRowid() method to obtain the value.
119719    */
119720    sqlite3_result_int64(pCtx, pCsr->iPrevId);
119721  }else if( iCol==p->nColumn ){
119722    /* The extra column whose name is the same as the table.
119723    ** Return a blob which is a pointer to the cursor.  */
119724    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
119725  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
119726    sqlite3_result_int64(pCtx, pCsr->iLangid);
119727  }else{
119728    /* The requested column is either a user column (one that contains
119729    ** indexed data), or the language-id column.  */
119730    rc = fts3CursorSeek(0, pCsr);
119731
119732    if( rc==SQLITE_OK ){
119733      if( iCol==p->nColumn+2 ){
119734        int iLangid = 0;
119735        if( p->zLanguageid ){
119736          iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
119737        }
119738        sqlite3_result_int(pCtx, iLangid);
119739      }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
119740        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
119741      }
119742    }
119743  }
119744
119745  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119746  return rc;
119747}
119748
119749/*
119750** This function is the implementation of the xUpdate callback used by
119751** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
119752** inserted, updated or deleted.
119753*/
119754static int fts3UpdateMethod(
119755  sqlite3_vtab *pVtab,            /* Virtual table handle */
119756  int nArg,                       /* Size of argument array */
119757  sqlite3_value **apVal,          /* Array of arguments */
119758  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
119759){
119760  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
119761}
119762
119763/*
119764** Implementation of xSync() method. Flush the contents of the pending-terms
119765** hash-table to the database.
119766*/
119767static int fts3SyncMethod(sqlite3_vtab *pVtab){
119768  int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
119769  sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
119770  return rc;
119771}
119772
119773/*
119774** Implementation of xBegin() method. This is a no-op.
119775*/
119776static int fts3BeginMethod(sqlite3_vtab *pVtab){
119777  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119778  UNUSED_PARAMETER(pVtab);
119779  assert( p->pSegments==0 );
119780  assert( p->nPendingData==0 );
119781  assert( p->inTransaction!=1 );
119782  TESTONLY( p->inTransaction = 1 );
119783  TESTONLY( p->mxSavepoint = -1; );
119784  return SQLITE_OK;
119785}
119786
119787/*
119788** Implementation of xCommit() method. This is a no-op. The contents of
119789** the pending-terms hash-table have already been flushed into the database
119790** by fts3SyncMethod().
119791*/
119792static int fts3CommitMethod(sqlite3_vtab *pVtab){
119793  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119794  UNUSED_PARAMETER(pVtab);
119795  assert( p->nPendingData==0 );
119796  assert( p->inTransaction!=0 );
119797  assert( p->pSegments==0 );
119798  TESTONLY( p->inTransaction = 0 );
119799  TESTONLY( p->mxSavepoint = -1; );
119800  return SQLITE_OK;
119801}
119802
119803/*
119804** Implementation of xRollback(). Discard the contents of the pending-terms
119805** hash-table. Any changes made to the database are reverted by SQLite.
119806*/
119807static int fts3RollbackMethod(sqlite3_vtab *pVtab){
119808  Fts3Table *p = (Fts3Table*)pVtab;
119809  sqlite3Fts3PendingTermsClear(p);
119810  assert( p->inTransaction!=0 );
119811  TESTONLY( p->inTransaction = 0 );
119812  TESTONLY( p->mxSavepoint = -1; );
119813  return SQLITE_OK;
119814}
119815
119816/*
119817** When called, *ppPoslist must point to the byte immediately following the
119818** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
119819** moves *ppPoslist so that it instead points to the first byte of the
119820** same position list.
119821*/
119822static void fts3ReversePoslist(char *pStart, char **ppPoslist){
119823  char *p = &(*ppPoslist)[-2];
119824  char c = 0;
119825
119826  while( p>pStart && (c=*p--)==0 );
119827  while( p>pStart && (*p & 0x80) | c ){
119828    c = *p--;
119829  }
119830  if( p>pStart ){ p = &p[2]; }
119831  while( *p++&0x80 );
119832  *ppPoslist = p;
119833}
119834
119835/*
119836** Helper function used by the implementation of the overloaded snippet(),
119837** offsets() and optimize() SQL functions.
119838**
119839** If the value passed as the third argument is a blob of size
119840** sizeof(Fts3Cursor*), then the blob contents are copied to the
119841** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
119842** message is written to context pContext and SQLITE_ERROR returned. The
119843** string passed via zFunc is used as part of the error message.
119844*/
119845static int fts3FunctionArg(
119846  sqlite3_context *pContext,      /* SQL function call context */
119847  const char *zFunc,              /* Function name */
119848  sqlite3_value *pVal,            /* argv[0] passed to function */
119849  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
119850){
119851  Fts3Cursor *pRet;
119852  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
119853   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
119854  ){
119855    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
119856    sqlite3_result_error(pContext, zErr, -1);
119857    sqlite3_free(zErr);
119858    return SQLITE_ERROR;
119859  }
119860  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
119861  *ppCsr = pRet;
119862  return SQLITE_OK;
119863}
119864
119865/*
119866** Implementation of the snippet() function for FTS3
119867*/
119868static void fts3SnippetFunc(
119869  sqlite3_context *pContext,      /* SQLite function call context */
119870  int nVal,                       /* Size of apVal[] array */
119871  sqlite3_value **apVal           /* Array of arguments */
119872){
119873  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119874  const char *zStart = "<b>";
119875  const char *zEnd = "</b>";
119876  const char *zEllipsis = "<b>...</b>";
119877  int iCol = -1;
119878  int nToken = 15;                /* Default number of tokens in snippet */
119879
119880  /* There must be at least one argument passed to this function (otherwise
119881  ** the non-overloaded version would have been called instead of this one).
119882  */
119883  assert( nVal>=1 );
119884
119885  if( nVal>6 ){
119886    sqlite3_result_error(pContext,
119887        "wrong number of arguments to function snippet()", -1);
119888    return;
119889  }
119890  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
119891
119892  switch( nVal ){
119893    case 6: nToken = sqlite3_value_int(apVal[5]);
119894    case 5: iCol = sqlite3_value_int(apVal[4]);
119895    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
119896    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
119897    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
119898  }
119899  if( !zEllipsis || !zEnd || !zStart ){
119900    sqlite3_result_error_nomem(pContext);
119901  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
119902    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
119903  }
119904}
119905
119906/*
119907** Implementation of the offsets() function for FTS3
119908*/
119909static void fts3OffsetsFunc(
119910  sqlite3_context *pContext,      /* SQLite function call context */
119911  int nVal,                       /* Size of argument array */
119912  sqlite3_value **apVal           /* Array of arguments */
119913){
119914  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119915
119916  UNUSED_PARAMETER(nVal);
119917
119918  assert( nVal==1 );
119919  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
119920  assert( pCsr );
119921  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
119922    sqlite3Fts3Offsets(pContext, pCsr);
119923  }
119924}
119925
119926/*
119927** Implementation of the special optimize() function for FTS3. This
119928** function merges all segments in the database to a single segment.
119929** Example usage is:
119930**
119931**   SELECT optimize(t) FROM t LIMIT 1;
119932**
119933** where 't' is the name of an FTS3 table.
119934*/
119935static void fts3OptimizeFunc(
119936  sqlite3_context *pContext,      /* SQLite function call context */
119937  int nVal,                       /* Size of argument array */
119938  sqlite3_value **apVal           /* Array of arguments */
119939){
119940  int rc;                         /* Return code */
119941  Fts3Table *p;                   /* Virtual table handle */
119942  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
119943
119944  UNUSED_PARAMETER(nVal);
119945
119946  assert( nVal==1 );
119947  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
119948  p = (Fts3Table *)pCursor->base.pVtab;
119949  assert( p );
119950
119951  rc = sqlite3Fts3Optimize(p);
119952
119953  switch( rc ){
119954    case SQLITE_OK:
119955      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
119956      break;
119957    case SQLITE_DONE:
119958      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
119959      break;
119960    default:
119961      sqlite3_result_error_code(pContext, rc);
119962      break;
119963  }
119964}
119965
119966/*
119967** Implementation of the matchinfo() function for FTS3
119968*/
119969static void fts3MatchinfoFunc(
119970  sqlite3_context *pContext,      /* SQLite function call context */
119971  int nVal,                       /* Size of argument array */
119972  sqlite3_value **apVal           /* Array of arguments */
119973){
119974  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119975  assert( nVal==1 || nVal==2 );
119976  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
119977    const char *zArg = 0;
119978    if( nVal>1 ){
119979      zArg = (const char *)sqlite3_value_text(apVal[1]);
119980    }
119981    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
119982  }
119983}
119984
119985/*
119986** This routine implements the xFindFunction method for the FTS3
119987** virtual table.
119988*/
119989static int fts3FindFunctionMethod(
119990  sqlite3_vtab *pVtab,            /* Virtual table handle */
119991  int nArg,                       /* Number of SQL function arguments */
119992  const char *zName,              /* Name of SQL function */
119993  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
119994  void **ppArg                    /* Unused */
119995){
119996  struct Overloaded {
119997    const char *zName;
119998    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
119999  } aOverload[] = {
120000    { "snippet", fts3SnippetFunc },
120001    { "offsets", fts3OffsetsFunc },
120002    { "optimize", fts3OptimizeFunc },
120003    { "matchinfo", fts3MatchinfoFunc },
120004  };
120005  int i;                          /* Iterator variable */
120006
120007  UNUSED_PARAMETER(pVtab);
120008  UNUSED_PARAMETER(nArg);
120009  UNUSED_PARAMETER(ppArg);
120010
120011  for(i=0; i<SizeofArray(aOverload); i++){
120012    if( strcmp(zName, aOverload[i].zName)==0 ){
120013      *pxFunc = aOverload[i].xFunc;
120014      return 1;
120015    }
120016  }
120017
120018  /* No function of the specified name was found. Return 0. */
120019  return 0;
120020}
120021
120022/*
120023** Implementation of FTS3 xRename method. Rename an fts3 table.
120024*/
120025static int fts3RenameMethod(
120026  sqlite3_vtab *pVtab,            /* Virtual table handle */
120027  const char *zName               /* New name of table */
120028){
120029  Fts3Table *p = (Fts3Table *)pVtab;
120030  sqlite3 *db = p->db;            /* Database connection */
120031  int rc;                         /* Return Code */
120032
120033  /* As it happens, the pending terms table is always empty here. This is
120034  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
120035  ** always opens a savepoint transaction. And the xSavepoint() method
120036  ** flushes the pending terms table. But leave the (no-op) call to
120037  ** PendingTermsFlush() in in case that changes.
120038  */
120039  assert( p->nPendingData==0 );
120040  rc = sqlite3Fts3PendingTermsFlush(p);
120041
120042  if( p->zContentTbl==0 ){
120043    fts3DbExec(&rc, db,
120044      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
120045      p->zDb, p->zName, zName
120046    );
120047  }
120048
120049  if( p->bHasDocsize ){
120050    fts3DbExec(&rc, db,
120051      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
120052      p->zDb, p->zName, zName
120053    );
120054  }
120055  if( p->bHasStat ){
120056    fts3DbExec(&rc, db,
120057      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
120058      p->zDb, p->zName, zName
120059    );
120060  }
120061  fts3DbExec(&rc, db,
120062    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
120063    p->zDb, p->zName, zName
120064  );
120065  fts3DbExec(&rc, db,
120066    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
120067    p->zDb, p->zName, zName
120068  );
120069  return rc;
120070}
120071
120072/*
120073** The xSavepoint() method.
120074**
120075** Flush the contents of the pending-terms table to disk.
120076*/
120077static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
120078  UNUSED_PARAMETER(iSavepoint);
120079  assert( ((Fts3Table *)pVtab)->inTransaction );
120080  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
120081  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
120082  return fts3SyncMethod(pVtab);
120083}
120084
120085/*
120086** The xRelease() method.
120087**
120088** This is a no-op.
120089*/
120090static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
120091  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
120092  UNUSED_PARAMETER(iSavepoint);
120093  UNUSED_PARAMETER(pVtab);
120094  assert( p->inTransaction );
120095  assert( p->mxSavepoint >= iSavepoint );
120096  TESTONLY( p->mxSavepoint = iSavepoint-1 );
120097  return SQLITE_OK;
120098}
120099
120100/*
120101** The xRollbackTo() method.
120102**
120103** Discard the contents of the pending terms table.
120104*/
120105static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
120106  Fts3Table *p = (Fts3Table*)pVtab;
120107  UNUSED_PARAMETER(iSavepoint);
120108  assert( p->inTransaction );
120109  assert( p->mxSavepoint >= iSavepoint );
120110  TESTONLY( p->mxSavepoint = iSavepoint );
120111  sqlite3Fts3PendingTermsClear(p);
120112  return SQLITE_OK;
120113}
120114
120115static const sqlite3_module fts3Module = {
120116  /* iVersion      */ 2,
120117  /* xCreate       */ fts3CreateMethod,
120118  /* xConnect      */ fts3ConnectMethod,
120119  /* xBestIndex    */ fts3BestIndexMethod,
120120  /* xDisconnect   */ fts3DisconnectMethod,
120121  /* xDestroy      */ fts3DestroyMethod,
120122  /* xOpen         */ fts3OpenMethod,
120123  /* xClose        */ fts3CloseMethod,
120124  /* xFilter       */ fts3FilterMethod,
120125  /* xNext         */ fts3NextMethod,
120126  /* xEof          */ fts3EofMethod,
120127  /* xColumn       */ fts3ColumnMethod,
120128  /* xRowid        */ fts3RowidMethod,
120129  /* xUpdate       */ fts3UpdateMethod,
120130  /* xBegin        */ fts3BeginMethod,
120131  /* xSync         */ fts3SyncMethod,
120132  /* xCommit       */ fts3CommitMethod,
120133  /* xRollback     */ fts3RollbackMethod,
120134  /* xFindFunction */ fts3FindFunctionMethod,
120135  /* xRename */       fts3RenameMethod,
120136  /* xSavepoint    */ fts3SavepointMethod,
120137  /* xRelease      */ fts3ReleaseMethod,
120138  /* xRollbackTo   */ fts3RollbackToMethod,
120139};
120140
120141/*
120142** This function is registered as the module destructor (called when an
120143** FTS3 enabled database connection is closed). It frees the memory
120144** allocated for the tokenizer hash table.
120145*/
120146static void hashDestroy(void *p){
120147  Fts3Hash *pHash = (Fts3Hash *)p;
120148  sqlite3Fts3HashClear(pHash);
120149  sqlite3_free(pHash);
120150}
120151
120152/*
120153** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
120154** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
120155** respectively. The following three forward declarations are for functions
120156** declared in these files used to retrieve the respective implementations.
120157**
120158** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
120159** to by the argument to point to the "simple" tokenizer implementation.
120160** And so on.
120161*/
120162SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
120163SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
120164#ifdef SQLITE_ENABLE_ICU
120165SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
120166#endif
120167
120168/*
120169** Initialise the fts3 extension. If this extension is built as part
120170** of the sqlite library, then this function is called directly by
120171** SQLite. If fts3 is built as a dynamically loadable extension, this
120172** function is called by the sqlite3_extension_init() entry point.
120173*/
120174SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs){ // Android Change
120175  int rc = SQLITE_OK;
120176  Fts3Hash *pHash = 0;
120177  const sqlite3_tokenizer_module *pSimple = 0;
120178  const sqlite3_tokenizer_module *pPorter = 0;
120179
120180#ifdef SQLITE_ENABLE_ICU
120181  const sqlite3_tokenizer_module *pIcu = 0;
120182  sqlite3Fts3IcuTokenizerModule(&pIcu);
120183#endif
120184
120185#ifdef SQLITE_TEST
120186  rc = sqlite3Fts3InitTerm(db);
120187  if( rc!=SQLITE_OK ) return rc;
120188#endif
120189
120190  rc = sqlite3Fts3InitAux(db);
120191  if( rc!=SQLITE_OK ) return rc;
120192
120193  sqlite3Fts3SimpleTokenizerModule(&pSimple);
120194  sqlite3Fts3PorterTokenizerModule(&pPorter);
120195
120196  /* Allocate and initialise the hash-table used to store tokenizers. */
120197  pHash = sqlite3_malloc(sizeof(Fts3Hash));
120198  if( !pHash ){
120199    rc = SQLITE_NOMEM;
120200  }else{
120201    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
120202  }
120203
120204  /* Load the built-in tokenizers into the hash table */
120205  if( rc==SQLITE_OK ){
120206    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
120207     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
120208#ifdef SQLITE_ENABLE_ICU
120209     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
120210#endif
120211    ){
120212      rc = SQLITE_NOMEM;
120213    }
120214  }
120215
120216#ifdef SQLITE_TEST
120217  if( rc==SQLITE_OK ){
120218    rc = sqlite3Fts3ExprInitTestInterface(db);
120219  }
120220#endif
120221
120222  /* Create the virtual table wrapper around the hash-table and overload
120223  ** the two scalar functions. If this is successful, register the
120224  ** module with sqlite.
120225  */
120226  if( SQLITE_OK==rc
120227   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
120228   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
120229   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
120230   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
120231   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
120232   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
120233  ){
120234    rc = sqlite3_create_module_v2(
120235        // Begin Android change
120236        // Also register as fts1 and fts2
120237        db, registerAs, &fts3Module, (void *)pHash, hashDestroy
120238        // End Android change
120239    );
120240    if( rc==SQLITE_OK ){
120241      rc = sqlite3_create_module_v2(
120242          db, "fts4", &fts3Module, (void *)pHash, 0
120243      );
120244    }
120245    return rc;
120246  }
120247
120248  /* An error has occurred. Delete the hash table and return the error code. */
120249  assert( rc!=SQLITE_OK );
120250  if( pHash ){
120251    sqlite3Fts3HashClear(pHash);
120252    sqlite3_free(pHash);
120253  }
120254  return rc;
120255}
120256
120257/*
120258** Allocate an Fts3MultiSegReader for each token in the expression headed
120259** by pExpr.
120260**
120261** An Fts3SegReader object is a cursor that can seek or scan a range of
120262** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
120263** Fts3SegReader objects internally to provide an interface to seek or scan
120264** within the union of all segments of a b-tree. Hence the name.
120265**
120266** If the allocated Fts3MultiSegReader just seeks to a single entry in a
120267** segment b-tree (if the term is not a prefix or it is a prefix for which
120268** there exists prefix b-tree of the right length) then it may be traversed
120269** and merged incrementally. Otherwise, it has to be merged into an in-memory
120270** doclist and then traversed.
120271*/
120272static void fts3EvalAllocateReaders(
120273  Fts3Cursor *pCsr,               /* FTS cursor handle */
120274  Fts3Expr *pExpr,                /* Allocate readers for this expression */
120275  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
120276  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
120277  int *pRc                        /* IN/OUT: Error code */
120278){
120279  if( pExpr && SQLITE_OK==*pRc ){
120280    if( pExpr->eType==FTSQUERY_PHRASE ){
120281      int i;
120282      int nToken = pExpr->pPhrase->nToken;
120283      *pnToken += nToken;
120284      for(i=0; i<nToken; i++){
120285        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
120286        int rc = fts3TermSegReaderCursor(pCsr,
120287            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
120288        );
120289        if( rc!=SQLITE_OK ){
120290          *pRc = rc;
120291          return;
120292        }
120293      }
120294      assert( pExpr->pPhrase->iDoclistToken==0 );
120295      pExpr->pPhrase->iDoclistToken = -1;
120296    }else{
120297      *pnOr += (pExpr->eType==FTSQUERY_OR);
120298      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
120299      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
120300    }
120301  }
120302}
120303
120304/*
120305** Arguments pList/nList contain the doclist for token iToken of phrase p.
120306** It is merged into the main doclist stored in p->doclist.aAll/nAll.
120307**
120308** This function assumes that pList points to a buffer allocated using
120309** sqlite3_malloc(). This function takes responsibility for eventually
120310** freeing the buffer.
120311*/
120312static void fts3EvalPhraseMergeToken(
120313  Fts3Table *pTab,                /* FTS Table pointer */
120314  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
120315  int iToken,                     /* Token pList/nList corresponds to */
120316  char *pList,                    /* Pointer to doclist */
120317  int nList                       /* Number of bytes in pList */
120318){
120319  assert( iToken!=p->iDoclistToken );
120320
120321  if( pList==0 ){
120322    sqlite3_free(p->doclist.aAll);
120323    p->doclist.aAll = 0;
120324    p->doclist.nAll = 0;
120325  }
120326
120327  else if( p->iDoclistToken<0 ){
120328    p->doclist.aAll = pList;
120329    p->doclist.nAll = nList;
120330  }
120331
120332  else if( p->doclist.aAll==0 ){
120333    sqlite3_free(pList);
120334  }
120335
120336  else {
120337    char *pLeft;
120338    char *pRight;
120339    int nLeft;
120340    int nRight;
120341    int nDiff;
120342
120343    if( p->iDoclistToken<iToken ){
120344      pLeft = p->doclist.aAll;
120345      nLeft = p->doclist.nAll;
120346      pRight = pList;
120347      nRight = nList;
120348      nDiff = iToken - p->iDoclistToken;
120349    }else{
120350      pRight = p->doclist.aAll;
120351      nRight = p->doclist.nAll;
120352      pLeft = pList;
120353      nLeft = nList;
120354      nDiff = p->iDoclistToken - iToken;
120355    }
120356
120357    fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
120358    sqlite3_free(pLeft);
120359    p->doclist.aAll = pRight;
120360    p->doclist.nAll = nRight;
120361  }
120362
120363  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
120364}
120365
120366/*
120367** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
120368** does not take deferred tokens into account.
120369**
120370** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120371*/
120372static int fts3EvalPhraseLoad(
120373  Fts3Cursor *pCsr,               /* FTS Cursor handle */
120374  Fts3Phrase *p                   /* Phrase object */
120375){
120376  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120377  int iToken;
120378  int rc = SQLITE_OK;
120379
120380  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
120381    Fts3PhraseToken *pToken = &p->aToken[iToken];
120382    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
120383
120384    if( pToken->pSegcsr ){
120385      int nThis = 0;
120386      char *pThis = 0;
120387      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
120388      if( rc==SQLITE_OK ){
120389        fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
120390      }
120391    }
120392    assert( pToken->pSegcsr==0 );
120393  }
120394
120395  return rc;
120396}
120397
120398/*
120399** This function is called on each phrase after the position lists for
120400** any deferred tokens have been loaded into memory. It updates the phrases
120401** current position list to include only those positions that are really
120402** instances of the phrase (after considering deferred tokens). If this
120403** means that the phrase does not appear in the current row, doclist.pList
120404** and doclist.nList are both zeroed.
120405**
120406** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120407*/
120408static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
120409  int iToken;                     /* Used to iterate through phrase tokens */
120410  char *aPoslist = 0;             /* Position list for deferred tokens */
120411  int nPoslist = 0;               /* Number of bytes in aPoslist */
120412  int iPrev = -1;                 /* Token number of previous deferred token */
120413
120414  assert( pPhrase->doclist.bFreeList==0 );
120415
120416  for(iToken=0; iToken<pPhrase->nToken; iToken++){
120417    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
120418    Fts3DeferredToken *pDeferred = pToken->pDeferred;
120419
120420    if( pDeferred ){
120421      char *pList;
120422      int nList;
120423      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
120424      if( rc!=SQLITE_OK ) return rc;
120425
120426      if( pList==0 ){
120427        sqlite3_free(aPoslist);
120428        pPhrase->doclist.pList = 0;
120429        pPhrase->doclist.nList = 0;
120430        return SQLITE_OK;
120431
120432      }else if( aPoslist==0 ){
120433        aPoslist = pList;
120434        nPoslist = nList;
120435
120436      }else{
120437        char *aOut = pList;
120438        char *p1 = aPoslist;
120439        char *p2 = aOut;
120440
120441        assert( iPrev>=0 );
120442        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
120443        sqlite3_free(aPoslist);
120444        aPoslist = pList;
120445        nPoslist = (int)(aOut - aPoslist);
120446        if( nPoslist==0 ){
120447          sqlite3_free(aPoslist);
120448          pPhrase->doclist.pList = 0;
120449          pPhrase->doclist.nList = 0;
120450          return SQLITE_OK;
120451        }
120452      }
120453      iPrev = iToken;
120454    }
120455  }
120456
120457  if( iPrev>=0 ){
120458    int nMaxUndeferred = pPhrase->iDoclistToken;
120459    if( nMaxUndeferred<0 ){
120460      pPhrase->doclist.pList = aPoslist;
120461      pPhrase->doclist.nList = nPoslist;
120462      pPhrase->doclist.iDocid = pCsr->iPrevId;
120463      pPhrase->doclist.bFreeList = 1;
120464    }else{
120465      int nDistance;
120466      char *p1;
120467      char *p2;
120468      char *aOut;
120469
120470      if( nMaxUndeferred>iPrev ){
120471        p1 = aPoslist;
120472        p2 = pPhrase->doclist.pList;
120473        nDistance = nMaxUndeferred - iPrev;
120474      }else{
120475        p1 = pPhrase->doclist.pList;
120476        p2 = aPoslist;
120477        nDistance = iPrev - nMaxUndeferred;
120478      }
120479
120480      aOut = (char *)sqlite3_malloc(nPoslist+8);
120481      if( !aOut ){
120482        sqlite3_free(aPoslist);
120483        return SQLITE_NOMEM;
120484      }
120485
120486      pPhrase->doclist.pList = aOut;
120487      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
120488        pPhrase->doclist.bFreeList = 1;
120489        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
120490      }else{
120491        sqlite3_free(aOut);
120492        pPhrase->doclist.pList = 0;
120493        pPhrase->doclist.nList = 0;
120494      }
120495      sqlite3_free(aPoslist);
120496    }
120497  }
120498
120499  return SQLITE_OK;
120500}
120501
120502/*
120503** This function is called for each Fts3Phrase in a full-text query
120504** expression to initialize the mechanism for returning rows. Once this
120505** function has been called successfully on an Fts3Phrase, it may be
120506** used with fts3EvalPhraseNext() to iterate through the matching docids.
120507**
120508** If parameter bOptOk is true, then the phrase may (or may not) use the
120509** incremental loading strategy. Otherwise, the entire doclist is loaded into
120510** memory within this call.
120511**
120512** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120513*/
120514static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
120515  int rc;                         /* Error code */
120516  Fts3PhraseToken *pFirst = &p->aToken[0];
120517  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120518
120519  if( pCsr->bDesc==pTab->bDescIdx
120520   && bOptOk==1
120521   && p->nToken==1
120522   && pFirst->pSegcsr
120523   && pFirst->pSegcsr->bLookup
120524   && pFirst->bFirst==0
120525  ){
120526    /* Use the incremental approach. */
120527    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
120528    rc = sqlite3Fts3MsrIncrStart(
120529        pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
120530    p->bIncr = 1;
120531
120532  }else{
120533    /* Load the full doclist for the phrase into memory. */
120534    rc = fts3EvalPhraseLoad(pCsr, p);
120535    p->bIncr = 0;
120536  }
120537
120538  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
120539  return rc;
120540}
120541
120542/*
120543** This function is used to iterate backwards (from the end to start)
120544** through doclists. It is used by this module to iterate through phrase
120545** doclists in reverse and by the fts3_write.c module to iterate through
120546** pending-terms lists when writing to databases with "order=desc".
120547**
120548** The doclist may be sorted in ascending (parameter bDescIdx==0) or
120549** descending (parameter bDescIdx==1) order of docid. Regardless, this
120550** function iterates from the end of the doclist to the beginning.
120551*/
120552SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
120553  int bDescIdx,                   /* True if the doclist is desc */
120554  char *aDoclist,                 /* Pointer to entire doclist */
120555  int nDoclist,                   /* Length of aDoclist in bytes */
120556  char **ppIter,                  /* IN/OUT: Iterator pointer */
120557  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
120558  int *pnList,                    /* IN/OUT: List length pointer */
120559  u8 *pbEof                       /* OUT: End-of-file flag */
120560){
120561  char *p = *ppIter;
120562
120563  assert( nDoclist>0 );
120564  assert( *pbEof==0 );
120565  assert( p || *piDocid==0 );
120566  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
120567
120568  if( p==0 ){
120569    sqlite3_int64 iDocid = 0;
120570    char *pNext = 0;
120571    char *pDocid = aDoclist;
120572    char *pEnd = &aDoclist[nDoclist];
120573    int iMul = 1;
120574
120575    while( pDocid<pEnd ){
120576      sqlite3_int64 iDelta;
120577      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
120578      iDocid += (iMul * iDelta);
120579      pNext = pDocid;
120580      fts3PoslistCopy(0, &pDocid);
120581      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
120582      iMul = (bDescIdx ? -1 : 1);
120583    }
120584
120585    *pnList = (int)(pEnd - pNext);
120586    *ppIter = pNext;
120587    *piDocid = iDocid;
120588  }else{
120589    int iMul = (bDescIdx ? -1 : 1);
120590    sqlite3_int64 iDelta;
120591    fts3GetReverseVarint(&p, aDoclist, &iDelta);
120592    *piDocid -= (iMul * iDelta);
120593
120594    if( p==aDoclist ){
120595      *pbEof = 1;
120596    }else{
120597      char *pSave = p;
120598      fts3ReversePoslist(aDoclist, &p);
120599      *pnList = (int)(pSave - p);
120600    }
120601    *ppIter = p;
120602  }
120603}
120604
120605/*
120606** Attempt to move the phrase iterator to point to the next matching docid.
120607** If an error occurs, return an SQLite error code. Otherwise, return
120608** SQLITE_OK.
120609**
120610** If there is no "next" entry and no error occurs, then *pbEof is set to
120611** 1 before returning. Otherwise, if no error occurs and the iterator is
120612** successfully advanced, *pbEof is set to 0.
120613*/
120614static int fts3EvalPhraseNext(
120615  Fts3Cursor *pCsr,               /* FTS Cursor handle */
120616  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
120617  u8 *pbEof                       /* OUT: Set to 1 if EOF */
120618){
120619  int rc = SQLITE_OK;
120620  Fts3Doclist *pDL = &p->doclist;
120621  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120622
120623  if( p->bIncr ){
120624    assert( p->nToken==1 );
120625    assert( pDL->pNextDocid==0 );
120626    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
120627        &pDL->iDocid, &pDL->pList, &pDL->nList
120628    );
120629    if( rc==SQLITE_OK && !pDL->pList ){
120630      *pbEof = 1;
120631    }
120632  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
120633    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
120634        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
120635    );
120636    pDL->pList = pDL->pNextDocid;
120637  }else{
120638    char *pIter;                            /* Used to iterate through aAll */
120639    char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
120640    if( pDL->pNextDocid ){
120641      pIter = pDL->pNextDocid;
120642    }else{
120643      pIter = pDL->aAll;
120644    }
120645
120646    if( pIter>=pEnd ){
120647      /* We have already reached the end of this doclist. EOF. */
120648      *pbEof = 1;
120649    }else{
120650      sqlite3_int64 iDelta;
120651      pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
120652      if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
120653        pDL->iDocid += iDelta;
120654      }else{
120655        pDL->iDocid -= iDelta;
120656      }
120657      pDL->pList = pIter;
120658      fts3PoslistCopy(0, &pIter);
120659      pDL->nList = (int)(pIter - pDL->pList);
120660
120661      /* pIter now points just past the 0x00 that terminates the position-
120662      ** list for document pDL->iDocid. However, if this position-list was
120663      ** edited in place by fts3EvalNearTrim(), then pIter may not actually
120664      ** point to the start of the next docid value. The following line deals
120665      ** with this case by advancing pIter past the zero-padding added by
120666      ** fts3EvalNearTrim().  */
120667      while( pIter<pEnd && *pIter==0 ) pIter++;
120668
120669      pDL->pNextDocid = pIter;
120670      assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
120671      *pbEof = 0;
120672    }
120673  }
120674
120675  return rc;
120676}
120677
120678/*
120679**
120680** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
120681** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
120682** expression. Also the Fts3Expr.bDeferred variable is set to true for any
120683** expressions for which all descendent tokens are deferred.
120684**
120685** If parameter bOptOk is zero, then it is guaranteed that the
120686** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
120687** each phrase in the expression (subject to deferred token processing).
120688** Or, if bOptOk is non-zero, then one or more tokens within the expression
120689** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
120690**
120691** If an error occurs within this function, *pRc is set to an SQLite error
120692** code before returning.
120693*/
120694static void fts3EvalStartReaders(
120695  Fts3Cursor *pCsr,               /* FTS Cursor handle */
120696  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
120697  int bOptOk,                     /* True to enable incremental loading */
120698  int *pRc                        /* IN/OUT: Error code */
120699){
120700  if( pExpr && SQLITE_OK==*pRc ){
120701    if( pExpr->eType==FTSQUERY_PHRASE ){
120702      int i;
120703      int nToken = pExpr->pPhrase->nToken;
120704      for(i=0; i<nToken; i++){
120705        if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
120706      }
120707      pExpr->bDeferred = (i==nToken);
120708      *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
120709    }else{
120710      fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
120711      fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
120712      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
120713    }
120714  }
120715}
120716
120717/*
120718** An array of the following structures is assembled as part of the process
120719** of selecting tokens to defer before the query starts executing (as part
120720** of the xFilter() method). There is one element in the array for each
120721** token in the FTS expression.
120722**
120723** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
120724** to phrases that are connected only by AND and NEAR operators (not OR or
120725** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
120726** separately. The root of a tokens AND/NEAR cluster is stored in
120727** Fts3TokenAndCost.pRoot.
120728*/
120729typedef struct Fts3TokenAndCost Fts3TokenAndCost;
120730struct Fts3TokenAndCost {
120731  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
120732  int iToken;                     /* Position of token in phrase */
120733  Fts3PhraseToken *pToken;        /* The token itself */
120734  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
120735  int nOvfl;                      /* Number of overflow pages to load doclist */
120736  int iCol;                       /* The column the token must match */
120737};
120738
120739/*
120740** This function is used to populate an allocated Fts3TokenAndCost array.
120741**
120742** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
120743** Otherwise, if an error occurs during execution, *pRc is set to an
120744** SQLite error code.
120745*/
120746static void fts3EvalTokenCosts(
120747  Fts3Cursor *pCsr,               /* FTS Cursor handle */
120748  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
120749  Fts3Expr *pExpr,                /* Expression to consider */
120750  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
120751  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
120752  int *pRc                        /* IN/OUT: Error code */
120753){
120754  if( *pRc==SQLITE_OK ){
120755    if( pExpr->eType==FTSQUERY_PHRASE ){
120756      Fts3Phrase *pPhrase = pExpr->pPhrase;
120757      int i;
120758      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
120759        Fts3TokenAndCost *pTC = (*ppTC)++;
120760        pTC->pPhrase = pPhrase;
120761        pTC->iToken = i;
120762        pTC->pRoot = pRoot;
120763        pTC->pToken = &pPhrase->aToken[i];
120764        pTC->iCol = pPhrase->iColumn;
120765        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
120766      }
120767    }else if( pExpr->eType!=FTSQUERY_NOT ){
120768      assert( pExpr->eType==FTSQUERY_OR
120769           || pExpr->eType==FTSQUERY_AND
120770           || pExpr->eType==FTSQUERY_NEAR
120771      );
120772      assert( pExpr->pLeft && pExpr->pRight );
120773      if( pExpr->eType==FTSQUERY_OR ){
120774        pRoot = pExpr->pLeft;
120775        **ppOr = pRoot;
120776        (*ppOr)++;
120777      }
120778      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
120779      if( pExpr->eType==FTSQUERY_OR ){
120780        pRoot = pExpr->pRight;
120781        **ppOr = pRoot;
120782        (*ppOr)++;
120783      }
120784      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
120785    }
120786  }
120787}
120788
120789/*
120790** Determine the average document (row) size in pages. If successful,
120791** write this value to *pnPage and return SQLITE_OK. Otherwise, return
120792** an SQLite error code.
120793**
120794** The average document size in pages is calculated by first calculating
120795** determining the average size in bytes, B. If B is less than the amount
120796** of data that will fit on a single leaf page of an intkey table in
120797** this database, then the average docsize is 1. Otherwise, it is 1 plus
120798** the number of overflow pages consumed by a record B bytes in size.
120799*/
120800static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
120801  if( pCsr->nRowAvg==0 ){
120802    /* The average document size, which is required to calculate the cost
120803    ** of each doclist, has not yet been determined. Read the required
120804    ** data from the %_stat table to calculate it.
120805    **
120806    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
120807    ** varints, where nCol is the number of columns in the FTS3 table.
120808    ** The first varint is the number of documents currently stored in
120809    ** the table. The following nCol varints contain the total amount of
120810    ** data stored in all rows of each column of the table, from left
120811    ** to right.
120812    */
120813    int rc;
120814    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
120815    sqlite3_stmt *pStmt;
120816    sqlite3_int64 nDoc = 0;
120817    sqlite3_int64 nByte = 0;
120818    const char *pEnd;
120819    const char *a;
120820
120821    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
120822    if( rc!=SQLITE_OK ) return rc;
120823    a = sqlite3_column_blob(pStmt, 0);
120824    assert( a );
120825
120826    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
120827    a += sqlite3Fts3GetVarint(a, &nDoc);
120828    while( a<pEnd ){
120829      a += sqlite3Fts3GetVarint(a, &nByte);
120830    }
120831    if( nDoc==0 || nByte==0 ){
120832      sqlite3_reset(pStmt);
120833      return FTS_CORRUPT_VTAB;
120834    }
120835
120836    pCsr->nDoc = nDoc;
120837    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
120838    assert( pCsr->nRowAvg>0 );
120839    rc = sqlite3_reset(pStmt);
120840    if( rc!=SQLITE_OK ) return rc;
120841  }
120842
120843  *pnPage = pCsr->nRowAvg;
120844  return SQLITE_OK;
120845}
120846
120847/*
120848** This function is called to select the tokens (if any) that will be
120849** deferred. The array aTC[] has already been populated when this is
120850** called.
120851**
120852** This function is called once for each AND/NEAR cluster in the
120853** expression. Each invocation determines which tokens to defer within
120854** the cluster with root node pRoot. See comments above the definition
120855** of struct Fts3TokenAndCost for more details.
120856**
120857** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
120858** called on each token to defer. Otherwise, an SQLite error code is
120859** returned.
120860*/
120861static int fts3EvalSelectDeferred(
120862  Fts3Cursor *pCsr,               /* FTS Cursor handle */
120863  Fts3Expr *pRoot,                /* Consider tokens with this root node */
120864  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
120865  int nTC                         /* Number of entries in aTC[] */
120866){
120867  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120868  int nDocSize = 0;               /* Number of pages per doc loaded */
120869  int rc = SQLITE_OK;             /* Return code */
120870  int ii;                         /* Iterator variable for various purposes */
120871  int nOvfl = 0;                  /* Total overflow pages used by doclists */
120872  int nToken = 0;                 /* Total number of tokens in cluster */
120873
120874  int nMinEst = 0;                /* The minimum count for any phrase so far. */
120875  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
120876
120877  /* Tokens are never deferred for FTS tables created using the content=xxx
120878  ** option. The reason being that it is not guaranteed that the content
120879  ** table actually contains the same data as the index. To prevent this from
120880  ** causing any problems, the deferred token optimization is completely
120881  ** disabled for content=xxx tables. */
120882  if( pTab->zContentTbl ){
120883    return SQLITE_OK;
120884  }
120885
120886  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
120887  ** associated with the tokens spill onto overflow pages, or if there is
120888  ** only 1 token, exit early. No tokens to defer in this case. */
120889  for(ii=0; ii<nTC; ii++){
120890    if( aTC[ii].pRoot==pRoot ){
120891      nOvfl += aTC[ii].nOvfl;
120892      nToken++;
120893    }
120894  }
120895  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
120896
120897  /* Obtain the average docsize (in pages). */
120898  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
120899  assert( rc!=SQLITE_OK || nDocSize>0 );
120900
120901
120902  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
120903  ** of the number of overflow pages that will be loaded by the pager layer
120904  ** to retrieve the entire doclist for the token from the full-text index.
120905  ** Load the doclists for tokens that are either:
120906  **
120907  **   a. The cheapest token in the entire query (i.e. the one visited by the
120908  **      first iteration of this loop), or
120909  **
120910  **   b. Part of a multi-token phrase.
120911  **
120912  ** After each token doclist is loaded, merge it with the others from the
120913  ** same phrase and count the number of documents that the merged doclist
120914  ** contains. Set variable "nMinEst" to the smallest number of documents in
120915  ** any phrase doclist for which 1 or more token doclists have been loaded.
120916  ** Let nOther be the number of other phrases for which it is certain that
120917  ** one or more tokens will not be deferred.
120918  **
120919  ** Then, for each token, defer it if loading the doclist would result in
120920  ** loading N or more overflow pages into memory, where N is computed as:
120921  **
120922  **    (nMinEst + 4^nOther - 1) / (4^nOther)
120923  */
120924  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
120925    int iTC;                      /* Used to iterate through aTC[] array. */
120926    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
120927
120928    /* Set pTC to point to the cheapest remaining token. */
120929    for(iTC=0; iTC<nTC; iTC++){
120930      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
120931       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
120932      ){
120933        pTC = &aTC[iTC];
120934      }
120935    }
120936    assert( pTC );
120937
120938    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
120939      /* The number of overflow pages to load for this (and therefore all
120940      ** subsequent) tokens is greater than the estimated number of pages
120941      ** that will be loaded if all subsequent tokens are deferred.
120942      */
120943      Fts3PhraseToken *pToken = pTC->pToken;
120944      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
120945      fts3SegReaderCursorFree(pToken->pSegcsr);
120946      pToken->pSegcsr = 0;
120947    }else{
120948      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
120949      ** for-loop. Except, limit the value to 2^24 to prevent it from
120950      ** overflowing the 32-bit integer it is stored in. */
120951      if( ii<12 ) nLoad4 = nLoad4*4;
120952
120953      if( ii==0 || pTC->pPhrase->nToken>1 ){
120954        /* Either this is the cheapest token in the entire query, or it is
120955        ** part of a multi-token phrase. Either way, the entire doclist will
120956        ** (eventually) be loaded into memory. It may as well be now. */
120957        Fts3PhraseToken *pToken = pTC->pToken;
120958        int nList = 0;
120959        char *pList = 0;
120960        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
120961        assert( rc==SQLITE_OK || pList==0 );
120962        if( rc==SQLITE_OK ){
120963          int nCount;
120964          fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
120965          nCount = fts3DoclistCountDocids(
120966              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
120967          );
120968          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
120969        }
120970      }
120971    }
120972    pTC->pToken = 0;
120973  }
120974
120975  return rc;
120976}
120977
120978/*
120979** This function is called from within the xFilter method. It initializes
120980** the full-text query currently stored in pCsr->pExpr. To iterate through
120981** the results of a query, the caller does:
120982**
120983**    fts3EvalStart(pCsr);
120984**    while( 1 ){
120985**      fts3EvalNext(pCsr);
120986**      if( pCsr->bEof ) break;
120987**      ... return row pCsr->iPrevId to the caller ...
120988**    }
120989*/
120990static int fts3EvalStart(Fts3Cursor *pCsr){
120991  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120992  int rc = SQLITE_OK;
120993  int nToken = 0;
120994  int nOr = 0;
120995
120996  /* Allocate a MultiSegReader for each token in the expression. */
120997  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
120998
120999  /* Determine which, if any, tokens in the expression should be deferred. */
121000  if( rc==SQLITE_OK && nToken>1 && pTab->bHasStat ){
121001    Fts3TokenAndCost *aTC;
121002    Fts3Expr **apOr;
121003    aTC = (Fts3TokenAndCost *)sqlite3_malloc(
121004        sizeof(Fts3TokenAndCost) * nToken
121005      + sizeof(Fts3Expr *) * nOr * 2
121006    );
121007    apOr = (Fts3Expr **)&aTC[nToken];
121008
121009    if( !aTC ){
121010      rc = SQLITE_NOMEM;
121011    }else{
121012      int ii;
121013      Fts3TokenAndCost *pTC = aTC;
121014      Fts3Expr **ppOr = apOr;
121015
121016      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
121017      nToken = (int)(pTC-aTC);
121018      nOr = (int)(ppOr-apOr);
121019
121020      if( rc==SQLITE_OK ){
121021        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
121022        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
121023          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
121024        }
121025      }
121026
121027      sqlite3_free(aTC);
121028    }
121029  }
121030
121031  fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
121032  return rc;
121033}
121034
121035/*
121036** Invalidate the current position list for phrase pPhrase.
121037*/
121038static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
121039  if( pPhrase->doclist.bFreeList ){
121040    sqlite3_free(pPhrase->doclist.pList);
121041  }
121042  pPhrase->doclist.pList = 0;
121043  pPhrase->doclist.nList = 0;
121044  pPhrase->doclist.bFreeList = 0;
121045}
121046
121047/*
121048** This function is called to edit the position list associated with
121049** the phrase object passed as the fifth argument according to a NEAR
121050** condition. For example:
121051**
121052**     abc NEAR/5 "def ghi"
121053**
121054** Parameter nNear is passed the NEAR distance of the expression (5 in
121055** the example above). When this function is called, *paPoslist points to
121056** the position list, and *pnToken is the number of phrase tokens in, the
121057** phrase on the other side of the NEAR operator to pPhrase. For example,
121058** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
121059** the position list associated with phrase "abc".
121060**
121061** All positions in the pPhrase position list that are not sufficiently
121062** close to a position in the *paPoslist position list are removed. If this
121063** leaves 0 positions, zero is returned. Otherwise, non-zero.
121064**
121065** Before returning, *paPoslist is set to point to the position lsit
121066** associated with pPhrase. And *pnToken is set to the number of tokens in
121067** pPhrase.
121068*/
121069static int fts3EvalNearTrim(
121070  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
121071  char *aTmp,                     /* Temporary space to use */
121072  char **paPoslist,               /* IN/OUT: Position list */
121073  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
121074  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
121075){
121076  int nParam1 = nNear + pPhrase->nToken;
121077  int nParam2 = nNear + *pnToken;
121078  int nNew;
121079  char *p2;
121080  char *pOut;
121081  int res;
121082
121083  assert( pPhrase->doclist.pList );
121084
121085  p2 = pOut = pPhrase->doclist.pList;
121086  res = fts3PoslistNearMerge(
121087    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
121088  );
121089  if( res ){
121090    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
121091    assert( pPhrase->doclist.pList[nNew]=='\0' );
121092    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
121093    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
121094    pPhrase->doclist.nList = nNew;
121095    *paPoslist = pPhrase->doclist.pList;
121096    *pnToken = pPhrase->nToken;
121097  }
121098
121099  return res;
121100}
121101
121102/*
121103** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
121104** Otherwise, it advances the expression passed as the second argument to
121105** point to the next matching row in the database. Expressions iterate through
121106** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
121107** or descending if it is non-zero.
121108**
121109** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
121110** successful, the following variables in pExpr are set:
121111**
121112**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
121113**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
121114**
121115** If the expression is of type FTSQUERY_PHRASE, and the expression is not
121116** at EOF, then the following variables are populated with the position list
121117** for the phrase for the visited row:
121118**
121119**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
121120**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
121121**
121122** It says above that this function advances the expression to the next
121123** matching row. This is usually true, but there are the following exceptions:
121124**
121125**   1. Deferred tokens are not taken into account. If a phrase consists
121126**      entirely of deferred tokens, it is assumed to match every row in
121127**      the db. In this case the position-list is not populated at all.
121128**
121129**      Or, if a phrase contains one or more deferred tokens and one or
121130**      more non-deferred tokens, then the expression is advanced to the
121131**      next possible match, considering only non-deferred tokens. In other
121132**      words, if the phrase is "A B C", and "B" is deferred, the expression
121133**      is advanced to the next row that contains an instance of "A * C",
121134**      where "*" may match any single token. The position list in this case
121135**      is populated as for "A * C" before returning.
121136**
121137**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
121138**      advanced to point to the next row that matches "x AND y".
121139**
121140** See fts3EvalTestDeferredAndNear() for details on testing if a row is
121141** really a match, taking into account deferred tokens and NEAR operators.
121142*/
121143static void fts3EvalNextRow(
121144  Fts3Cursor *pCsr,               /* FTS Cursor handle */
121145  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
121146  int *pRc                        /* IN/OUT: Error code */
121147){
121148  if( *pRc==SQLITE_OK ){
121149    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
121150    assert( pExpr->bEof==0 );
121151    pExpr->bStart = 1;
121152
121153    switch( pExpr->eType ){
121154      case FTSQUERY_NEAR:
121155      case FTSQUERY_AND: {
121156        Fts3Expr *pLeft = pExpr->pLeft;
121157        Fts3Expr *pRight = pExpr->pRight;
121158        assert( !pLeft->bDeferred || !pRight->bDeferred );
121159
121160        if( pLeft->bDeferred ){
121161          /* LHS is entirely deferred. So we assume it matches every row.
121162          ** Advance the RHS iterator to find the next row visited. */
121163          fts3EvalNextRow(pCsr, pRight, pRc);
121164          pExpr->iDocid = pRight->iDocid;
121165          pExpr->bEof = pRight->bEof;
121166        }else if( pRight->bDeferred ){
121167          /* RHS is entirely deferred. So we assume it matches every row.
121168          ** Advance the LHS iterator to find the next row visited. */
121169          fts3EvalNextRow(pCsr, pLeft, pRc);
121170          pExpr->iDocid = pLeft->iDocid;
121171          pExpr->bEof = pLeft->bEof;
121172        }else{
121173          /* Neither the RHS or LHS are deferred. */
121174          fts3EvalNextRow(pCsr, pLeft, pRc);
121175          fts3EvalNextRow(pCsr, pRight, pRc);
121176          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
121177            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
121178            if( iDiff==0 ) break;
121179            if( iDiff<0 ){
121180              fts3EvalNextRow(pCsr, pLeft, pRc);
121181            }else{
121182              fts3EvalNextRow(pCsr, pRight, pRc);
121183            }
121184          }
121185          pExpr->iDocid = pLeft->iDocid;
121186          pExpr->bEof = (pLeft->bEof || pRight->bEof);
121187        }
121188        break;
121189      }
121190
121191      case FTSQUERY_OR: {
121192        Fts3Expr *pLeft = pExpr->pLeft;
121193        Fts3Expr *pRight = pExpr->pRight;
121194        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
121195
121196        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
121197        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
121198
121199        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
121200          fts3EvalNextRow(pCsr, pLeft, pRc);
121201        }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
121202          fts3EvalNextRow(pCsr, pRight, pRc);
121203        }else{
121204          fts3EvalNextRow(pCsr, pLeft, pRc);
121205          fts3EvalNextRow(pCsr, pRight, pRc);
121206        }
121207
121208        pExpr->bEof = (pLeft->bEof && pRight->bEof);
121209        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
121210        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
121211          pExpr->iDocid = pLeft->iDocid;
121212        }else{
121213          pExpr->iDocid = pRight->iDocid;
121214        }
121215
121216        break;
121217      }
121218
121219      case FTSQUERY_NOT: {
121220        Fts3Expr *pLeft = pExpr->pLeft;
121221        Fts3Expr *pRight = pExpr->pRight;
121222
121223        if( pRight->bStart==0 ){
121224          fts3EvalNextRow(pCsr, pRight, pRc);
121225          assert( *pRc!=SQLITE_OK || pRight->bStart );
121226        }
121227
121228        fts3EvalNextRow(pCsr, pLeft, pRc);
121229        if( pLeft->bEof==0 ){
121230          while( !*pRc
121231              && !pRight->bEof
121232              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
121233          ){
121234            fts3EvalNextRow(pCsr, pRight, pRc);
121235          }
121236        }
121237        pExpr->iDocid = pLeft->iDocid;
121238        pExpr->bEof = pLeft->bEof;
121239        break;
121240      }
121241
121242      default: {
121243        Fts3Phrase *pPhrase = pExpr->pPhrase;
121244        fts3EvalInvalidatePoslist(pPhrase);
121245        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
121246        pExpr->iDocid = pPhrase->doclist.iDocid;
121247        break;
121248      }
121249    }
121250  }
121251}
121252
121253/*
121254** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
121255** cluster, then this function returns 1 immediately.
121256**
121257** Otherwise, it checks if the current row really does match the NEAR
121258** expression, using the data currently stored in the position lists
121259** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
121260**
121261** If the current row is a match, the position list associated with each
121262** phrase in the NEAR expression is edited in place to contain only those
121263** phrase instances sufficiently close to their peers to satisfy all NEAR
121264** constraints. In this case it returns 1. If the NEAR expression does not
121265** match the current row, 0 is returned. The position lists may or may not
121266** be edited if 0 is returned.
121267*/
121268static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
121269  int res = 1;
121270
121271  /* The following block runs if pExpr is the root of a NEAR query.
121272  ** For example, the query:
121273  **
121274  **         "w" NEAR "x" NEAR "y" NEAR "z"
121275  **
121276  ** which is represented in tree form as:
121277  **
121278  **                               |
121279  **                          +--NEAR--+      <-- root of NEAR query
121280  **                          |        |
121281  **                     +--NEAR--+   "z"
121282  **                     |        |
121283  **                +--NEAR--+   "y"
121284  **                |        |
121285  **               "w"      "x"
121286  **
121287  ** The right-hand child of a NEAR node is always a phrase. The
121288  ** left-hand child may be either a phrase or a NEAR node. There are
121289  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
121290  */
121291  if( *pRc==SQLITE_OK
121292   && pExpr->eType==FTSQUERY_NEAR
121293   && pExpr->bEof==0
121294   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
121295  ){
121296    Fts3Expr *p;
121297    int nTmp = 0;                 /* Bytes of temp space */
121298    char *aTmp;                   /* Temp space for PoslistNearMerge() */
121299
121300    /* Allocate temporary working space. */
121301    for(p=pExpr; p->pLeft; p=p->pLeft){
121302      nTmp += p->pRight->pPhrase->doclist.nList;
121303    }
121304    nTmp += p->pPhrase->doclist.nList;
121305    aTmp = sqlite3_malloc(nTmp*2);
121306    if( !aTmp ){
121307      *pRc = SQLITE_NOMEM;
121308      res = 0;
121309    }else{
121310      char *aPoslist = p->pPhrase->doclist.pList;
121311      int nToken = p->pPhrase->nToken;
121312
121313      for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
121314        Fts3Phrase *pPhrase = p->pRight->pPhrase;
121315        int nNear = p->nNear;
121316        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
121317      }
121318
121319      aPoslist = pExpr->pRight->pPhrase->doclist.pList;
121320      nToken = pExpr->pRight->pPhrase->nToken;
121321      for(p=pExpr->pLeft; p && res; p=p->pLeft){
121322        int nNear;
121323        Fts3Phrase *pPhrase;
121324        assert( p->pParent && p->pParent->pLeft==p );
121325        nNear = p->pParent->nNear;
121326        pPhrase = (
121327            p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
121328        );
121329        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
121330      }
121331    }
121332
121333    sqlite3_free(aTmp);
121334  }
121335
121336  return res;
121337}
121338
121339/*
121340** This function is a helper function for fts3EvalTestDeferredAndNear().
121341** Assuming no error occurs or has occurred, It returns non-zero if the
121342** expression passed as the second argument matches the row that pCsr
121343** currently points to, or zero if it does not.
121344**
121345** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
121346** If an error occurs during execution of this function, *pRc is set to
121347** the appropriate SQLite error code. In this case the returned value is
121348** undefined.
121349*/
121350static int fts3EvalTestExpr(
121351  Fts3Cursor *pCsr,               /* FTS cursor handle */
121352  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
121353  int *pRc                        /* IN/OUT: Error code */
121354){
121355  int bHit = 1;                   /* Return value */
121356  if( *pRc==SQLITE_OK ){
121357    switch( pExpr->eType ){
121358      case FTSQUERY_NEAR:
121359      case FTSQUERY_AND:
121360        bHit = (
121361            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
121362         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
121363         && fts3EvalNearTest(pExpr, pRc)
121364        );
121365
121366        /* If the NEAR expression does not match any rows, zero the doclist for
121367        ** all phrases involved in the NEAR. This is because the snippet(),
121368        ** offsets() and matchinfo() functions are not supposed to recognize
121369        ** any instances of phrases that are part of unmatched NEAR queries.
121370        ** For example if this expression:
121371        **
121372        **    ... MATCH 'a OR (b NEAR c)'
121373        **
121374        ** is matched against a row containing:
121375        **
121376        **        'a b d e'
121377        **
121378        ** then any snippet() should ony highlight the "a" term, not the "b"
121379        ** (as "b" is part of a non-matching NEAR clause).
121380        */
121381        if( bHit==0
121382         && pExpr->eType==FTSQUERY_NEAR
121383         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
121384        ){
121385          Fts3Expr *p;
121386          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
121387            if( p->pRight->iDocid==pCsr->iPrevId ){
121388              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
121389            }
121390          }
121391          if( p->iDocid==pCsr->iPrevId ){
121392            fts3EvalInvalidatePoslist(p->pPhrase);
121393          }
121394        }
121395
121396        break;
121397
121398      case FTSQUERY_OR: {
121399        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
121400        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
121401        bHit = bHit1 || bHit2;
121402        break;
121403      }
121404
121405      case FTSQUERY_NOT:
121406        bHit = (
121407            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
121408         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
121409        );
121410        break;
121411
121412      default: {
121413        if( pCsr->pDeferred
121414         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
121415        ){
121416          Fts3Phrase *pPhrase = pExpr->pPhrase;
121417          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
121418          if( pExpr->bDeferred ){
121419            fts3EvalInvalidatePoslist(pPhrase);
121420          }
121421          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
121422          bHit = (pPhrase->doclist.pList!=0);
121423          pExpr->iDocid = pCsr->iPrevId;
121424        }else{
121425          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
121426        }
121427        break;
121428      }
121429    }
121430  }
121431  return bHit;
121432}
121433
121434/*
121435** This function is called as the second part of each xNext operation when
121436** iterating through the results of a full-text query. At this point the
121437** cursor points to a row that matches the query expression, with the
121438** following caveats:
121439**
121440**   * Up until this point, "NEAR" operators in the expression have been
121441**     treated as "AND".
121442**
121443**   * Deferred tokens have not yet been considered.
121444**
121445** If *pRc is not SQLITE_OK when this function is called, it immediately
121446** returns 0. Otherwise, it tests whether or not after considering NEAR
121447** operators and deferred tokens the current row is still a match for the
121448** expression. It returns 1 if both of the following are true:
121449**
121450**   1. *pRc is SQLITE_OK when this function returns, and
121451**
121452**   2. After scanning the current FTS table row for the deferred tokens,
121453**      it is determined that the row does *not* match the query.
121454**
121455** Or, if no error occurs and it seems the current row does match the FTS
121456** query, return 0.
121457*/
121458static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
121459  int rc = *pRc;
121460  int bMiss = 0;
121461  if( rc==SQLITE_OK ){
121462
121463    /* If there are one or more deferred tokens, load the current row into
121464    ** memory and scan it to determine the position list for each deferred
121465    ** token. Then, see if this row is really a match, considering deferred
121466    ** tokens and NEAR operators (neither of which were taken into account
121467    ** earlier, by fts3EvalNextRow()).
121468    */
121469    if( pCsr->pDeferred ){
121470      rc = fts3CursorSeek(0, pCsr);
121471      if( rc==SQLITE_OK ){
121472        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
121473      }
121474    }
121475    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
121476
121477    /* Free the position-lists accumulated for each deferred token above. */
121478    sqlite3Fts3FreeDeferredDoclists(pCsr);
121479    *pRc = rc;
121480  }
121481  return (rc==SQLITE_OK && bMiss);
121482}
121483
121484/*
121485** Advance to the next document that matches the FTS expression in
121486** Fts3Cursor.pExpr.
121487*/
121488static int fts3EvalNext(Fts3Cursor *pCsr){
121489  int rc = SQLITE_OK;             /* Return Code */
121490  Fts3Expr *pExpr = pCsr->pExpr;
121491  assert( pCsr->isEof==0 );
121492  if( pExpr==0 ){
121493    pCsr->isEof = 1;
121494  }else{
121495    do {
121496      if( pCsr->isRequireSeek==0 ){
121497        sqlite3_reset(pCsr->pStmt);
121498      }
121499      assert( sqlite3_data_count(pCsr->pStmt)==0 );
121500      fts3EvalNextRow(pCsr, pExpr, &rc);
121501      pCsr->isEof = pExpr->bEof;
121502      pCsr->isRequireSeek = 1;
121503      pCsr->isMatchinfoNeeded = 1;
121504      pCsr->iPrevId = pExpr->iDocid;
121505    }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
121506  }
121507  return rc;
121508}
121509
121510/*
121511** Restart interation for expression pExpr so that the next call to
121512** fts3EvalNext() visits the first row. Do not allow incremental
121513** loading or merging of phrase doclists for this iteration.
121514**
121515** If *pRc is other than SQLITE_OK when this function is called, it is
121516** a no-op. If an error occurs within this function, *pRc is set to an
121517** SQLite error code before returning.
121518*/
121519static void fts3EvalRestart(
121520  Fts3Cursor *pCsr,
121521  Fts3Expr *pExpr,
121522  int *pRc
121523){
121524  if( pExpr && *pRc==SQLITE_OK ){
121525    Fts3Phrase *pPhrase = pExpr->pPhrase;
121526
121527    if( pPhrase ){
121528      fts3EvalInvalidatePoslist(pPhrase);
121529      if( pPhrase->bIncr ){
121530        assert( pPhrase->nToken==1 );
121531        assert( pPhrase->aToken[0].pSegcsr );
121532        sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
121533        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
121534      }
121535
121536      pPhrase->doclist.pNextDocid = 0;
121537      pPhrase->doclist.iDocid = 0;
121538    }
121539
121540    pExpr->iDocid = 0;
121541    pExpr->bEof = 0;
121542    pExpr->bStart = 0;
121543
121544    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
121545    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
121546  }
121547}
121548
121549/*
121550** After allocating the Fts3Expr.aMI[] array for each phrase in the
121551** expression rooted at pExpr, the cursor iterates through all rows matched
121552** by pExpr, calling this function for each row. This function increments
121553** the values in Fts3Expr.aMI[] according to the position-list currently
121554** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
121555** expression nodes.
121556*/
121557static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
121558  if( pExpr ){
121559    Fts3Phrase *pPhrase = pExpr->pPhrase;
121560    if( pPhrase && pPhrase->doclist.pList ){
121561      int iCol = 0;
121562      char *p = pPhrase->doclist.pList;
121563
121564      assert( *p );
121565      while( 1 ){
121566        u8 c = 0;
121567        int iCnt = 0;
121568        while( 0xFE & (*p | c) ){
121569          if( (c&0x80)==0 ) iCnt++;
121570          c = *p++ & 0x80;
121571        }
121572
121573        /* aMI[iCol*3 + 1] = Number of occurrences
121574        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
121575        */
121576        pExpr->aMI[iCol*3 + 1] += iCnt;
121577        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
121578        if( *p==0x00 ) break;
121579        p++;
121580        p += sqlite3Fts3GetVarint32(p, &iCol);
121581      }
121582    }
121583
121584    fts3EvalUpdateCounts(pExpr->pLeft);
121585    fts3EvalUpdateCounts(pExpr->pRight);
121586  }
121587}
121588
121589/*
121590** Expression pExpr must be of type FTSQUERY_PHRASE.
121591**
121592** If it is not already allocated and populated, this function allocates and
121593** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
121594** of a NEAR expression, then it also allocates and populates the same array
121595** for all other phrases that are part of the NEAR expression.
121596**
121597** SQLITE_OK is returned if the aMI[] array is successfully allocated and
121598** populated. Otherwise, if an error occurs, an SQLite error code is returned.
121599*/
121600static int fts3EvalGatherStats(
121601  Fts3Cursor *pCsr,               /* Cursor object */
121602  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
121603){
121604  int rc = SQLITE_OK;             /* Return code */
121605
121606  assert( pExpr->eType==FTSQUERY_PHRASE );
121607  if( pExpr->aMI==0 ){
121608    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121609    Fts3Expr *pRoot;                /* Root of NEAR expression */
121610    Fts3Expr *p;                    /* Iterator used for several purposes */
121611
121612    sqlite3_int64 iPrevId = pCsr->iPrevId;
121613    sqlite3_int64 iDocid;
121614    u8 bEof;
121615
121616    /* Find the root of the NEAR expression */
121617    pRoot = pExpr;
121618    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
121619      pRoot = pRoot->pParent;
121620    }
121621    iDocid = pRoot->iDocid;
121622    bEof = pRoot->bEof;
121623    assert( pRoot->bStart );
121624
121625    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
121626    for(p=pRoot; p; p=p->pLeft){
121627      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
121628      assert( pE->aMI==0 );
121629      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
121630      if( !pE->aMI ) return SQLITE_NOMEM;
121631      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
121632    }
121633
121634    fts3EvalRestart(pCsr, pRoot, &rc);
121635
121636    while( pCsr->isEof==0 && rc==SQLITE_OK ){
121637
121638      do {
121639        /* Ensure the %_content statement is reset. */
121640        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
121641        assert( sqlite3_data_count(pCsr->pStmt)==0 );
121642
121643        /* Advance to the next document */
121644        fts3EvalNextRow(pCsr, pRoot, &rc);
121645        pCsr->isEof = pRoot->bEof;
121646        pCsr->isRequireSeek = 1;
121647        pCsr->isMatchinfoNeeded = 1;
121648        pCsr->iPrevId = pRoot->iDocid;
121649      }while( pCsr->isEof==0
121650           && pRoot->eType==FTSQUERY_NEAR
121651           && fts3EvalTestDeferredAndNear(pCsr, &rc)
121652      );
121653
121654      if( rc==SQLITE_OK && pCsr->isEof==0 ){
121655        fts3EvalUpdateCounts(pRoot);
121656      }
121657    }
121658
121659    pCsr->isEof = 0;
121660    pCsr->iPrevId = iPrevId;
121661
121662    if( bEof ){
121663      pRoot->bEof = bEof;
121664    }else{
121665      /* Caution: pRoot may iterate through docids in ascending or descending
121666      ** order. For this reason, even though it seems more defensive, the
121667      ** do loop can not be written:
121668      **
121669      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
121670      */
121671      fts3EvalRestart(pCsr, pRoot, &rc);
121672      do {
121673        fts3EvalNextRow(pCsr, pRoot, &rc);
121674        assert( pRoot->bEof==0 );
121675      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
121676      fts3EvalTestDeferredAndNear(pCsr, &rc);
121677    }
121678  }
121679  return rc;
121680}
121681
121682/*
121683** This function is used by the matchinfo() module to query a phrase
121684** expression node for the following information:
121685**
121686**   1. The total number of occurrences of the phrase in each column of
121687**      the FTS table (considering all rows), and
121688**
121689**   2. For each column, the number of rows in the table for which the
121690**      column contains at least one instance of the phrase.
121691**
121692** If no error occurs, SQLITE_OK is returned and the values for each column
121693** written into the array aiOut as follows:
121694**
121695**   aiOut[iCol*3 + 1] = Number of occurrences
121696**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
121697**
121698** Caveats:
121699**
121700**   * If a phrase consists entirely of deferred tokens, then all output
121701**     values are set to the number of documents in the table. In other
121702**     words we assume that very common tokens occur exactly once in each
121703**     column of each row of the table.
121704**
121705**   * If a phrase contains some deferred tokens (and some non-deferred
121706**     tokens), count the potential occurrence identified by considering
121707**     the non-deferred tokens instead of actual phrase occurrences.
121708**
121709**   * If the phrase is part of a NEAR expression, then only phrase instances
121710**     that meet the NEAR constraint are included in the counts.
121711*/
121712SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
121713  Fts3Cursor *pCsr,               /* FTS cursor handle */
121714  Fts3Expr *pExpr,                /* Phrase expression */
121715  u32 *aiOut                      /* Array to write results into (see above) */
121716){
121717  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121718  int rc = SQLITE_OK;
121719  int iCol;
121720
121721  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
121722    assert( pCsr->nDoc>0 );
121723    for(iCol=0; iCol<pTab->nColumn; iCol++){
121724      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
121725      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
121726    }
121727  }else{
121728    rc = fts3EvalGatherStats(pCsr, pExpr);
121729    if( rc==SQLITE_OK ){
121730      assert( pExpr->aMI );
121731      for(iCol=0; iCol<pTab->nColumn; iCol++){
121732        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
121733        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
121734      }
121735    }
121736  }
121737
121738  return rc;
121739}
121740
121741/*
121742** The expression pExpr passed as the second argument to this function
121743** must be of type FTSQUERY_PHRASE.
121744**
121745** The returned value is either NULL or a pointer to a buffer containing
121746** a position-list indicating the occurrences of the phrase in column iCol
121747** of the current row.
121748**
121749** More specifically, the returned buffer contains 1 varint for each
121750** occurence of the phrase in the column, stored using the normal (delta+2)
121751** compression and is terminated by either an 0x01 or 0x00 byte. For example,
121752** if the requested column contains "a b X c d X X" and the position-list
121753** for 'X' is requested, the buffer returned may contain:
121754**
121755**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
121756**
121757** This function works regardless of whether or not the phrase is deferred,
121758** incremental, or neither.
121759*/
121760SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(
121761  Fts3Cursor *pCsr,               /* FTS3 cursor object */
121762  Fts3Expr *pExpr,                /* Phrase to return doclist for */
121763  int iCol                        /* Column to return position list for */
121764){
121765  Fts3Phrase *pPhrase = pExpr->pPhrase;
121766  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121767  char *pIter = pPhrase->doclist.pList;
121768  int iThis;
121769
121770  assert( iCol>=0 && iCol<pTab->nColumn );
121771  if( !pIter
121772   || pExpr->bEof
121773   || pExpr->iDocid!=pCsr->iPrevId
121774   || (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol)
121775  ){
121776    return 0;
121777  }
121778
121779  assert( pPhrase->doclist.nList>0 );
121780  if( *pIter==0x01 ){
121781    pIter++;
121782    pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
121783  }else{
121784    iThis = 0;
121785  }
121786  while( iThis<iCol ){
121787    fts3ColumnlistCopy(0, &pIter);
121788    if( *pIter==0x00 ) return 0;
121789    pIter++;
121790    pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
121791  }
121792
121793  return ((iCol==iThis)?pIter:0);
121794}
121795
121796/*
121797** Free all components of the Fts3Phrase structure that were allocated by
121798** the eval module. Specifically, this means to free:
121799**
121800**   * the contents of pPhrase->doclist, and
121801**   * any Fts3MultiSegReader objects held by phrase tokens.
121802*/
121803SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
121804  if( pPhrase ){
121805    int i;
121806    sqlite3_free(pPhrase->doclist.aAll);
121807    fts3EvalInvalidatePoslist(pPhrase);
121808    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
121809    for(i=0; i<pPhrase->nToken; i++){
121810      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
121811      pPhrase->aToken[i].pSegcsr = 0;
121812    }
121813  }
121814}
121815
121816/*
121817** Return SQLITE_CORRUPT_VTAB.
121818*/
121819#ifdef SQLITE_DEBUG
121820SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
121821  return SQLITE_CORRUPT_VTAB;
121822}
121823#endif
121824
121825#if !SQLITE_CORE
121826/*
121827** Initialize API pointer table, if required.
121828*/
121829SQLITE_API int sqlite3_extension_init(
121830  sqlite3 *db,
121831  char **pzErrMsg,
121832  const sqlite3_api_routines *pApi
121833){
121834  SQLITE_EXTENSION_INIT2(pApi)
121835  return sqlite3Fts3Init(db);
121836}
121837#endif
121838
121839#endif
121840
121841/************** End of fts3.c ************************************************/
121842/************** Begin file fts3_aux.c ****************************************/
121843/*
121844** 2011 Jan 27
121845**
121846** The author disclaims copyright to this source code.  In place of
121847** a legal notice, here is a blessing:
121848**
121849**    May you do good and not evil.
121850**    May you find forgiveness for yourself and forgive others.
121851**    May you share freely, never taking more than you give.
121852**
121853******************************************************************************
121854**
121855*/
121856#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
121857
121858/* #include <string.h> */
121859/* #include <assert.h> */
121860
121861typedef struct Fts3auxTable Fts3auxTable;
121862typedef struct Fts3auxCursor Fts3auxCursor;
121863
121864struct Fts3auxTable {
121865  sqlite3_vtab base;              /* Base class used by SQLite core */
121866  Fts3Table *pFts3Tab;
121867};
121868
121869struct Fts3auxCursor {
121870  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
121871  Fts3MultiSegReader csr;        /* Must be right after "base" */
121872  Fts3SegFilter filter;
121873  char *zStop;
121874  int nStop;                      /* Byte-length of string zStop */
121875  int isEof;                      /* True if cursor is at EOF */
121876  sqlite3_int64 iRowid;           /* Current rowid */
121877
121878  int iCol;                       /* Current value of 'col' column */
121879  int nStat;                      /* Size of aStat[] array */
121880  struct Fts3auxColstats {
121881    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
121882    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
121883  } *aStat;
121884};
121885
121886/*
121887** Schema of the terms table.
121888*/
121889#define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
121890
121891/*
121892** This function does all the work for both the xConnect and xCreate methods.
121893** These tables have no persistent representation of their own, so xConnect
121894** and xCreate are identical operations.
121895*/
121896static int fts3auxConnectMethod(
121897  sqlite3 *db,                    /* Database connection */
121898  void *pUnused,                  /* Unused */
121899  int argc,                       /* Number of elements in argv array */
121900  const char * const *argv,       /* xCreate/xConnect argument array */
121901  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
121902  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
121903){
121904  char const *zDb;                /* Name of database (e.g. "main") */
121905  char const *zFts3;              /* Name of fts3 table */
121906  int nDb;                        /* Result of strlen(zDb) */
121907  int nFts3;                      /* Result of strlen(zFts3) */
121908  int nByte;                      /* Bytes of space to allocate here */
121909  int rc;                         /* value returned by declare_vtab() */
121910  Fts3auxTable *p;                /* Virtual table object to return */
121911
121912  UNUSED_PARAMETER(pUnused);
121913
121914  /* The user should specify a single argument - the name of an fts3 table. */
121915  if( argc!=4 ){
121916    *pzErr = sqlite3_mprintf(
121917        "wrong number of arguments to fts4aux constructor"
121918    );
121919    return SQLITE_ERROR;
121920  }
121921
121922  zDb = argv[1];
121923  nDb = (int)strlen(zDb);
121924  zFts3 = argv[3];
121925  nFts3 = (int)strlen(zFts3);
121926
121927  rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
121928  if( rc!=SQLITE_OK ) return rc;
121929
121930  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
121931  p = (Fts3auxTable *)sqlite3_malloc(nByte);
121932  if( !p ) return SQLITE_NOMEM;
121933  memset(p, 0, nByte);
121934
121935  p->pFts3Tab = (Fts3Table *)&p[1];
121936  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
121937  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
121938  p->pFts3Tab->db = db;
121939  p->pFts3Tab->nIndex = 1;
121940
121941  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
121942  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
121943  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
121944
121945  *ppVtab = (sqlite3_vtab *)p;
121946  return SQLITE_OK;
121947}
121948
121949/*
121950** This function does the work for both the xDisconnect and xDestroy methods.
121951** These tables have no persistent representation of their own, so xDisconnect
121952** and xDestroy are identical operations.
121953*/
121954static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
121955  Fts3auxTable *p = (Fts3auxTable *)pVtab;
121956  Fts3Table *pFts3 = p->pFts3Tab;
121957  int i;
121958
121959  /* Free any prepared statements held */
121960  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
121961    sqlite3_finalize(pFts3->aStmt[i]);
121962  }
121963  sqlite3_free(pFts3->zSegmentsTbl);
121964  sqlite3_free(p);
121965  return SQLITE_OK;
121966}
121967
121968#define FTS4AUX_EQ_CONSTRAINT 1
121969#define FTS4AUX_GE_CONSTRAINT 2
121970#define FTS4AUX_LE_CONSTRAINT 4
121971
121972/*
121973** xBestIndex - Analyze a WHERE and ORDER BY clause.
121974*/
121975static int fts3auxBestIndexMethod(
121976  sqlite3_vtab *pVTab,
121977  sqlite3_index_info *pInfo
121978){
121979  int i;
121980  int iEq = -1;
121981  int iGe = -1;
121982  int iLe = -1;
121983
121984  UNUSED_PARAMETER(pVTab);
121985
121986  /* This vtab delivers always results in "ORDER BY term ASC" order. */
121987  if( pInfo->nOrderBy==1
121988   && pInfo->aOrderBy[0].iColumn==0
121989   && pInfo->aOrderBy[0].desc==0
121990  ){
121991    pInfo->orderByConsumed = 1;
121992  }
121993
121994  /* Search for equality and range constraints on the "term" column. */
121995  for(i=0; i<pInfo->nConstraint; i++){
121996    if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
121997      int op = pInfo->aConstraint[i].op;
121998      if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
121999      if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
122000      if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
122001      if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
122002      if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
122003    }
122004  }
122005
122006  if( iEq>=0 ){
122007    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
122008    pInfo->aConstraintUsage[iEq].argvIndex = 1;
122009    pInfo->estimatedCost = 5;
122010  }else{
122011    pInfo->idxNum = 0;
122012    pInfo->estimatedCost = 20000;
122013    if( iGe>=0 ){
122014      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
122015      pInfo->aConstraintUsage[iGe].argvIndex = 1;
122016      pInfo->estimatedCost /= 2;
122017    }
122018    if( iLe>=0 ){
122019      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
122020      pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
122021      pInfo->estimatedCost /= 2;
122022    }
122023  }
122024
122025  return SQLITE_OK;
122026}
122027
122028/*
122029** xOpen - Open a cursor.
122030*/
122031static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
122032  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
122033
122034  UNUSED_PARAMETER(pVTab);
122035
122036  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
122037  if( !pCsr ) return SQLITE_NOMEM;
122038  memset(pCsr, 0, sizeof(Fts3auxCursor));
122039
122040  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
122041  return SQLITE_OK;
122042}
122043
122044/*
122045** xClose - Close a cursor.
122046*/
122047static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
122048  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
122049  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122050
122051  sqlite3Fts3SegmentsClose(pFts3);
122052  sqlite3Fts3SegReaderFinish(&pCsr->csr);
122053  sqlite3_free((void *)pCsr->filter.zTerm);
122054  sqlite3_free(pCsr->zStop);
122055  sqlite3_free(pCsr->aStat);
122056  sqlite3_free(pCsr);
122057  return SQLITE_OK;
122058}
122059
122060static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
122061  if( nSize>pCsr->nStat ){
122062    struct Fts3auxColstats *aNew;
122063    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
122064        sizeof(struct Fts3auxColstats) * nSize
122065    );
122066    if( aNew==0 ) return SQLITE_NOMEM;
122067    memset(&aNew[pCsr->nStat], 0,
122068        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
122069    );
122070    pCsr->aStat = aNew;
122071    pCsr->nStat = nSize;
122072  }
122073  return SQLITE_OK;
122074}
122075
122076/*
122077** xNext - Advance the cursor to the next row, if any.
122078*/
122079static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
122080  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122081  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
122082  int rc;
122083
122084  /* Increment our pretend rowid value. */
122085  pCsr->iRowid++;
122086
122087  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
122088    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
122089  }
122090
122091  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
122092  if( rc==SQLITE_ROW ){
122093    int i = 0;
122094    int nDoclist = pCsr->csr.nDoclist;
122095    char *aDoclist = pCsr->csr.aDoclist;
122096    int iCol;
122097
122098    int eState = 0;
122099
122100    if( pCsr->zStop ){
122101      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
122102      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
122103      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
122104        pCsr->isEof = 1;
122105        return SQLITE_OK;
122106      }
122107    }
122108
122109    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
122110    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
122111    iCol = 0;
122112
122113    while( i<nDoclist ){
122114      sqlite3_int64 v = 0;
122115
122116      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
122117      switch( eState ){
122118        /* State 0. In this state the integer just read was a docid. */
122119        case 0:
122120          pCsr->aStat[0].nDoc++;
122121          eState = 1;
122122          iCol = 0;
122123          break;
122124
122125        /* State 1. In this state we are expecting either a 1, indicating
122126        ** that the following integer will be a column number, or the
122127        ** start of a position list for column 0.
122128        **
122129        ** The only difference between state 1 and state 2 is that if the
122130        ** integer encountered in state 1 is not 0 or 1, then we need to
122131        ** increment the column 0 "nDoc" count for this term.
122132        */
122133        case 1:
122134          assert( iCol==0 );
122135          if( v>1 ){
122136            pCsr->aStat[1].nDoc++;
122137          }
122138          eState = 2;
122139          /* fall through */
122140
122141        case 2:
122142          if( v==0 ){       /* 0x00. Next integer will be a docid. */
122143            eState = 0;
122144          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
122145            eState = 3;
122146          }else{            /* 2 or greater. A position. */
122147            pCsr->aStat[iCol+1].nOcc++;
122148            pCsr->aStat[0].nOcc++;
122149          }
122150          break;
122151
122152        /* State 3. The integer just read is a column number. */
122153        default: assert( eState==3 );
122154          iCol = (int)v;
122155          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
122156          pCsr->aStat[iCol+1].nDoc++;
122157          eState = 2;
122158          break;
122159      }
122160    }
122161
122162    pCsr->iCol = 0;
122163    rc = SQLITE_OK;
122164  }else{
122165    pCsr->isEof = 1;
122166  }
122167  return rc;
122168}
122169
122170/*
122171** xFilter - Initialize a cursor to point at the start of its data.
122172*/
122173static int fts3auxFilterMethod(
122174  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
122175  int idxNum,                     /* Strategy index */
122176  const char *idxStr,             /* Unused */
122177  int nVal,                       /* Number of elements in apVal */
122178  sqlite3_value **apVal           /* Arguments for the indexing scheme */
122179){
122180  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122181  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
122182  int rc;
122183  int isScan;
122184
122185  UNUSED_PARAMETER(nVal);
122186  UNUSED_PARAMETER(idxStr);
122187
122188  assert( idxStr==0 );
122189  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
122190       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
122191       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
122192  );
122193  isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
122194
122195  /* In case this cursor is being reused, close and zero it. */
122196  testcase(pCsr->filter.zTerm);
122197  sqlite3Fts3SegReaderFinish(&pCsr->csr);
122198  sqlite3_free((void *)pCsr->filter.zTerm);
122199  sqlite3_free(pCsr->aStat);
122200  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
122201
122202  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
122203  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
122204
122205  if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
122206    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
122207    if( zStr ){
122208      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
122209      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
122210      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
122211    }
122212  }
122213  if( idxNum&FTS4AUX_LE_CONSTRAINT ){
122214    int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
122215    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
122216    pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
122217    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
122218  }
122219
122220  rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
122221      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
122222  );
122223  if( rc==SQLITE_OK ){
122224    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
122225  }
122226
122227  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
122228  return rc;
122229}
122230
122231/*
122232** xEof - Return true if the cursor is at EOF, or false otherwise.
122233*/
122234static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
122235  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122236  return pCsr->isEof;
122237}
122238
122239/*
122240** xColumn - Return a column value.
122241*/
122242static int fts3auxColumnMethod(
122243  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
122244  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
122245  int iCol                        /* Index of column to read value from */
122246){
122247  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
122248
122249  assert( p->isEof==0 );
122250  if( iCol==0 ){        /* Column "term" */
122251    sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
122252  }else if( iCol==1 ){  /* Column "col" */
122253    if( p->iCol ){
122254      sqlite3_result_int(pContext, p->iCol-1);
122255    }else{
122256      sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
122257    }
122258  }else if( iCol==2 ){  /* Column "documents" */
122259    sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
122260  }else{                /* Column "occurrences" */
122261    sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
122262  }
122263
122264  return SQLITE_OK;
122265}
122266
122267/*
122268** xRowid - Return the current rowid for the cursor.
122269*/
122270static int fts3auxRowidMethod(
122271  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
122272  sqlite_int64 *pRowid            /* OUT: Rowid value */
122273){
122274  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122275  *pRowid = pCsr->iRowid;
122276  return SQLITE_OK;
122277}
122278
122279/*
122280** Register the fts3aux module with database connection db. Return SQLITE_OK
122281** if successful or an error code if sqlite3_create_module() fails.
122282*/
122283SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
122284  static const sqlite3_module fts3aux_module = {
122285     0,                           /* iVersion      */
122286     fts3auxConnectMethod,        /* xCreate       */
122287     fts3auxConnectMethod,        /* xConnect      */
122288     fts3auxBestIndexMethod,      /* xBestIndex    */
122289     fts3auxDisconnectMethod,     /* xDisconnect   */
122290     fts3auxDisconnectMethod,     /* xDestroy      */
122291     fts3auxOpenMethod,           /* xOpen         */
122292     fts3auxCloseMethod,          /* xClose        */
122293     fts3auxFilterMethod,         /* xFilter       */
122294     fts3auxNextMethod,           /* xNext         */
122295     fts3auxEofMethod,            /* xEof          */
122296     fts3auxColumnMethod,         /* xColumn       */
122297     fts3auxRowidMethod,          /* xRowid        */
122298     0,                           /* xUpdate       */
122299     0,                           /* xBegin        */
122300     0,                           /* xSync         */
122301     0,                           /* xCommit       */
122302     0,                           /* xRollback     */
122303     0,                           /* xFindFunction */
122304     0,                           /* xRename       */
122305     0,                           /* xSavepoint    */
122306     0,                           /* xRelease      */
122307     0                            /* xRollbackTo   */
122308  };
122309  int rc;                         /* Return code */
122310
122311  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
122312  return rc;
122313}
122314
122315#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
122316
122317/************** End of fts3_aux.c ********************************************/
122318/************** Begin file fts3_expr.c ***************************************/
122319/*
122320** 2008 Nov 28
122321**
122322** The author disclaims copyright to this source code.  In place of
122323** a legal notice, here is a blessing:
122324**
122325**    May you do good and not evil.
122326**    May you find forgiveness for yourself and forgive others.
122327**    May you share freely, never taking more than you give.
122328**
122329******************************************************************************
122330**
122331** This module contains code that implements a parser for fts3 query strings
122332** (the right-hand argument to the MATCH operator). Because the supported
122333** syntax is relatively simple, the whole tokenizer/parser system is
122334** hand-coded.
122335*/
122336#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122337
122338/*
122339** By default, this module parses the legacy syntax that has been
122340** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
122341** is defined, then it uses the new syntax. The differences between
122342** the new and the old syntaxes are:
122343**
122344**  a) The new syntax supports parenthesis. The old does not.
122345**
122346**  b) The new syntax supports the AND and NOT operators. The old does not.
122347**
122348**  c) The old syntax supports the "-" token qualifier. This is not
122349**     supported by the new syntax (it is replaced by the NOT operator).
122350**
122351**  d) When using the old syntax, the OR operator has a greater precedence
122352**     than an implicit AND. When using the new, both implicity and explicit
122353**     AND operators have a higher precedence than OR.
122354**
122355** If compiled with SQLITE_TEST defined, then this module exports the
122356** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
122357** to zero causes the module to use the old syntax. If it is set to
122358** non-zero the new syntax is activated. This is so both syntaxes can
122359** be tested using a single build of testfixture.
122360**
122361** The following describes the syntax supported by the fts3 MATCH
122362** operator in a similar format to that used by the lemon parser
122363** generator. This module does not use actually lemon, it uses a
122364** custom parser.
122365**
122366**   query ::= andexpr (OR andexpr)*.
122367**
122368**   andexpr ::= notexpr (AND? notexpr)*.
122369**
122370**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
122371**   notexpr ::= LP query RP.
122372**
122373**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
122374**
122375**   distance_opt ::= .
122376**   distance_opt ::= / INTEGER.
122377**
122378**   phrase ::= TOKEN.
122379**   phrase ::= COLUMN:TOKEN.
122380**   phrase ::= "TOKEN TOKEN TOKEN...".
122381*/
122382
122383#ifdef SQLITE_TEST
122384SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
122385#else
122386# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
122387#  define sqlite3_fts3_enable_parentheses 1
122388# else
122389#  define sqlite3_fts3_enable_parentheses 0
122390# endif
122391#endif
122392
122393/*
122394** Default span for NEAR operators.
122395*/
122396#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
122397
122398/* #include <string.h> */
122399/* #include <assert.h> */
122400
122401/*
122402** isNot:
122403**   This variable is used by function getNextNode(). When getNextNode() is
122404**   called, it sets ParseContext.isNot to true if the 'next node' is a
122405**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
122406**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
122407**   zero.
122408*/
122409typedef struct ParseContext ParseContext;
122410struct ParseContext {
122411  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
122412  int iLangid;                        /* Language id used with tokenizer */
122413  const char **azCol;                 /* Array of column names for fts3 table */
122414  int bFts4;                          /* True to allow FTS4-only syntax */
122415  int nCol;                           /* Number of entries in azCol[] */
122416  int iDefaultCol;                    /* Default column to query */
122417  int isNot;                          /* True if getNextNode() sees a unary - */
122418  sqlite3_context *pCtx;              /* Write error message here */
122419  int nNest;                          /* Number of nested brackets */
122420};
122421
122422/*
122423** This function is equivalent to the standard isspace() function.
122424**
122425** The standard isspace() can be awkward to use safely, because although it
122426** is defined to accept an argument of type int, its behaviour when passed
122427** an integer that falls outside of the range of the unsigned char type
122428** is undefined (and sometimes, "undefined" means segfault). This wrapper
122429** is defined to accept an argument of type char, and always returns 0 for
122430** any values that fall outside of the range of the unsigned char type (i.e.
122431** negative values).
122432*/
122433static int fts3isspace(char c){
122434  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
122435}
122436
122437/*
122438** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
122439** zero the memory before returning a pointer to it. If unsuccessful,
122440** return NULL.
122441*/
122442static void *fts3MallocZero(int nByte){
122443  void *pRet = sqlite3_malloc(nByte);
122444  if( pRet ) memset(pRet, 0, nByte);
122445  return pRet;
122446}
122447
122448SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
122449  sqlite3_tokenizer *pTokenizer,
122450  int iLangid,
122451  const char *z,
122452  int n,
122453  sqlite3_tokenizer_cursor **ppCsr
122454){
122455  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
122456  sqlite3_tokenizer_cursor *pCsr = 0;
122457  int rc;
122458
122459  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
122460  assert( rc==SQLITE_OK || pCsr==0 );
122461  if( rc==SQLITE_OK ){
122462    pCsr->pTokenizer = pTokenizer;
122463    if( pModule->iVersion>=1 ){
122464      rc = pModule->xLanguageid(pCsr, iLangid);
122465      if( rc!=SQLITE_OK ){
122466        pModule->xClose(pCsr);
122467        pCsr = 0;
122468      }
122469    }
122470  }
122471  *ppCsr = pCsr;
122472  return rc;
122473}
122474
122475
122476/*
122477** Extract the next token from buffer z (length n) using the tokenizer
122478** and other information (column names etc.) in pParse. Create an Fts3Expr
122479** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
122480** single token and set *ppExpr to point to it. If the end of the buffer is
122481** reached before a token is found, set *ppExpr to zero. It is the
122482** responsibility of the caller to eventually deallocate the allocated
122483** Fts3Expr structure (if any) by passing it to sqlite3_free().
122484**
122485** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
122486** fails.
122487*/
122488static int getNextToken(
122489  ParseContext *pParse,                   /* fts3 query parse context */
122490  int iCol,                               /* Value for Fts3Phrase.iColumn */
122491  const char *z, int n,                   /* Input string */
122492  Fts3Expr **ppExpr,                      /* OUT: expression */
122493  int *pnConsumed                         /* OUT: Number of bytes consumed */
122494){
122495  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
122496  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
122497  int rc;
122498  sqlite3_tokenizer_cursor *pCursor;
122499  Fts3Expr *pRet = 0;
122500  int nConsumed = 0;
122501
122502  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
122503  if( rc==SQLITE_OK ){
122504    const char *zToken;
122505    int nToken, iStart, iEnd, iPosition;
122506    int nByte;                               /* total space to allocate */
122507
122508    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
122509    if( rc==SQLITE_OK ){
122510      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
122511      pRet = (Fts3Expr *)fts3MallocZero(nByte);
122512      if( !pRet ){
122513        rc = SQLITE_NOMEM;
122514      }else{
122515        pRet->eType = FTSQUERY_PHRASE;
122516        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
122517        pRet->pPhrase->nToken = 1;
122518        pRet->pPhrase->iColumn = iCol;
122519        pRet->pPhrase->aToken[0].n = nToken;
122520        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
122521        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
122522
122523        if( iEnd<n && z[iEnd]=='*' ){
122524          pRet->pPhrase->aToken[0].isPrefix = 1;
122525          iEnd++;
122526        }
122527
122528        while( 1 ){
122529          if( !sqlite3_fts3_enable_parentheses
122530           && iStart>0 && z[iStart-1]=='-'
122531          ){
122532            pParse->isNot = 1;
122533            iStart--;
122534          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
122535            pRet->pPhrase->aToken[0].bFirst = 1;
122536            iStart--;
122537          }else{
122538            break;
122539          }
122540        }
122541
122542      }
122543      nConsumed = iEnd;
122544    }
122545
122546    pModule->xClose(pCursor);
122547  }
122548
122549  *pnConsumed = nConsumed;
122550  *ppExpr = pRet;
122551  return rc;
122552}
122553
122554
122555/*
122556** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
122557** then free the old allocation.
122558*/
122559static void *fts3ReallocOrFree(void *pOrig, int nNew){
122560  void *pRet = sqlite3_realloc(pOrig, nNew);
122561  if( !pRet ){
122562    sqlite3_free(pOrig);
122563  }
122564  return pRet;
122565}
122566
122567/*
122568** Buffer zInput, length nInput, contains the contents of a quoted string
122569** that appeared as part of an fts3 query expression. Neither quote character
122570** is included in the buffer. This function attempts to tokenize the entire
122571** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
122572** containing the results.
122573**
122574** If successful, SQLITE_OK is returned and *ppExpr set to point at the
122575** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
122576** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
122577** to 0.
122578*/
122579static int getNextString(
122580  ParseContext *pParse,                   /* fts3 query parse context */
122581  const char *zInput, int nInput,         /* Input string */
122582  Fts3Expr **ppExpr                       /* OUT: expression */
122583){
122584  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
122585  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
122586  int rc;
122587  Fts3Expr *p = 0;
122588  sqlite3_tokenizer_cursor *pCursor = 0;
122589  char *zTemp = 0;
122590  int nTemp = 0;
122591
122592  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
122593  int nToken = 0;
122594
122595  /* The final Fts3Expr data structure, including the Fts3Phrase,
122596  ** Fts3PhraseToken structures token buffers are all stored as a single
122597  ** allocation so that the expression can be freed with a single call to
122598  ** sqlite3_free(). Setting this up requires a two pass approach.
122599  **
122600  ** The first pass, in the block below, uses a tokenizer cursor to iterate
122601  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
122602  ** to assemble data in two dynamic buffers:
122603  **
122604  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
122605  **             structure, followed by the array of Fts3PhraseToken
122606  **             structures. This pass only populates the Fts3PhraseToken array.
122607  **
122608  **   Buffer zTemp: Contains copies of all tokens.
122609  **
122610  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
122611  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
122612  ** structures.
122613  */
122614  rc = sqlite3Fts3OpenTokenizer(
122615      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
122616  if( rc==SQLITE_OK ){
122617    int ii;
122618    for(ii=0; rc==SQLITE_OK; ii++){
122619      const char *zByte;
122620      int nByte, iBegin, iEnd, iPos;
122621      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
122622      if( rc==SQLITE_OK ){
122623        Fts3PhraseToken *pToken;
122624
122625        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
122626        if( !p ) goto no_mem;
122627
122628        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
122629        if( !zTemp ) goto no_mem;
122630
122631        assert( nToken==ii );
122632        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
122633        memset(pToken, 0, sizeof(Fts3PhraseToken));
122634
122635        memcpy(&zTemp[nTemp], zByte, nByte);
122636        nTemp += nByte;
122637
122638        pToken->n = nByte;
122639        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
122640        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
122641        nToken = ii+1;
122642      }
122643    }
122644
122645    pModule->xClose(pCursor);
122646    pCursor = 0;
122647  }
122648
122649  if( rc==SQLITE_DONE ){
122650    int jj;
122651    char *zBuf = 0;
122652
122653    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
122654    if( !p ) goto no_mem;
122655    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
122656    p->eType = FTSQUERY_PHRASE;
122657    p->pPhrase = (Fts3Phrase *)&p[1];
122658    p->pPhrase->iColumn = pParse->iDefaultCol;
122659    p->pPhrase->nToken = nToken;
122660
122661    zBuf = (char *)&p->pPhrase->aToken[nToken];
122662    if( zTemp ){
122663      memcpy(zBuf, zTemp, nTemp);
122664      sqlite3_free(zTemp);
122665    }else{
122666      assert( nTemp==0 );
122667    }
122668
122669    for(jj=0; jj<p->pPhrase->nToken; jj++){
122670      p->pPhrase->aToken[jj].z = zBuf;
122671      zBuf += p->pPhrase->aToken[jj].n;
122672    }
122673    rc = SQLITE_OK;
122674  }
122675
122676  *ppExpr = p;
122677  return rc;
122678no_mem:
122679
122680  if( pCursor ){
122681    pModule->xClose(pCursor);
122682  }
122683  sqlite3_free(zTemp);
122684  sqlite3_free(p);
122685  *ppExpr = 0;
122686  return SQLITE_NOMEM;
122687}
122688
122689/*
122690** Function getNextNode(), which is called by fts3ExprParse(), may itself
122691** call fts3ExprParse(). So this forward declaration is required.
122692*/
122693static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
122694
122695/*
122696** The output variable *ppExpr is populated with an allocated Fts3Expr
122697** structure, or set to 0 if the end of the input buffer is reached.
122698**
122699** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
122700** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
122701** If SQLITE_ERROR is returned, pContext is populated with an error message.
122702*/
122703static int getNextNode(
122704  ParseContext *pParse,                   /* fts3 query parse context */
122705  const char *z, int n,                   /* Input string */
122706  Fts3Expr **ppExpr,                      /* OUT: expression */
122707  int *pnConsumed                         /* OUT: Number of bytes consumed */
122708){
122709  static const struct Fts3Keyword {
122710    char *z;                              /* Keyword text */
122711    unsigned char n;                      /* Length of the keyword */
122712    unsigned char parenOnly;              /* Only valid in paren mode */
122713    unsigned char eType;                  /* Keyword code */
122714  } aKeyword[] = {
122715    { "OR" ,  2, 0, FTSQUERY_OR   },
122716    { "AND",  3, 1, FTSQUERY_AND  },
122717    { "NOT",  3, 1, FTSQUERY_NOT  },
122718    { "NEAR", 4, 0, FTSQUERY_NEAR }
122719  };
122720  int ii;
122721  int iCol;
122722  int iColLen;
122723  int rc;
122724  Fts3Expr *pRet = 0;
122725
122726  const char *zInput = z;
122727  int nInput = n;
122728
122729  pParse->isNot = 0;
122730
122731  /* Skip over any whitespace before checking for a keyword, an open or
122732  ** close bracket, or a quoted string.
122733  */
122734  while( nInput>0 && fts3isspace(*zInput) ){
122735    nInput--;
122736    zInput++;
122737  }
122738  if( nInput==0 ){
122739    return SQLITE_DONE;
122740  }
122741
122742  /* See if we are dealing with a keyword. */
122743  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
122744    const struct Fts3Keyword *pKey = &aKeyword[ii];
122745
122746    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
122747      continue;
122748    }
122749
122750    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
122751      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
122752      int nKey = pKey->n;
122753      char cNext;
122754
122755      /* If this is a "NEAR" keyword, check for an explicit nearness. */
122756      if( pKey->eType==FTSQUERY_NEAR ){
122757        assert( nKey==4 );
122758        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
122759          nNear = 0;
122760          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
122761            nNear = nNear * 10 + (zInput[nKey] - '0');
122762          }
122763        }
122764      }
122765
122766      /* At this point this is probably a keyword. But for that to be true,
122767      ** the next byte must contain either whitespace, an open or close
122768      ** parenthesis, a quote character, or EOF.
122769      */
122770      cNext = zInput[nKey];
122771      if( fts3isspace(cNext)
122772       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
122773      ){
122774        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
122775        if( !pRet ){
122776          return SQLITE_NOMEM;
122777        }
122778        pRet->eType = pKey->eType;
122779        pRet->nNear = nNear;
122780        *ppExpr = pRet;
122781        *pnConsumed = (int)((zInput - z) + nKey);
122782        return SQLITE_OK;
122783      }
122784
122785      /* Turns out that wasn't a keyword after all. This happens if the
122786      ** user has supplied a token such as "ORacle". Continue.
122787      */
122788    }
122789  }
122790
122791  /* Check for an open bracket. */
122792  if( sqlite3_fts3_enable_parentheses ){
122793    if( *zInput=='(' ){
122794      int nConsumed;
122795      pParse->nNest++;
122796      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
122797      if( rc==SQLITE_OK && !*ppExpr ){
122798        rc = SQLITE_DONE;
122799      }
122800      *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
122801      return rc;
122802    }
122803
122804    /* Check for a close bracket. */
122805    if( *zInput==')' ){
122806      pParse->nNest--;
122807      *pnConsumed = (int)((zInput - z) + 1);
122808      return SQLITE_DONE;
122809    }
122810  }
122811
122812  /* See if we are dealing with a quoted phrase. If this is the case, then
122813  ** search for the closing quote and pass the whole string to getNextString()
122814  ** for processing. This is easy to do, as fts3 has no syntax for escaping
122815  ** a quote character embedded in a string.
122816  */
122817  if( *zInput=='"' ){
122818    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
122819    *pnConsumed = (int)((zInput - z) + ii + 1);
122820    if( ii==nInput ){
122821      return SQLITE_ERROR;
122822    }
122823    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
122824  }
122825
122826
122827  /* If control flows to this point, this must be a regular token, or
122828  ** the end of the input. Read a regular token using the sqlite3_tokenizer
122829  ** interface. Before doing so, figure out if there is an explicit
122830  ** column specifier for the token.
122831  **
122832  ** TODO: Strangely, it is not possible to associate a column specifier
122833  ** with a quoted phrase, only with a single token. Not sure if this was
122834  ** an implementation artifact or an intentional decision when fts3 was
122835  ** first implemented. Whichever it was, this module duplicates the
122836  ** limitation.
122837  */
122838  iCol = pParse->iDefaultCol;
122839  iColLen = 0;
122840  for(ii=0; ii<pParse->nCol; ii++){
122841    const char *zStr = pParse->azCol[ii];
122842    int nStr = (int)strlen(zStr);
122843    if( nInput>nStr && zInput[nStr]==':'
122844     && sqlite3_strnicmp(zStr, zInput, nStr)==0
122845    ){
122846      iCol = ii;
122847      iColLen = (int)((zInput - z) + nStr + 1);
122848      break;
122849    }
122850  }
122851  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
122852  *pnConsumed += iColLen;
122853  return rc;
122854}
122855
122856/*
122857** The argument is an Fts3Expr structure for a binary operator (any type
122858** except an FTSQUERY_PHRASE). Return an integer value representing the
122859** precedence of the operator. Lower values have a higher precedence (i.e.
122860** group more tightly). For example, in the C language, the == operator
122861** groups more tightly than ||, and would therefore have a higher precedence.
122862**
122863** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
122864** is defined), the order of the operators in precedence from highest to
122865** lowest is:
122866**
122867**   NEAR
122868**   NOT
122869**   AND (including implicit ANDs)
122870**   OR
122871**
122872** Note that when using the old query syntax, the OR operator has a higher
122873** precedence than the AND operator.
122874*/
122875static int opPrecedence(Fts3Expr *p){
122876  assert( p->eType!=FTSQUERY_PHRASE );
122877  if( sqlite3_fts3_enable_parentheses ){
122878    return p->eType;
122879  }else if( p->eType==FTSQUERY_NEAR ){
122880    return 1;
122881  }else if( p->eType==FTSQUERY_OR ){
122882    return 2;
122883  }
122884  assert( p->eType==FTSQUERY_AND );
122885  return 3;
122886}
122887
122888/*
122889** Argument ppHead contains a pointer to the current head of a query
122890** expression tree being parsed. pPrev is the expression node most recently
122891** inserted into the tree. This function adds pNew, which is always a binary
122892** operator node, into the expression tree based on the relative precedence
122893** of pNew and the existing nodes of the tree. This may result in the head
122894** of the tree changing, in which case *ppHead is set to the new root node.
122895*/
122896static void insertBinaryOperator(
122897  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
122898  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
122899  Fts3Expr *pNew           /* New binary node to insert into expression tree */
122900){
122901  Fts3Expr *pSplit = pPrev;
122902  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
122903    pSplit = pSplit->pParent;
122904  }
122905
122906  if( pSplit->pParent ){
122907    assert( pSplit->pParent->pRight==pSplit );
122908    pSplit->pParent->pRight = pNew;
122909    pNew->pParent = pSplit->pParent;
122910  }else{
122911    *ppHead = pNew;
122912  }
122913  pNew->pLeft = pSplit;
122914  pSplit->pParent = pNew;
122915}
122916
122917/*
122918** Parse the fts3 query expression found in buffer z, length n. This function
122919** returns either when the end of the buffer is reached or an unmatched
122920** closing bracket - ')' - is encountered.
122921**
122922** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
122923** parsed form of the expression and *pnConsumed is set to the number of
122924** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
122925** (out of memory error) or SQLITE_ERROR (parse error) is returned.
122926*/
122927static int fts3ExprParse(
122928  ParseContext *pParse,                   /* fts3 query parse context */
122929  const char *z, int n,                   /* Text of MATCH query */
122930  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
122931  int *pnConsumed                         /* OUT: Number of bytes consumed */
122932){
122933  Fts3Expr *pRet = 0;
122934  Fts3Expr *pPrev = 0;
122935  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
122936  int nIn = n;
122937  const char *zIn = z;
122938  int rc = SQLITE_OK;
122939  int isRequirePhrase = 1;
122940
122941  while( rc==SQLITE_OK ){
122942    Fts3Expr *p = 0;
122943    int nByte = 0;
122944    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
122945    if( rc==SQLITE_OK ){
122946      int isPhrase;
122947
122948      if( !sqlite3_fts3_enable_parentheses
122949       && p->eType==FTSQUERY_PHRASE && pParse->isNot
122950      ){
122951        /* Create an implicit NOT operator. */
122952        Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
122953        if( !pNot ){
122954          sqlite3Fts3ExprFree(p);
122955          rc = SQLITE_NOMEM;
122956          goto exprparse_out;
122957        }
122958        pNot->eType = FTSQUERY_NOT;
122959        pNot->pRight = p;
122960        if( pNotBranch ){
122961          pNot->pLeft = pNotBranch;
122962        }
122963        pNotBranch = pNot;
122964        p = pPrev;
122965      }else{
122966        int eType = p->eType;
122967        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
122968
122969        /* The isRequirePhrase variable is set to true if a phrase or
122970        ** an expression contained in parenthesis is required. If a
122971        ** binary operator (AND, OR, NOT or NEAR) is encounted when
122972        ** isRequirePhrase is set, this is a syntax error.
122973        */
122974        if( !isPhrase && isRequirePhrase ){
122975          sqlite3Fts3ExprFree(p);
122976          rc = SQLITE_ERROR;
122977          goto exprparse_out;
122978        }
122979
122980        if( isPhrase && !isRequirePhrase ){
122981          /* Insert an implicit AND operator. */
122982          Fts3Expr *pAnd;
122983          assert( pRet && pPrev );
122984          pAnd = fts3MallocZero(sizeof(Fts3Expr));
122985          if( !pAnd ){
122986            sqlite3Fts3ExprFree(p);
122987            rc = SQLITE_NOMEM;
122988            goto exprparse_out;
122989          }
122990          pAnd->eType = FTSQUERY_AND;
122991          insertBinaryOperator(&pRet, pPrev, pAnd);
122992          pPrev = pAnd;
122993        }
122994
122995        /* This test catches attempts to make either operand of a NEAR
122996        ** operator something other than a phrase. For example, either of
122997        ** the following:
122998        **
122999        **    (bracketed expression) NEAR phrase
123000        **    phrase NEAR (bracketed expression)
123001        **
123002        ** Return an error in either case.
123003        */
123004        if( pPrev && (
123005            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
123006         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
123007        )){
123008          sqlite3Fts3ExprFree(p);
123009          rc = SQLITE_ERROR;
123010          goto exprparse_out;
123011        }
123012
123013        if( isPhrase ){
123014          if( pRet ){
123015            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
123016            pPrev->pRight = p;
123017            p->pParent = pPrev;
123018          }else{
123019            pRet = p;
123020          }
123021        }else{
123022          insertBinaryOperator(&pRet, pPrev, p);
123023        }
123024        isRequirePhrase = !isPhrase;
123025      }
123026      assert( nByte>0 );
123027    }
123028    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
123029    nIn -= nByte;
123030    zIn += nByte;
123031    pPrev = p;
123032  }
123033
123034  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
123035    rc = SQLITE_ERROR;
123036  }
123037
123038  if( rc==SQLITE_DONE ){
123039    rc = SQLITE_OK;
123040    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
123041      if( !pRet ){
123042        rc = SQLITE_ERROR;
123043      }else{
123044        Fts3Expr *pIter = pNotBranch;
123045        while( pIter->pLeft ){
123046          pIter = pIter->pLeft;
123047        }
123048        pIter->pLeft = pRet;
123049        pRet = pNotBranch;
123050      }
123051    }
123052  }
123053  *pnConsumed = n - nIn;
123054
123055exprparse_out:
123056  if( rc!=SQLITE_OK ){
123057    sqlite3Fts3ExprFree(pRet);
123058    sqlite3Fts3ExprFree(pNotBranch);
123059    pRet = 0;
123060  }
123061  *ppExpr = pRet;
123062  return rc;
123063}
123064
123065/*
123066** Parameters z and n contain a pointer to and length of a buffer containing
123067** an fts3 query expression, respectively. This function attempts to parse the
123068** query expression and create a tree of Fts3Expr structures representing the
123069** parsed expression. If successful, *ppExpr is set to point to the head
123070** of the parsed expression tree and SQLITE_OK is returned. If an error
123071** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
123072** error) is returned and *ppExpr is set to 0.
123073**
123074** If parameter n is a negative number, then z is assumed to point to a
123075** nul-terminated string and the length is determined using strlen().
123076**
123077** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
123078** use to normalize query tokens while parsing the expression. The azCol[]
123079** array, which is assumed to contain nCol entries, should contain the names
123080** of each column in the target fts3 table, in order from left to right.
123081** Column names must be nul-terminated strings.
123082**
123083** The iDefaultCol parameter should be passed the index of the table column
123084** that appears on the left-hand-side of the MATCH operator (the default
123085** column to match against for tokens for which a column name is not explicitly
123086** specified as part of the query string), or -1 if tokens may by default
123087** match any table column.
123088*/
123089SQLITE_PRIVATE int sqlite3Fts3ExprParse(
123090  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
123091  int iLangid,                        /* Language id for tokenizer */
123092  char **azCol,                       /* Array of column names for fts3 table */
123093  int bFts4,                          /* True to allow FTS4-only syntax */
123094  int nCol,                           /* Number of entries in azCol[] */
123095  int iDefaultCol,                    /* Default column to query */
123096  const char *z, int n,               /* Text of MATCH query */
123097  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
123098){
123099  int nParsed;
123100  int rc;
123101  ParseContext sParse;
123102
123103  memset(&sParse, 0, sizeof(ParseContext));
123104  sParse.pTokenizer = pTokenizer;
123105  sParse.iLangid = iLangid;
123106  sParse.azCol = (const char **)azCol;
123107  sParse.nCol = nCol;
123108  sParse.iDefaultCol = iDefaultCol;
123109  sParse.bFts4 = bFts4;
123110  if( z==0 ){
123111    *ppExpr = 0;
123112    return SQLITE_OK;
123113  }
123114  if( n<0 ){
123115    n = (int)strlen(z);
123116  }
123117  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
123118
123119  /* Check for mismatched parenthesis */
123120  if( rc==SQLITE_OK && sParse.nNest ){
123121    rc = SQLITE_ERROR;
123122    sqlite3Fts3ExprFree(*ppExpr);
123123    *ppExpr = 0;
123124  }
123125
123126  return rc;
123127}
123128
123129/*
123130** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
123131*/
123132SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
123133  if( p ){
123134    assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
123135    sqlite3Fts3ExprFree(p->pLeft);
123136    sqlite3Fts3ExprFree(p->pRight);
123137    sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
123138    sqlite3_free(p->aMI);
123139    sqlite3_free(p);
123140  }
123141}
123142
123143/****************************************************************************
123144*****************************************************************************
123145** Everything after this point is just test code.
123146*/
123147
123148#ifdef SQLITE_TEST
123149
123150/* #include <stdio.h> */
123151
123152/*
123153** Function to query the hash-table of tokenizers (see README.tokenizers).
123154*/
123155static int queryTestTokenizer(
123156  sqlite3 *db,
123157  const char *zName,
123158  const sqlite3_tokenizer_module **pp
123159){
123160  int rc;
123161  sqlite3_stmt *pStmt;
123162  const char zSql[] = "SELECT fts3_tokenizer(?)";
123163
123164  *pp = 0;
123165  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
123166  if( rc!=SQLITE_OK ){
123167    return rc;
123168  }
123169
123170  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
123171  if( SQLITE_ROW==sqlite3_step(pStmt) ){
123172    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
123173      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
123174    }
123175  }
123176
123177  return sqlite3_finalize(pStmt);
123178}
123179
123180/*
123181** Return a pointer to a buffer containing a text representation of the
123182** expression passed as the first argument. The buffer is obtained from
123183** sqlite3_malloc(). It is the responsibility of the caller to use
123184** sqlite3_free() to release the memory. If an OOM condition is encountered,
123185** NULL is returned.
123186**
123187** If the second argument is not NULL, then its contents are prepended to
123188** the returned expression text and then freed using sqlite3_free().
123189*/
123190static char *exprToString(Fts3Expr *pExpr, char *zBuf){
123191  switch( pExpr->eType ){
123192    case FTSQUERY_PHRASE: {
123193      Fts3Phrase *pPhrase = pExpr->pPhrase;
123194      int i;
123195      zBuf = sqlite3_mprintf(
123196          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
123197      for(i=0; zBuf && i<pPhrase->nToken; i++){
123198        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
123199            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
123200            (pPhrase->aToken[i].isPrefix?"+":"")
123201        );
123202      }
123203      return zBuf;
123204    }
123205
123206    case FTSQUERY_NEAR:
123207      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
123208      break;
123209    case FTSQUERY_NOT:
123210      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
123211      break;
123212    case FTSQUERY_AND:
123213      zBuf = sqlite3_mprintf("%zAND ", zBuf);
123214      break;
123215    case FTSQUERY_OR:
123216      zBuf = sqlite3_mprintf("%zOR ", zBuf);
123217      break;
123218  }
123219
123220  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
123221  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
123222  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
123223
123224  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
123225  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
123226
123227  return zBuf;
123228}
123229
123230/*
123231** This is the implementation of a scalar SQL function used to test the
123232** expression parser. It should be called as follows:
123233**
123234**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
123235**
123236** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
123237** to parse the query expression (see README.tokenizers). The second argument
123238** is the query expression to parse. Each subsequent argument is the name
123239** of a column of the fts3 table that the query expression may refer to.
123240** For example:
123241**
123242**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
123243*/
123244static void fts3ExprTest(
123245  sqlite3_context *context,
123246  int argc,
123247  sqlite3_value **argv
123248){
123249  sqlite3_tokenizer_module const *pModule = 0;
123250  sqlite3_tokenizer *pTokenizer = 0;
123251  int rc;
123252  char **azCol = 0;
123253  const char *zExpr;
123254  int nExpr;
123255  int nCol;
123256  int ii;
123257  Fts3Expr *pExpr;
123258  char *zBuf = 0;
123259  sqlite3 *db = sqlite3_context_db_handle(context);
123260
123261  if( argc<3 ){
123262    sqlite3_result_error(context,
123263        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
123264    );
123265    return;
123266  }
123267
123268  rc = queryTestTokenizer(db,
123269                          (const char *)sqlite3_value_text(argv[0]), &pModule);
123270  if( rc==SQLITE_NOMEM ){
123271    sqlite3_result_error_nomem(context);
123272    goto exprtest_out;
123273  }else if( !pModule ){
123274    sqlite3_result_error(context, "No such tokenizer module", -1);
123275    goto exprtest_out;
123276  }
123277
123278  rc = pModule->xCreate(0, 0, &pTokenizer);
123279  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
123280  if( rc==SQLITE_NOMEM ){
123281    sqlite3_result_error_nomem(context);
123282    goto exprtest_out;
123283  }
123284  pTokenizer->pModule = pModule;
123285
123286  zExpr = (const char *)sqlite3_value_text(argv[1]);
123287  nExpr = sqlite3_value_bytes(argv[1]);
123288  nCol = argc-2;
123289  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
123290  if( !azCol ){
123291    sqlite3_result_error_nomem(context);
123292    goto exprtest_out;
123293  }
123294  for(ii=0; ii<nCol; ii++){
123295    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
123296  }
123297
123298  rc = sqlite3Fts3ExprParse(
123299      pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
123300  );
123301  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
123302    sqlite3_result_error(context, "Error parsing expression", -1);
123303  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
123304    sqlite3_result_error_nomem(context);
123305  }else{
123306    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
123307    sqlite3_free(zBuf);
123308  }
123309
123310  sqlite3Fts3ExprFree(pExpr);
123311
123312exprtest_out:
123313  if( pModule && pTokenizer ){
123314    rc = pModule->xDestroy(pTokenizer);
123315  }
123316  sqlite3_free(azCol);
123317}
123318
123319/*
123320** Register the query expression parser test function fts3_exprtest()
123321** with database connection db.
123322*/
123323SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
123324  return sqlite3_create_function(
123325      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
123326  );
123327}
123328
123329#endif
123330#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
123331
123332/************** End of fts3_expr.c *******************************************/
123333/************** Begin file fts3_hash.c ***************************************/
123334/*
123335** 2001 September 22
123336**
123337** The author disclaims copyright to this source code.  In place of
123338** a legal notice, here is a blessing:
123339**
123340**    May you do good and not evil.
123341**    May you find forgiveness for yourself and forgive others.
123342**    May you share freely, never taking more than you give.
123343**
123344*************************************************************************
123345** This is the implementation of generic hash-tables used in SQLite.
123346** We've modified it slightly to serve as a standalone hash table
123347** implementation for the full-text indexing module.
123348*/
123349
123350/*
123351** The code in this file is only compiled if:
123352**
123353**     * The FTS3 module is being built as an extension
123354**       (in which case SQLITE_CORE is not defined), or
123355**
123356**     * The FTS3 module is being built into the core of
123357**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
123358*/
123359#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123360
123361/* #include <assert.h> */
123362/* #include <stdlib.h> */
123363/* #include <string.h> */
123364
123365
123366/*
123367** Malloc and Free functions
123368*/
123369static void *fts3HashMalloc(int n){
123370  void *p = sqlite3_malloc(n);
123371  if( p ){
123372    memset(p, 0, n);
123373  }
123374  return p;
123375}
123376static void fts3HashFree(void *p){
123377  sqlite3_free(p);
123378}
123379
123380/* Turn bulk memory into a hash table object by initializing the
123381** fields of the Hash structure.
123382**
123383** "pNew" is a pointer to the hash table that is to be initialized.
123384** keyClass is one of the constants
123385** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
123386** determines what kind of key the hash table will use.  "copyKey" is
123387** true if the hash table should make its own private copy of keys and
123388** false if it should just use the supplied pointer.
123389*/
123390SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
123391  assert( pNew!=0 );
123392  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
123393  pNew->keyClass = keyClass;
123394  pNew->copyKey = copyKey;
123395  pNew->first = 0;
123396  pNew->count = 0;
123397  pNew->htsize = 0;
123398  pNew->ht = 0;
123399}
123400
123401/* Remove all entries from a hash table.  Reclaim all memory.
123402** Call this routine to delete a hash table or to reset a hash table
123403** to the empty state.
123404*/
123405SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
123406  Fts3HashElem *elem;         /* For looping over all elements of the table */
123407
123408  assert( pH!=0 );
123409  elem = pH->first;
123410  pH->first = 0;
123411  fts3HashFree(pH->ht);
123412  pH->ht = 0;
123413  pH->htsize = 0;
123414  while( elem ){
123415    Fts3HashElem *next_elem = elem->next;
123416    if( pH->copyKey && elem->pKey ){
123417      fts3HashFree(elem->pKey);
123418    }
123419    fts3HashFree(elem);
123420    elem = next_elem;
123421  }
123422  pH->count = 0;
123423}
123424
123425/*
123426** Hash and comparison functions when the mode is FTS3_HASH_STRING
123427*/
123428static int fts3StrHash(const void *pKey, int nKey){
123429  const char *z = (const char *)pKey;
123430  int h = 0;
123431  if( nKey<=0 ) nKey = (int) strlen(z);
123432  while( nKey > 0  ){
123433    h = (h<<3) ^ h ^ *z++;
123434    nKey--;
123435  }
123436  return h & 0x7fffffff;
123437}
123438static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
123439  if( n1!=n2 ) return 1;
123440  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
123441}
123442
123443/*
123444** Hash and comparison functions when the mode is FTS3_HASH_BINARY
123445*/
123446static int fts3BinHash(const void *pKey, int nKey){
123447  int h = 0;
123448  const char *z = (const char *)pKey;
123449  while( nKey-- > 0 ){
123450    h = (h<<3) ^ h ^ *(z++);
123451  }
123452  return h & 0x7fffffff;
123453}
123454static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
123455  if( n1!=n2 ) return 1;
123456  return memcmp(pKey1,pKey2,n1);
123457}
123458
123459/*
123460** Return a pointer to the appropriate hash function given the key class.
123461**
123462** The C syntax in this function definition may be unfamilar to some
123463** programmers, so we provide the following additional explanation:
123464**
123465** The name of the function is "ftsHashFunction".  The function takes a
123466** single parameter "keyClass".  The return value of ftsHashFunction()
123467** is a pointer to another function.  Specifically, the return value
123468** of ftsHashFunction() is a pointer to a function that takes two parameters
123469** with types "const void*" and "int" and returns an "int".
123470*/
123471static int (*ftsHashFunction(int keyClass))(const void*,int){
123472  if( keyClass==FTS3_HASH_STRING ){
123473    return &fts3StrHash;
123474  }else{
123475    assert( keyClass==FTS3_HASH_BINARY );
123476    return &fts3BinHash;
123477  }
123478}
123479
123480/*
123481** Return a pointer to the appropriate hash function given the key class.
123482**
123483** For help in interpreted the obscure C code in the function definition,
123484** see the header comment on the previous function.
123485*/
123486static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
123487  if( keyClass==FTS3_HASH_STRING ){
123488    return &fts3StrCompare;
123489  }else{
123490    assert( keyClass==FTS3_HASH_BINARY );
123491    return &fts3BinCompare;
123492  }
123493}
123494
123495/* Link an element into the hash table
123496*/
123497static void fts3HashInsertElement(
123498  Fts3Hash *pH,            /* The complete hash table */
123499  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
123500  Fts3HashElem *pNew       /* The element to be inserted */
123501){
123502  Fts3HashElem *pHead;     /* First element already in pEntry */
123503  pHead = pEntry->chain;
123504  if( pHead ){
123505    pNew->next = pHead;
123506    pNew->prev = pHead->prev;
123507    if( pHead->prev ){ pHead->prev->next = pNew; }
123508    else             { pH->first = pNew; }
123509    pHead->prev = pNew;
123510  }else{
123511    pNew->next = pH->first;
123512    if( pH->first ){ pH->first->prev = pNew; }
123513    pNew->prev = 0;
123514    pH->first = pNew;
123515  }
123516  pEntry->count++;
123517  pEntry->chain = pNew;
123518}
123519
123520
123521/* Resize the hash table so that it cantains "new_size" buckets.
123522** "new_size" must be a power of 2.  The hash table might fail
123523** to resize if sqliteMalloc() fails.
123524**
123525** Return non-zero if a memory allocation error occurs.
123526*/
123527static int fts3Rehash(Fts3Hash *pH, int new_size){
123528  struct _fts3ht *new_ht;          /* The new hash table */
123529  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
123530  int (*xHash)(const void*,int);   /* The hash function */
123531
123532  assert( (new_size & (new_size-1))==0 );
123533  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
123534  if( new_ht==0 ) return 1;
123535  fts3HashFree(pH->ht);
123536  pH->ht = new_ht;
123537  pH->htsize = new_size;
123538  xHash = ftsHashFunction(pH->keyClass);
123539  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
123540    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
123541    next_elem = elem->next;
123542    fts3HashInsertElement(pH, &new_ht[h], elem);
123543  }
123544  return 0;
123545}
123546
123547/* This function (for internal use only) locates an element in an
123548** hash table that matches the given key.  The hash for this key has
123549** already been computed and is passed as the 4th parameter.
123550*/
123551static Fts3HashElem *fts3FindElementByHash(
123552  const Fts3Hash *pH, /* The pH to be searched */
123553  const void *pKey,   /* The key we are searching for */
123554  int nKey,
123555  int h               /* The hash for this key. */
123556){
123557  Fts3HashElem *elem;            /* Used to loop thru the element list */
123558  int count;                     /* Number of elements left to test */
123559  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
123560
123561  if( pH->ht ){
123562    struct _fts3ht *pEntry = &pH->ht[h];
123563    elem = pEntry->chain;
123564    count = pEntry->count;
123565    xCompare = ftsCompareFunction(pH->keyClass);
123566    while( count-- && elem ){
123567      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
123568        return elem;
123569      }
123570      elem = elem->next;
123571    }
123572  }
123573  return 0;
123574}
123575
123576/* Remove a single entry from the hash table given a pointer to that
123577** element and a hash on the element's key.
123578*/
123579static void fts3RemoveElementByHash(
123580  Fts3Hash *pH,         /* The pH containing "elem" */
123581  Fts3HashElem* elem,   /* The element to be removed from the pH */
123582  int h                 /* Hash value for the element */
123583){
123584  struct _fts3ht *pEntry;
123585  if( elem->prev ){
123586    elem->prev->next = elem->next;
123587  }else{
123588    pH->first = elem->next;
123589  }
123590  if( elem->next ){
123591    elem->next->prev = elem->prev;
123592  }
123593  pEntry = &pH->ht[h];
123594  if( pEntry->chain==elem ){
123595    pEntry->chain = elem->next;
123596  }
123597  pEntry->count--;
123598  if( pEntry->count<=0 ){
123599    pEntry->chain = 0;
123600  }
123601  if( pH->copyKey && elem->pKey ){
123602    fts3HashFree(elem->pKey);
123603  }
123604  fts3HashFree( elem );
123605  pH->count--;
123606  if( pH->count<=0 ){
123607    assert( pH->first==0 );
123608    assert( pH->count==0 );
123609    fts3HashClear(pH);
123610  }
123611}
123612
123613SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
123614  const Fts3Hash *pH,
123615  const void *pKey,
123616  int nKey
123617){
123618  int h;                          /* A hash on key */
123619  int (*xHash)(const void*,int);  /* The hash function */
123620
123621  if( pH==0 || pH->ht==0 ) return 0;
123622  xHash = ftsHashFunction(pH->keyClass);
123623  assert( xHash!=0 );
123624  h = (*xHash)(pKey,nKey);
123625  assert( (pH->htsize & (pH->htsize-1))==0 );
123626  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
123627}
123628
123629/*
123630** Attempt to locate an element of the hash table pH with a key
123631** that matches pKey,nKey.  Return the data for this element if it is
123632** found, or NULL if there is no match.
123633*/
123634SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
123635  Fts3HashElem *pElem;            /* The element that matches key (if any) */
123636
123637  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
123638  return pElem ? pElem->data : 0;
123639}
123640
123641/* Insert an element into the hash table pH.  The key is pKey,nKey
123642** and the data is "data".
123643**
123644** If no element exists with a matching key, then a new
123645** element is created.  A copy of the key is made if the copyKey
123646** flag is set.  NULL is returned.
123647**
123648** If another element already exists with the same key, then the
123649** new data replaces the old data and the old data is returned.
123650** The key is not copied in this instance.  If a malloc fails, then
123651** the new data is returned and the hash table is unchanged.
123652**
123653** If the "data" parameter to this function is NULL, then the
123654** element corresponding to "key" is removed from the hash table.
123655*/
123656SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
123657  Fts3Hash *pH,        /* The hash table to insert into */
123658  const void *pKey,    /* The key */
123659  int nKey,            /* Number of bytes in the key */
123660  void *data           /* The data */
123661){
123662  int hraw;                 /* Raw hash value of the key */
123663  int h;                    /* the hash of the key modulo hash table size */
123664  Fts3HashElem *elem;       /* Used to loop thru the element list */
123665  Fts3HashElem *new_elem;   /* New element added to the pH */
123666  int (*xHash)(const void*,int);  /* The hash function */
123667
123668  assert( pH!=0 );
123669  xHash = ftsHashFunction(pH->keyClass);
123670  assert( xHash!=0 );
123671  hraw = (*xHash)(pKey, nKey);
123672  assert( (pH->htsize & (pH->htsize-1))==0 );
123673  h = hraw & (pH->htsize-1);
123674  elem = fts3FindElementByHash(pH,pKey,nKey,h);
123675  if( elem ){
123676    void *old_data = elem->data;
123677    if( data==0 ){
123678      fts3RemoveElementByHash(pH,elem,h);
123679    }else{
123680      elem->data = data;
123681    }
123682    return old_data;
123683  }
123684  if( data==0 ) return 0;
123685  if( (pH->htsize==0 && fts3Rehash(pH,8))
123686   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
123687  ){
123688    pH->count = 0;
123689    return data;
123690  }
123691  assert( pH->htsize>0 );
123692  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
123693  if( new_elem==0 ) return data;
123694  if( pH->copyKey && pKey!=0 ){
123695    new_elem->pKey = fts3HashMalloc( nKey );
123696    if( new_elem->pKey==0 ){
123697      fts3HashFree(new_elem);
123698      return data;
123699    }
123700    memcpy((void*)new_elem->pKey, pKey, nKey);
123701  }else{
123702    new_elem->pKey = (void*)pKey;
123703  }
123704  new_elem->nKey = nKey;
123705  pH->count++;
123706  assert( pH->htsize>0 );
123707  assert( (pH->htsize & (pH->htsize-1))==0 );
123708  h = hraw & (pH->htsize-1);
123709  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
123710  new_elem->data = data;
123711  return 0;
123712}
123713
123714#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
123715
123716/************** End of fts3_hash.c *******************************************/
123717/************** Begin file fts3_porter.c *************************************/
123718/*
123719** 2006 September 30
123720**
123721** The author disclaims copyright to this source code.  In place of
123722** a legal notice, here is a blessing:
123723**
123724**    May you do good and not evil.
123725**    May you find forgiveness for yourself and forgive others.
123726**    May you share freely, never taking more than you give.
123727**
123728*************************************************************************
123729** Implementation of the full-text-search tokenizer that implements
123730** a Porter stemmer.
123731*/
123732
123733/*
123734** The code in this file is only compiled if:
123735**
123736**     * The FTS3 module is being built as an extension
123737**       (in which case SQLITE_CORE is not defined), or
123738**
123739**     * The FTS3 module is being built into the core of
123740**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
123741*/
123742#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123743
123744/* #include <assert.h> */
123745/* #include <stdlib.h> */
123746/* #include <stdio.h> */
123747/* #include <string.h> */
123748
123749
123750/*
123751** Class derived from sqlite3_tokenizer
123752*/
123753typedef struct porter_tokenizer {
123754  sqlite3_tokenizer base;      /* Base class */
123755} porter_tokenizer;
123756
123757/*
123758** Class derived from sqlite3_tokenizer_cursor
123759*/
123760typedef struct porter_tokenizer_cursor {
123761  sqlite3_tokenizer_cursor base;
123762  const char *zInput;          /* input we are tokenizing */
123763  int nInput;                  /* size of the input */
123764  int iOffset;                 /* current position in zInput */
123765  int iToken;                  /* index of next token to be returned */
123766  char *zToken;                /* storage for current token */
123767  int nAllocated;              /* space allocated to zToken buffer */
123768} porter_tokenizer_cursor;
123769
123770
123771/*
123772** Create a new tokenizer instance.
123773*/
123774static int porterCreate(
123775  int argc, const char * const *argv,
123776  sqlite3_tokenizer **ppTokenizer
123777){
123778  porter_tokenizer *t;
123779
123780  UNUSED_PARAMETER(argc);
123781  UNUSED_PARAMETER(argv);
123782
123783  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
123784  if( t==NULL ) return SQLITE_NOMEM;
123785  memset(t, 0, sizeof(*t));
123786  *ppTokenizer = &t->base;
123787  return SQLITE_OK;
123788}
123789
123790/*
123791** Destroy a tokenizer
123792*/
123793static int porterDestroy(sqlite3_tokenizer *pTokenizer){
123794  sqlite3_free(pTokenizer);
123795  return SQLITE_OK;
123796}
123797
123798/*
123799** Prepare to begin tokenizing a particular string.  The input
123800** string to be tokenized is zInput[0..nInput-1].  A cursor
123801** used to incrementally tokenize this string is returned in
123802** *ppCursor.
123803*/
123804static int porterOpen(
123805  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
123806  const char *zInput, int nInput,        /* String to be tokenized */
123807  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
123808){
123809  porter_tokenizer_cursor *c;
123810
123811  UNUSED_PARAMETER(pTokenizer);
123812
123813  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
123814  if( c==NULL ) return SQLITE_NOMEM;
123815
123816  c->zInput = zInput;
123817  if( zInput==0 ){
123818    c->nInput = 0;
123819  }else if( nInput<0 ){
123820    c->nInput = (int)strlen(zInput);
123821  }else{
123822    c->nInput = nInput;
123823  }
123824  c->iOffset = 0;                 /* start tokenizing at the beginning */
123825  c->iToken = 0;
123826  c->zToken = NULL;               /* no space allocated, yet. */
123827  c->nAllocated = 0;
123828
123829  *ppCursor = &c->base;
123830  return SQLITE_OK;
123831}
123832
123833/*
123834** Close a tokenization cursor previously opened by a call to
123835** porterOpen() above.
123836*/
123837static int porterClose(sqlite3_tokenizer_cursor *pCursor){
123838  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
123839  sqlite3_free(c->zToken);
123840  sqlite3_free(c);
123841  return SQLITE_OK;
123842}
123843/*
123844** Vowel or consonant
123845*/
123846static const char cType[] = {
123847   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
123848   1, 1, 1, 2, 1
123849};
123850
123851/*
123852** isConsonant() and isVowel() determine if their first character in
123853** the string they point to is a consonant or a vowel, according
123854** to Porter ruls.
123855**
123856** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
123857** 'Y' is a consonant unless it follows another consonant,
123858** in which case it is a vowel.
123859**
123860** In these routine, the letters are in reverse order.  So the 'y' rule
123861** is that 'y' is a consonant unless it is followed by another
123862** consonent.
123863*/
123864static int isVowel(const char*);
123865static int isConsonant(const char *z){
123866  int j;
123867  char x = *z;
123868  if( x==0 ) return 0;
123869  assert( x>='a' && x<='z' );
123870  j = cType[x-'a'];
123871  if( j<2 ) return j;
123872  return z[1]==0 || isVowel(z + 1);
123873}
123874static int isVowel(const char *z){
123875  int j;
123876  char x = *z;
123877  if( x==0 ) return 0;
123878  assert( x>='a' && x<='z' );
123879  j = cType[x-'a'];
123880  if( j<2 ) return 1-j;
123881  return isConsonant(z + 1);
123882}
123883
123884/*
123885** Let any sequence of one or more vowels be represented by V and let
123886** C be sequence of one or more consonants.  Then every word can be
123887** represented as:
123888**
123889**           [C] (VC){m} [V]
123890**
123891** In prose:  A word is an optional consonant followed by zero or
123892** vowel-consonant pairs followed by an optional vowel.  "m" is the
123893** number of vowel consonant pairs.  This routine computes the value
123894** of m for the first i bytes of a word.
123895**
123896** Return true if the m-value for z is 1 or more.  In other words,
123897** return true if z contains at least one vowel that is followed
123898** by a consonant.
123899**
123900** In this routine z[] is in reverse order.  So we are really looking
123901** for an instance of of a consonant followed by a vowel.
123902*/
123903static int m_gt_0(const char *z){
123904  while( isVowel(z) ){ z++; }
123905  if( *z==0 ) return 0;
123906  while( isConsonant(z) ){ z++; }
123907  return *z!=0;
123908}
123909
123910/* Like mgt0 above except we are looking for a value of m which is
123911** exactly 1
123912*/
123913static int m_eq_1(const char *z){
123914  while( isVowel(z) ){ z++; }
123915  if( *z==0 ) return 0;
123916  while( isConsonant(z) ){ z++; }
123917  if( *z==0 ) return 0;
123918  while( isVowel(z) ){ z++; }
123919  if( *z==0 ) return 1;
123920  while( isConsonant(z) ){ z++; }
123921  return *z==0;
123922}
123923
123924/* Like mgt0 above except we are looking for a value of m>1 instead
123925** or m>0
123926*/
123927static int m_gt_1(const char *z){
123928  while( isVowel(z) ){ z++; }
123929  if( *z==0 ) return 0;
123930  while( isConsonant(z) ){ z++; }
123931  if( *z==0 ) return 0;
123932  while( isVowel(z) ){ z++; }
123933  if( *z==0 ) return 0;
123934  while( isConsonant(z) ){ z++; }
123935  return *z!=0;
123936}
123937
123938/*
123939** Return TRUE if there is a vowel anywhere within z[0..n-1]
123940*/
123941static int hasVowel(const char *z){
123942  while( isConsonant(z) ){ z++; }
123943  return *z!=0;
123944}
123945
123946/*
123947** Return TRUE if the word ends in a double consonant.
123948**
123949** The text is reversed here. So we are really looking at
123950** the first two characters of z[].
123951*/
123952static int doubleConsonant(const char *z){
123953  return isConsonant(z) && z[0]==z[1];
123954}
123955
123956/*
123957** Return TRUE if the word ends with three letters which
123958** are consonant-vowel-consonent and where the final consonant
123959** is not 'w', 'x', or 'y'.
123960**
123961** The word is reversed here.  So we are really checking the
123962** first three letters and the first one cannot be in [wxy].
123963*/
123964static int star_oh(const char *z){
123965  return
123966    isConsonant(z) &&
123967    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
123968    isVowel(z+1) &&
123969    isConsonant(z+2);
123970}
123971
123972/*
123973** If the word ends with zFrom and xCond() is true for the stem
123974** of the word that preceeds the zFrom ending, then change the
123975** ending to zTo.
123976**
123977** The input word *pz and zFrom are both in reverse order.  zTo
123978** is in normal order.
123979**
123980** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
123981** match.  Not that TRUE is returned even if xCond() fails and
123982** no substitution occurs.
123983*/
123984static int stem(
123985  char **pz,             /* The word being stemmed (Reversed) */
123986  const char *zFrom,     /* If the ending matches this... (Reversed) */
123987  const char *zTo,       /* ... change the ending to this (not reversed) */
123988  int (*xCond)(const char*)   /* Condition that must be true */
123989){
123990  char *z = *pz;
123991  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
123992  if( *zFrom!=0 ) return 0;
123993  if( xCond && !xCond(z) ) return 1;
123994  while( *zTo ){
123995    *(--z) = *(zTo++);
123996  }
123997  *pz = z;
123998  return 1;
123999}
124000
124001/*
124002** This is the fallback stemmer used when the porter stemmer is
124003** inappropriate.  The input word is copied into the output with
124004** US-ASCII case folding.  If the input word is too long (more
124005** than 20 bytes if it contains no digits or more than 6 bytes if
124006** it contains digits) then word is truncated to 20 or 6 bytes
124007** by taking 10 or 3 bytes from the beginning and end.
124008*/
124009static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
124010  int i, mx, j;
124011  int hasDigit = 0;
124012  for(i=0; i<nIn; i++){
124013    char c = zIn[i];
124014    if( c>='A' && c<='Z' ){
124015      zOut[i] = c - 'A' + 'a';
124016    }else{
124017      if( c>='0' && c<='9' ) hasDigit = 1;
124018      zOut[i] = c;
124019    }
124020  }
124021  mx = hasDigit ? 3 : 10;
124022  if( nIn>mx*2 ){
124023    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
124024      zOut[j] = zOut[i];
124025    }
124026    i = j;
124027  }
124028  zOut[i] = 0;
124029  *pnOut = i;
124030}
124031
124032
124033/*
124034** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
124035** zOut is at least big enough to hold nIn bytes.  Write the actual
124036** size of the output word (exclusive of the '\0' terminator) into *pnOut.
124037**
124038** Any upper-case characters in the US-ASCII character set ([A-Z])
124039** are converted to lower case.  Upper-case UTF characters are
124040** unchanged.
124041**
124042** Words that are longer than about 20 bytes are stemmed by retaining
124043** a few bytes from the beginning and the end of the word.  If the
124044** word contains digits, 3 bytes are taken from the beginning and
124045** 3 bytes from the end.  For long words without digits, 10 bytes
124046** are taken from each end.  US-ASCII case folding still applies.
124047**
124048** If the input word contains not digits but does characters not
124049** in [a-zA-Z] then no stemming is attempted and this routine just
124050** copies the input into the input into the output with US-ASCII
124051** case folding.
124052**
124053** Stemming never increases the length of the word.  So there is
124054** no chance of overflowing the zOut buffer.
124055*/
124056static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
124057  int i, j;
124058  char zReverse[28];
124059  char *z, *z2;
124060  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
124061    /* The word is too big or too small for the porter stemmer.
124062    ** Fallback to the copy stemmer */
124063    copy_stemmer(zIn, nIn, zOut, pnOut);
124064    return;
124065  }
124066  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
124067    char c = zIn[i];
124068    if( c>='A' && c<='Z' ){
124069      zReverse[j] = c + 'a' - 'A';
124070    }else if( c>='a' && c<='z' ){
124071      zReverse[j] = c;
124072    }else{
124073      /* The use of a character not in [a-zA-Z] means that we fallback
124074      ** to the copy stemmer */
124075      copy_stemmer(zIn, nIn, zOut, pnOut);
124076      return;
124077    }
124078  }
124079  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
124080  z = &zReverse[j+1];
124081
124082
124083  /* Step 1a */
124084  if( z[0]=='s' ){
124085    if(
124086     !stem(&z, "sess", "ss", 0) &&
124087     !stem(&z, "sei", "i", 0)  &&
124088     !stem(&z, "ss", "ss", 0)
124089    ){
124090      z++;
124091    }
124092  }
124093
124094  /* Step 1b */
124095  z2 = z;
124096  if( stem(&z, "dee", "ee", m_gt_0) ){
124097    /* Do nothing.  The work was all in the test */
124098  }else if(
124099     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
124100      && z!=z2
124101  ){
124102     if( stem(&z, "ta", "ate", 0) ||
124103         stem(&z, "lb", "ble", 0) ||
124104         stem(&z, "zi", "ize", 0) ){
124105       /* Do nothing.  The work was all in the test */
124106     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
124107       z++;
124108     }else if( m_eq_1(z) && star_oh(z) ){
124109       *(--z) = 'e';
124110     }
124111  }
124112
124113  /* Step 1c */
124114  if( z[0]=='y' && hasVowel(z+1) ){
124115    z[0] = 'i';
124116  }
124117
124118  /* Step 2 */
124119  switch( z[1] ){
124120   case 'a':
124121     stem(&z, "lanoita", "ate", m_gt_0) ||
124122     stem(&z, "lanoit", "tion", m_gt_0);
124123     break;
124124   case 'c':
124125     stem(&z, "icne", "ence", m_gt_0) ||
124126     stem(&z, "icna", "ance", m_gt_0);
124127     break;
124128   case 'e':
124129     stem(&z, "rezi", "ize", m_gt_0);
124130     break;
124131   case 'g':
124132     stem(&z, "igol", "log", m_gt_0);
124133     break;
124134   case 'l':
124135     stem(&z, "ilb", "ble", m_gt_0) ||
124136     stem(&z, "illa", "al", m_gt_0) ||
124137     stem(&z, "iltne", "ent", m_gt_0) ||
124138     stem(&z, "ile", "e", m_gt_0) ||
124139     stem(&z, "ilsuo", "ous", m_gt_0);
124140     break;
124141   case 'o':
124142     stem(&z, "noitazi", "ize", m_gt_0) ||
124143     stem(&z, "noita", "ate", m_gt_0) ||
124144     stem(&z, "rota", "ate", m_gt_0);
124145     break;
124146   case 's':
124147     stem(&z, "msila", "al", m_gt_0) ||
124148     stem(&z, "ssenevi", "ive", m_gt_0) ||
124149     stem(&z, "ssenluf", "ful", m_gt_0) ||
124150     stem(&z, "ssensuo", "ous", m_gt_0);
124151     break;
124152   case 't':
124153     stem(&z, "itila", "al", m_gt_0) ||
124154     stem(&z, "itivi", "ive", m_gt_0) ||
124155     stem(&z, "itilib", "ble", m_gt_0);
124156     break;
124157  }
124158
124159  /* Step 3 */
124160  switch( z[0] ){
124161   case 'e':
124162     stem(&z, "etaci", "ic", m_gt_0) ||
124163     stem(&z, "evita", "", m_gt_0)   ||
124164     stem(&z, "ezila", "al", m_gt_0);
124165     break;
124166   case 'i':
124167     stem(&z, "itici", "ic", m_gt_0);
124168     break;
124169   case 'l':
124170     stem(&z, "laci", "ic", m_gt_0) ||
124171     stem(&z, "luf", "", m_gt_0);
124172     break;
124173   case 's':
124174     stem(&z, "ssen", "", m_gt_0);
124175     break;
124176  }
124177
124178  /* Step 4 */
124179  switch( z[1] ){
124180   case 'a':
124181     if( z[0]=='l' && m_gt_1(z+2) ){
124182       z += 2;
124183     }
124184     break;
124185   case 'c':
124186     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
124187       z += 4;
124188     }
124189     break;
124190   case 'e':
124191     if( z[0]=='r' && m_gt_1(z+2) ){
124192       z += 2;
124193     }
124194     break;
124195   case 'i':
124196     if( z[0]=='c' && m_gt_1(z+2) ){
124197       z += 2;
124198     }
124199     break;
124200   case 'l':
124201     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
124202       z += 4;
124203     }
124204     break;
124205   case 'n':
124206     if( z[0]=='t' ){
124207       if( z[2]=='a' ){
124208         if( m_gt_1(z+3) ){
124209           z += 3;
124210         }
124211       }else if( z[2]=='e' ){
124212         stem(&z, "tneme", "", m_gt_1) ||
124213         stem(&z, "tnem", "", m_gt_1) ||
124214         stem(&z, "tne", "", m_gt_1);
124215       }
124216     }
124217     break;
124218   case 'o':
124219     if( z[0]=='u' ){
124220       if( m_gt_1(z+2) ){
124221         z += 2;
124222       }
124223     }else if( z[3]=='s' || z[3]=='t' ){
124224       stem(&z, "noi", "", m_gt_1);
124225     }
124226     break;
124227   case 's':
124228     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
124229       z += 3;
124230     }
124231     break;
124232   case 't':
124233     stem(&z, "eta", "", m_gt_1) ||
124234     stem(&z, "iti", "", m_gt_1);
124235     break;
124236   case 'u':
124237     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
124238       z += 3;
124239     }
124240     break;
124241   case 'v':
124242   case 'z':
124243     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
124244       z += 3;
124245     }
124246     break;
124247  }
124248
124249  /* Step 5a */
124250  if( z[0]=='e' ){
124251    if( m_gt_1(z+1) ){
124252      z++;
124253    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
124254      z++;
124255    }
124256  }
124257
124258  /* Step 5b */
124259  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
124260    z++;
124261  }
124262
124263  /* z[] is now the stemmed word in reverse order.  Flip it back
124264  ** around into forward order and return.
124265  */
124266  *pnOut = i = (int)strlen(z);
124267  zOut[i] = 0;
124268  while( *z ){
124269    zOut[--i] = *(z++);
124270  }
124271}
124272
124273/*
124274** Characters that can be part of a token.  We assume any character
124275** whose value is greater than 0x80 (any UTF character) can be
124276** part of a token.  In other words, delimiters all must have
124277** values of 0x7f or lower.
124278*/
124279static const char porterIdChar[] = {
124280/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
124281    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
124282    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
124283    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
124284    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
124285    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
124286};
124287#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
124288
124289/*
124290** Extract the next token from a tokenization cursor.  The cursor must
124291** have been opened by a prior call to porterOpen().
124292*/
124293static int porterNext(
124294  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
124295  const char **pzToken,               /* OUT: *pzToken is the token text */
124296  int *pnBytes,                       /* OUT: Number of bytes in token */
124297  int *piStartOffset,                 /* OUT: Starting offset of token */
124298  int *piEndOffset,                   /* OUT: Ending offset of token */
124299  int *piPosition                     /* OUT: Position integer of token */
124300){
124301  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
124302  const char *z = c->zInput;
124303
124304  while( c->iOffset<c->nInput ){
124305    int iStartOffset, ch;
124306
124307    /* Scan past delimiter characters */
124308    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
124309      c->iOffset++;
124310    }
124311
124312    /* Count non-delimiter characters. */
124313    iStartOffset = c->iOffset;
124314    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
124315      c->iOffset++;
124316    }
124317
124318    if( c->iOffset>iStartOffset ){
124319      int n = c->iOffset-iStartOffset;
124320      if( n>c->nAllocated ){
124321        char *pNew;
124322        c->nAllocated = n+20;
124323        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
124324        if( !pNew ) return SQLITE_NOMEM;
124325        c->zToken = pNew;
124326      }
124327      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
124328      *pzToken = c->zToken;
124329      *piStartOffset = iStartOffset;
124330      *piEndOffset = c->iOffset;
124331      *piPosition = c->iToken++;
124332      return SQLITE_OK;
124333    }
124334  }
124335  return SQLITE_DONE;
124336}
124337
124338/*
124339** The set of routines that implement the porter-stemmer tokenizer
124340*/
124341static const sqlite3_tokenizer_module porterTokenizerModule = {
124342  0,
124343  porterCreate,
124344  porterDestroy,
124345  porterOpen,
124346  porterClose,
124347  porterNext,
124348  0
124349};
124350
124351/*
124352** Allocate a new porter tokenizer.  Return a pointer to the new
124353** tokenizer in *ppModule
124354*/
124355SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
124356  sqlite3_tokenizer_module const**ppModule
124357){
124358  *ppModule = &porterTokenizerModule;
124359}
124360
124361#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124362
124363/************** End of fts3_porter.c *****************************************/
124364/************** Begin file fts3_tokenizer.c **********************************/
124365/*
124366** 2007 June 22
124367**
124368** The author disclaims copyright to this source code.  In place of
124369** a legal notice, here is a blessing:
124370**
124371**    May you do good and not evil.
124372**    May you find forgiveness for yourself and forgive others.
124373**    May you share freely, never taking more than you give.
124374**
124375******************************************************************************
124376**
124377** This is part of an SQLite module implementing full-text search.
124378** This particular file implements the generic tokenizer interface.
124379*/
124380
124381/*
124382** The code in this file is only compiled if:
124383**
124384**     * The FTS3 module is being built as an extension
124385**       (in which case SQLITE_CORE is not defined), or
124386**
124387**     * The FTS3 module is being built into the core of
124388**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124389*/
124390#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124391
124392/* #include <assert.h> */
124393/* #include <string.h> */
124394
124395/*
124396** Implementation of the SQL scalar function for accessing the underlying
124397** hash table. This function may be called as follows:
124398**
124399**   SELECT <function-name>(<key-name>);
124400**   SELECT <function-name>(<key-name>, <pointer>);
124401**
124402** where <function-name> is the name passed as the second argument
124403** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
124404**
124405** If the <pointer> argument is specified, it must be a blob value
124406** containing a pointer to be stored as the hash data corresponding
124407** to the string <key-name>. If <pointer> is not specified, then
124408** the string <key-name> must already exist in the has table. Otherwise,
124409** an error is returned.
124410**
124411** Whether or not the <pointer> argument is specified, the value returned
124412** is a blob containing the pointer stored as the hash data corresponding
124413** to string <key-name> (after the hash-table is updated, if applicable).
124414*/
124415static void scalarFunc(
124416  sqlite3_context *context,
124417  int argc,
124418  sqlite3_value **argv
124419){
124420  Fts3Hash *pHash;
124421  void *pPtr = 0;
124422  const unsigned char *zName;
124423  int nName;
124424
124425  assert( argc==1 || argc==2 );
124426
124427  pHash = (Fts3Hash *)sqlite3_user_data(context);
124428
124429  zName = sqlite3_value_text(argv[0]);
124430  nName = sqlite3_value_bytes(argv[0])+1;
124431
124432  if( argc==2 ){
124433    void *pOld;
124434    int n = sqlite3_value_bytes(argv[1]);
124435    if( n!=sizeof(pPtr) ){
124436      sqlite3_result_error(context, "argument type mismatch", -1);
124437      return;
124438    }
124439    pPtr = *(void **)sqlite3_value_blob(argv[1]);
124440    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
124441    if( pOld==pPtr ){
124442      sqlite3_result_error(context, "out of memory", -1);
124443      return;
124444    }
124445  }else{
124446    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
124447    if( !pPtr ){
124448      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
124449      sqlite3_result_error(context, zErr, -1);
124450      sqlite3_free(zErr);
124451      return;
124452    }
124453  }
124454
124455  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
124456}
124457
124458SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
124459  static const char isFtsIdChar[] = {
124460      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
124461      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
124462      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
124463      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
124464      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
124465      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
124466      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
124467      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
124468  };
124469  return (c&0x80 || isFtsIdChar[(int)(c)]);
124470}
124471
124472SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
124473  const char *z1;
124474  const char *z2 = 0;
124475
124476  /* Find the start of the next token. */
124477  z1 = zStr;
124478  while( z2==0 ){
124479    char c = *z1;
124480    switch( c ){
124481      case '\0': return 0;        /* No more tokens here */
124482      case '\'':
124483      case '"':
124484      case '`': {
124485        z2 = z1;
124486        while( *++z2 && (*z2!=c || *++z2==c) );
124487        break;
124488      }
124489      case '[':
124490        z2 = &z1[1];
124491        while( *z2 && z2[0]!=']' ) z2++;
124492        if( *z2 ) z2++;
124493        break;
124494
124495      default:
124496        if( sqlite3Fts3IsIdChar(*z1) ){
124497          z2 = &z1[1];
124498          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
124499        }else{
124500          z1++;
124501        }
124502    }
124503  }
124504
124505  *pn = (int)(z2-z1);
124506  return z1;
124507}
124508
124509SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
124510  Fts3Hash *pHash,                /* Tokenizer hash table */
124511  const char *zArg,               /* Tokenizer name */
124512  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
124513  char **pzErr                    /* OUT: Set to malloced error message */
124514){
124515  int rc;
124516  char *z = (char *)zArg;
124517  int n = 0;
124518  char *zCopy;
124519  char *zEnd;                     /* Pointer to nul-term of zCopy */
124520  sqlite3_tokenizer_module *m;
124521
124522  zCopy = sqlite3_mprintf("%s", zArg);
124523  if( !zCopy ) return SQLITE_NOMEM;
124524  zEnd = &zCopy[strlen(zCopy)];
124525
124526  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
124527  z[n] = '\0';
124528  sqlite3Fts3Dequote(z);
124529
124530  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
124531  if( !m ){
124532    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
124533    rc = SQLITE_ERROR;
124534  }else{
124535    char const **aArg = 0;
124536    int iArg = 0;
124537    z = &z[n+1];
124538    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
124539      int nNew = sizeof(char *)*(iArg+1);
124540      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
124541      if( !aNew ){
124542        sqlite3_free(zCopy);
124543        sqlite3_free((void *)aArg);
124544        return SQLITE_NOMEM;
124545      }
124546      aArg = aNew;
124547      aArg[iArg++] = z;
124548      z[n] = '\0';
124549      sqlite3Fts3Dequote(z);
124550      z = &z[n+1];
124551    }
124552    rc = m->xCreate(iArg, aArg, ppTok);
124553    assert( rc!=SQLITE_OK || *ppTok );
124554    if( rc!=SQLITE_OK ){
124555      *pzErr = sqlite3_mprintf("unknown tokenizer");
124556    }else{
124557      (*ppTok)->pModule = m;
124558    }
124559    sqlite3_free((void *)aArg);
124560  }
124561
124562  sqlite3_free(zCopy);
124563  return rc;
124564}
124565
124566
124567#ifdef SQLITE_TEST
124568
124569/* #include <tcl.h> */
124570/* #include <string.h> */
124571
124572/*
124573** Implementation of a special SQL scalar function for testing tokenizers
124574** designed to be used in concert with the Tcl testing framework. This
124575** function must be called with two arguments:
124576**
124577**   SELECT <function-name>(<key-name>, <input-string>);
124578**   SELECT <function-name>(<key-name>, <pointer>);
124579**
124580** where <function-name> is the name passed as the second argument
124581** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
124582** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
124583**
124584** The return value is a string that may be interpreted as a Tcl
124585** list. For each token in the <input-string>, three elements are
124586** added to the returned list. The first is the token position, the
124587** second is the token text (folded, stemmed, etc.) and the third is the
124588** substring of <input-string> associated with the token. For example,
124589** using the built-in "simple" tokenizer:
124590**
124591**   SELECT fts_tokenizer_test('simple', 'I don't see how');
124592**
124593** will return the string:
124594**
124595**   "{0 i I 1 dont don't 2 see see 3 how how}"
124596**
124597*/
124598static void testFunc(
124599  sqlite3_context *context,
124600  int argc,
124601  sqlite3_value **argv
124602){
124603  Fts3Hash *pHash;
124604  sqlite3_tokenizer_module *p;
124605  sqlite3_tokenizer *pTokenizer = 0;
124606  sqlite3_tokenizer_cursor *pCsr = 0;
124607
124608  const char *zErr = 0;
124609
124610  const char *zName;
124611  int nName;
124612  const char *zInput;
124613  int nInput;
124614
124615  const char *zArg = 0;
124616
124617  const char *zToken;
124618  int nToken;
124619  int iStart;
124620  int iEnd;
124621  int iPos;
124622
124623  Tcl_Obj *pRet;
124624
124625  assert( argc==2 || argc==3 );
124626
124627  nName = sqlite3_value_bytes(argv[0]);
124628  zName = (const char *)sqlite3_value_text(argv[0]);
124629  nInput = sqlite3_value_bytes(argv[argc-1]);
124630  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
124631
124632  if( argc==3 ){
124633    zArg = (const char *)sqlite3_value_text(argv[1]);
124634  }
124635
124636  pHash = (Fts3Hash *)sqlite3_user_data(context);
124637  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
124638
124639  if( !p ){
124640    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
124641    sqlite3_result_error(context, zErr, -1);
124642    sqlite3_free(zErr);
124643    return;
124644  }
124645
124646  pRet = Tcl_NewObj();
124647  Tcl_IncrRefCount(pRet);
124648
124649  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
124650    zErr = "error in xCreate()";
124651    goto finish;
124652  }
124653  pTokenizer->pModule = p;
124654  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
124655    zErr = "error in xOpen()";
124656    goto finish;
124657  }
124658
124659  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
124660    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
124661    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
124662    zToken = &zInput[iStart];
124663    nToken = iEnd-iStart;
124664    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
124665  }
124666
124667  if( SQLITE_OK!=p->xClose(pCsr) ){
124668    zErr = "error in xClose()";
124669    goto finish;
124670  }
124671  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
124672    zErr = "error in xDestroy()";
124673    goto finish;
124674  }
124675
124676finish:
124677  if( zErr ){
124678    sqlite3_result_error(context, zErr, -1);
124679  }else{
124680    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
124681  }
124682  Tcl_DecrRefCount(pRet);
124683}
124684
124685static
124686int registerTokenizer(
124687  sqlite3 *db,
124688  char *zName,
124689  const sqlite3_tokenizer_module *p
124690){
124691  int rc;
124692  sqlite3_stmt *pStmt;
124693  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
124694
124695  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124696  if( rc!=SQLITE_OK ){
124697    return rc;
124698  }
124699
124700  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
124701  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
124702  sqlite3_step(pStmt);
124703
124704  return sqlite3_finalize(pStmt);
124705}
124706
124707static
124708int queryTokenizer(
124709  sqlite3 *db,
124710  char *zName,
124711  const sqlite3_tokenizer_module **pp
124712){
124713  int rc;
124714  sqlite3_stmt *pStmt;
124715  const char zSql[] = "SELECT fts3_tokenizer(?)";
124716
124717  *pp = 0;
124718  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124719  if( rc!=SQLITE_OK ){
124720    return rc;
124721  }
124722
124723  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
124724  if( SQLITE_ROW==sqlite3_step(pStmt) ){
124725    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
124726      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
124727    }
124728  }
124729
124730  return sqlite3_finalize(pStmt);
124731}
124732
124733SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
124734
124735/*
124736** Implementation of the scalar function fts3_tokenizer_internal_test().
124737** This function is used for testing only, it is not included in the
124738** build unless SQLITE_TEST is defined.
124739**
124740** The purpose of this is to test that the fts3_tokenizer() function
124741** can be used as designed by the C-code in the queryTokenizer and
124742** registerTokenizer() functions above. These two functions are repeated
124743** in the README.tokenizer file as an example, so it is important to
124744** test them.
124745**
124746** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
124747** function with no arguments. An assert() will fail if a problem is
124748** detected. i.e.:
124749**
124750**     SELECT fts3_tokenizer_internal_test();
124751**
124752*/
124753static void intTestFunc(
124754  sqlite3_context *context,
124755  int argc,
124756  sqlite3_value **argv
124757){
124758  int rc;
124759  const sqlite3_tokenizer_module *p1;
124760  const sqlite3_tokenizer_module *p2;
124761  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
124762
124763  UNUSED_PARAMETER(argc);
124764  UNUSED_PARAMETER(argv);
124765
124766  /* Test the query function */
124767  sqlite3Fts3SimpleTokenizerModule(&p1);
124768  rc = queryTokenizer(db, "simple", &p2);
124769  assert( rc==SQLITE_OK );
124770  assert( p1==p2 );
124771  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
124772  assert( rc==SQLITE_ERROR );
124773  assert( p2==0 );
124774  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
124775
124776  /* Test the storage function */
124777  rc = registerTokenizer(db, "nosuchtokenizer", p1);
124778  assert( rc==SQLITE_OK );
124779  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
124780  assert( rc==SQLITE_OK );
124781  assert( p2==p1 );
124782
124783  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
124784}
124785
124786#endif
124787
124788/*
124789** Set up SQL objects in database db used to access the contents of
124790** the hash table pointed to by argument pHash. The hash table must
124791** been initialised to use string keys, and to take a private copy
124792** of the key when a value is inserted. i.e. by a call similar to:
124793**
124794**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
124795**
124796** This function adds a scalar function (see header comment above
124797** scalarFunc() in this file for details) and, if ENABLE_TABLE is
124798** defined at compilation time, a temporary virtual table (see header
124799** comment above struct HashTableVtab) to the database schema. Both
124800** provide read/write access to the contents of *pHash.
124801**
124802** The third argument to this function, zName, is used as the name
124803** of both the scalar and, if created, the virtual table.
124804*/
124805SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
124806  sqlite3 *db,
124807  Fts3Hash *pHash,
124808  const char *zName
124809){
124810  int rc = SQLITE_OK;
124811  void *p = (void *)pHash;
124812  const int any = SQLITE_ANY;
124813
124814#ifdef SQLITE_TEST
124815  char *zTest = 0;
124816  char *zTest2 = 0;
124817  void *pdb = (void *)db;
124818  zTest = sqlite3_mprintf("%s_test", zName);
124819  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
124820  if( !zTest || !zTest2 ){
124821    rc = SQLITE_NOMEM;
124822  }
124823#endif
124824
124825  if( SQLITE_OK==rc ){
124826    rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
124827  }
124828  if( SQLITE_OK==rc ){
124829    rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
124830  }
124831#ifdef SQLITE_TEST
124832  if( SQLITE_OK==rc ){
124833    rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
124834  }
124835  if( SQLITE_OK==rc ){
124836    rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
124837  }
124838  if( SQLITE_OK==rc ){
124839    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
124840  }
124841#endif
124842
124843#ifdef SQLITE_TEST
124844  sqlite3_free(zTest);
124845  sqlite3_free(zTest2);
124846#endif
124847
124848  return rc;
124849}
124850
124851#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124852
124853/************** End of fts3_tokenizer.c **************************************/
124854/************** Begin file fts3_tokenizer1.c *********************************/
124855/*
124856** 2006 Oct 10
124857**
124858** The author disclaims copyright to this source code.  In place of
124859** a legal notice, here is a blessing:
124860**
124861**    May you do good and not evil.
124862**    May you find forgiveness for yourself and forgive others.
124863**    May you share freely, never taking more than you give.
124864**
124865******************************************************************************
124866**
124867** Implementation of the "simple" full-text-search tokenizer.
124868*/
124869
124870/*
124871** The code in this file is only compiled if:
124872**
124873**     * The FTS3 module is being built as an extension
124874**       (in which case SQLITE_CORE is not defined), or
124875**
124876**     * The FTS3 module is being built into the core of
124877**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124878*/
124879#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124880
124881/* #include <assert.h> */
124882/* #include <stdlib.h> */
124883/* #include <stdio.h> */
124884/* #include <string.h> */
124885
124886
124887typedef struct simple_tokenizer {
124888  sqlite3_tokenizer base;
124889  char delim[128];             /* flag ASCII delimiters */
124890} simple_tokenizer;
124891
124892typedef struct simple_tokenizer_cursor {
124893  sqlite3_tokenizer_cursor base;
124894  const char *pInput;          /* input we are tokenizing */
124895  int nBytes;                  /* size of the input */
124896  int iOffset;                 /* current position in pInput */
124897  int iToken;                  /* index of next token to be returned */
124898  char *pToken;                /* storage for current token */
124899  int nTokenAllocated;         /* space allocated to zToken buffer */
124900} simple_tokenizer_cursor;
124901
124902
124903static int simpleDelim(simple_tokenizer *t, unsigned char c){
124904  return c<0x80 && t->delim[c];
124905}
124906static int fts3_isalnum(int x){
124907  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
124908}
124909
124910/*
124911** Create a new tokenizer instance.
124912*/
124913static int simpleCreate(
124914  int argc, const char * const *argv,
124915  sqlite3_tokenizer **ppTokenizer
124916){
124917  simple_tokenizer *t;
124918
124919  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
124920  if( t==NULL ) return SQLITE_NOMEM;
124921  memset(t, 0, sizeof(*t));
124922
124923  /* TODO(shess) Delimiters need to remain the same from run to run,
124924  ** else we need to reindex.  One solution would be a meta-table to
124925  ** track such information in the database, then we'd only want this
124926  ** information on the initial create.
124927  */
124928  if( argc>1 ){
124929    int i, n = (int)strlen(argv[1]);
124930    for(i=0; i<n; i++){
124931      unsigned char ch = argv[1][i];
124932      /* We explicitly don't support UTF-8 delimiters for now. */
124933      if( ch>=0x80 ){
124934        sqlite3_free(t);
124935        return SQLITE_ERROR;
124936      }
124937      t->delim[ch] = 1;
124938    }
124939  } else {
124940    /* Mark non-alphanumeric ASCII characters as delimiters */
124941    int i;
124942    for(i=1; i<0x80; i++){
124943      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
124944    }
124945  }
124946
124947  *ppTokenizer = &t->base;
124948  return SQLITE_OK;
124949}
124950
124951/*
124952** Destroy a tokenizer
124953*/
124954static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
124955  sqlite3_free(pTokenizer);
124956  return SQLITE_OK;
124957}
124958
124959/*
124960** Prepare to begin tokenizing a particular string.  The input
124961** string to be tokenized is pInput[0..nBytes-1].  A cursor
124962** used to incrementally tokenize this string is returned in
124963** *ppCursor.
124964*/
124965static int simpleOpen(
124966  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
124967  const char *pInput, int nBytes,        /* String to be tokenized */
124968  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
124969){
124970  simple_tokenizer_cursor *c;
124971
124972  UNUSED_PARAMETER(pTokenizer);
124973
124974  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
124975  if( c==NULL ) return SQLITE_NOMEM;
124976
124977  c->pInput = pInput;
124978  if( pInput==0 ){
124979    c->nBytes = 0;
124980  }else if( nBytes<0 ){
124981    c->nBytes = (int)strlen(pInput);
124982  }else{
124983    c->nBytes = nBytes;
124984  }
124985  c->iOffset = 0;                 /* start tokenizing at the beginning */
124986  c->iToken = 0;
124987  c->pToken = NULL;               /* no space allocated, yet. */
124988  c->nTokenAllocated = 0;
124989
124990  *ppCursor = &c->base;
124991  return SQLITE_OK;
124992}
124993
124994/*
124995** Close a tokenization cursor previously opened by a call to
124996** simpleOpen() above.
124997*/
124998static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
124999  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
125000  sqlite3_free(c->pToken);
125001  sqlite3_free(c);
125002  return SQLITE_OK;
125003}
125004
125005/*
125006** Extract the next token from a tokenization cursor.  The cursor must
125007** have been opened by a prior call to simpleOpen().
125008*/
125009static int simpleNext(
125010  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
125011  const char **ppToken,               /* OUT: *ppToken is the token text */
125012  int *pnBytes,                       /* OUT: Number of bytes in token */
125013  int *piStartOffset,                 /* OUT: Starting offset of token */
125014  int *piEndOffset,                   /* OUT: Ending offset of token */
125015  int *piPosition                     /* OUT: Position integer of token */
125016){
125017  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
125018  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
125019  unsigned char *p = (unsigned char *)c->pInput;
125020
125021  while( c->iOffset<c->nBytes ){
125022    int iStartOffset;
125023
125024    /* Scan past delimiter characters */
125025    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
125026      c->iOffset++;
125027    }
125028
125029    /* Count non-delimiter characters. */
125030    iStartOffset = c->iOffset;
125031    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
125032      c->iOffset++;
125033    }
125034
125035    if( c->iOffset>iStartOffset ){
125036      int i, n = c->iOffset-iStartOffset;
125037      if( n>c->nTokenAllocated ){
125038        char *pNew;
125039        c->nTokenAllocated = n+20;
125040        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
125041        if( !pNew ) return SQLITE_NOMEM;
125042        c->pToken = pNew;
125043      }
125044      for(i=0; i<n; i++){
125045        /* TODO(shess) This needs expansion to handle UTF-8
125046        ** case-insensitivity.
125047        */
125048        unsigned char ch = p[iStartOffset+i];
125049        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
125050      }
125051      *ppToken = c->pToken;
125052      *pnBytes = n;
125053      *piStartOffset = iStartOffset;
125054      *piEndOffset = c->iOffset;
125055      *piPosition = c->iToken++;
125056
125057      return SQLITE_OK;
125058    }
125059  }
125060  return SQLITE_DONE;
125061}
125062
125063/*
125064** The set of routines that implement the simple tokenizer
125065*/
125066static const sqlite3_tokenizer_module simpleTokenizerModule = {
125067  0,
125068  simpleCreate,
125069  simpleDestroy,
125070  simpleOpen,
125071  simpleClose,
125072  simpleNext,
125073  0,
125074};
125075
125076/*
125077** Allocate a new simple tokenizer.  Return a pointer to the new
125078** tokenizer in *ppModule
125079*/
125080SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
125081  sqlite3_tokenizer_module const**ppModule
125082){
125083  *ppModule = &simpleTokenizerModule;
125084}
125085
125086#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125087
125088/************** End of fts3_tokenizer1.c *************************************/
125089/************** Begin file fts3_write.c **************************************/
125090/*
125091** 2009 Oct 23
125092**
125093** The author disclaims copyright to this source code.  In place of
125094** a legal notice, here is a blessing:
125095**
125096**    May you do good and not evil.
125097**    May you find forgiveness for yourself and forgive others.
125098**    May you share freely, never taking more than you give.
125099**
125100******************************************************************************
125101**
125102** This file is part of the SQLite FTS3 extension module. Specifically,
125103** this file contains code to insert, update and delete rows from FTS3
125104** tables. It also contains code to merge FTS3 b-tree segments. Some
125105** of the sub-routines used to merge segments are also used by the query
125106** code in fts3.c.
125107*/
125108
125109#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125110
125111/* #include <string.h> */
125112/* #include <assert.h> */
125113/* #include <stdlib.h> */
125114
125115/*
125116** When full-text index nodes are loaded from disk, the buffer that they
125117** are loaded into has the following number of bytes of padding at the end
125118** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
125119** of 920 bytes is allocated for it.
125120**
125121** This means that if we have a pointer into a buffer containing node data,
125122** it is always safe to read up to two varints from it without risking an
125123** overread, even if the node data is corrupted.
125124*/
125125#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
125126
125127/*
125128** Under certain circumstances, b-tree nodes (doclists) can be loaded into
125129** memory incrementally instead of all at once. This can be a big performance
125130** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
125131** method before retrieving all query results (as may happen, for example,
125132** if a query has a LIMIT clause).
125133**
125134** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
125135** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
125136** The code is written so that the hard lower-limit for each of these values
125137** is 1. Clearly such small values would be inefficient, but can be useful
125138** for testing purposes.
125139**
125140** If this module is built with SQLITE_TEST defined, these constants may
125141** be overridden at runtime for testing purposes. File fts3_test.c contains
125142** a Tcl interface to read and write the values.
125143*/
125144#ifdef SQLITE_TEST
125145int test_fts3_node_chunksize = (4*1024);
125146int test_fts3_node_chunk_threshold = (4*1024)*4;
125147# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
125148# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
125149#else
125150# define FTS3_NODE_CHUNKSIZE (4*1024)
125151# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
125152#endif
125153
125154typedef struct PendingList PendingList;
125155typedef struct SegmentNode SegmentNode;
125156typedef struct SegmentWriter SegmentWriter;
125157
125158/*
125159** An instance of the following data structure is used to build doclists
125160** incrementally. See function fts3PendingListAppend() for details.
125161*/
125162struct PendingList {
125163  int nData;
125164  char *aData;
125165  int nSpace;
125166  sqlite3_int64 iLastDocid;
125167  sqlite3_int64 iLastCol;
125168  sqlite3_int64 iLastPos;
125169};
125170
125171
125172/*
125173** Each cursor has a (possibly empty) linked list of the following objects.
125174*/
125175struct Fts3DeferredToken {
125176  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
125177  int iCol;                       /* Column token must occur in */
125178  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
125179  PendingList *pList;             /* Doclist is assembled here */
125180};
125181
125182/*
125183** An instance of this structure is used to iterate through the terms on
125184** a contiguous set of segment b-tree leaf nodes. Although the details of
125185** this structure are only manipulated by code in this file, opaque handles
125186** of type Fts3SegReader* are also used by code in fts3.c to iterate through
125187** terms when querying the full-text index. See functions:
125188**
125189**   sqlite3Fts3SegReaderNew()
125190**   sqlite3Fts3SegReaderFree()
125191**   sqlite3Fts3SegReaderIterate()
125192**
125193** Methods used to manipulate Fts3SegReader structures:
125194**
125195**   fts3SegReaderNext()
125196**   fts3SegReaderFirstDocid()
125197**   fts3SegReaderNextDocid()
125198*/
125199struct Fts3SegReader {
125200  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
125201  int bLookup;                    /* True for a lookup only */
125202
125203  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
125204  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
125205  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
125206  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
125207
125208  char *aNode;                    /* Pointer to node data (or NULL) */
125209  int nNode;                      /* Size of buffer at aNode (or 0) */
125210  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
125211  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
125212
125213  Fts3HashElem **ppNextElem;
125214
125215  /* Variables set by fts3SegReaderNext(). These may be read directly
125216  ** by the caller. They are valid from the time SegmentReaderNew() returns
125217  ** until SegmentReaderNext() returns something other than SQLITE_OK
125218  ** (i.e. SQLITE_DONE).
125219  */
125220  int nTerm;                      /* Number of bytes in current term */
125221  char *zTerm;                    /* Pointer to current term */
125222  int nTermAlloc;                 /* Allocated size of zTerm buffer */
125223  char *aDoclist;                 /* Pointer to doclist of current entry */
125224  int nDoclist;                   /* Size of doclist in current entry */
125225
125226  /* The following variables are used by fts3SegReaderNextDocid() to iterate
125227  ** through the current doclist (aDoclist/nDoclist).
125228  */
125229  char *pOffsetList;
125230  int nOffsetList;                /* For descending pending seg-readers only */
125231  sqlite3_int64 iDocid;
125232};
125233
125234#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
125235#define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
125236
125237/*
125238** An instance of this structure is used to create a segment b-tree in the
125239** database. The internal details of this type are only accessed by the
125240** following functions:
125241**
125242**   fts3SegWriterAdd()
125243**   fts3SegWriterFlush()
125244**   fts3SegWriterFree()
125245*/
125246struct SegmentWriter {
125247  SegmentNode *pTree;             /* Pointer to interior tree structure */
125248  sqlite3_int64 iFirst;           /* First slot in %_segments written */
125249  sqlite3_int64 iFree;            /* Next free slot in %_segments */
125250  char *zTerm;                    /* Pointer to previous term buffer */
125251  int nTerm;                      /* Number of bytes in zTerm */
125252  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
125253  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
125254  int nSize;                      /* Size of allocation at aData */
125255  int nData;                      /* Bytes of data in aData */
125256  char *aData;                    /* Pointer to block from malloc() */
125257};
125258
125259/*
125260** Type SegmentNode is used by the following three functions to create
125261** the interior part of the segment b+-tree structures (everything except
125262** the leaf nodes). These functions and type are only ever used by code
125263** within the fts3SegWriterXXX() family of functions described above.
125264**
125265**   fts3NodeAddTerm()
125266**   fts3NodeWrite()
125267**   fts3NodeFree()
125268**
125269** When a b+tree is written to the database (either as a result of a merge
125270** or the pending-terms table being flushed), leaves are written into the
125271** database file as soon as they are completely populated. The interior of
125272** the tree is assembled in memory and written out only once all leaves have
125273** been populated and stored. This is Ok, as the b+-tree fanout is usually
125274** very large, meaning that the interior of the tree consumes relatively
125275** little memory.
125276*/
125277struct SegmentNode {
125278  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
125279  SegmentNode *pRight;            /* Pointer to right-sibling */
125280  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
125281  int nEntry;                     /* Number of terms written to node so far */
125282  char *zTerm;                    /* Pointer to previous term buffer */
125283  int nTerm;                      /* Number of bytes in zTerm */
125284  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
125285  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
125286  int nData;                      /* Bytes of valid data so far */
125287  char *aData;                    /* Node data */
125288};
125289
125290/*
125291** Valid values for the second argument to fts3SqlStmt().
125292*/
125293#define SQL_DELETE_CONTENT             0
125294#define SQL_IS_EMPTY                   1
125295#define SQL_DELETE_ALL_CONTENT         2
125296#define SQL_DELETE_ALL_SEGMENTS        3
125297#define SQL_DELETE_ALL_SEGDIR          4
125298#define SQL_DELETE_ALL_DOCSIZE         5
125299#define SQL_DELETE_ALL_STAT            6
125300#define SQL_SELECT_CONTENT_BY_ROWID    7
125301#define SQL_NEXT_SEGMENT_INDEX         8
125302#define SQL_INSERT_SEGMENTS            9
125303#define SQL_NEXT_SEGMENTS_ID          10
125304#define SQL_INSERT_SEGDIR             11
125305#define SQL_SELECT_LEVEL              12
125306#define SQL_SELECT_LEVEL_RANGE        13
125307#define SQL_SELECT_LEVEL_COUNT        14
125308#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
125309#define SQL_DELETE_SEGDIR_LEVEL       16
125310#define SQL_DELETE_SEGMENTS_RANGE     17
125311#define SQL_CONTENT_INSERT            18
125312#define SQL_DELETE_DOCSIZE            19
125313#define SQL_REPLACE_DOCSIZE           20
125314#define SQL_SELECT_DOCSIZE            21
125315#define SQL_SELECT_DOCTOTAL           22
125316#define SQL_REPLACE_DOCTOTAL          23
125317
125318#define SQL_SELECT_ALL_PREFIX_LEVEL   24
125319#define SQL_DELETE_ALL_TERMS_SEGDIR   25
125320
125321#define SQL_DELETE_SEGDIR_RANGE       26
125322
125323#define SQL_SELECT_ALL_LANGID         27
125324
125325/*
125326** This function is used to obtain an SQLite prepared statement handle
125327** for the statement identified by the second argument. If successful,
125328** *pp is set to the requested statement handle and SQLITE_OK returned.
125329** Otherwise, an SQLite error code is returned and *pp is set to 0.
125330**
125331** If argument apVal is not NULL, then it must point to an array with
125332** at least as many entries as the requested statement has bound
125333** parameters. The values are bound to the statements parameters before
125334** returning.
125335*/
125336static int fts3SqlStmt(
125337  Fts3Table *p,                   /* Virtual table handle */
125338  int eStmt,                      /* One of the SQL_XXX constants above */
125339  sqlite3_stmt **pp,              /* OUT: Statement handle */
125340  sqlite3_value **apVal           /* Values to bind to statement */
125341){
125342  const char *azSql[] = {
125343/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
125344/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
125345/* 2  */  "DELETE FROM %Q.'%q_content'",
125346/* 3  */  "DELETE FROM %Q.'%q_segments'",
125347/* 4  */  "DELETE FROM %Q.'%q_segdir'",
125348/* 5  */  "DELETE FROM %Q.'%q_docsize'",
125349/* 6  */  "DELETE FROM %Q.'%q_stat'",
125350/* 7  */  "SELECT %s WHERE rowid=?",
125351/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
125352/* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
125353/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
125354/* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
125355
125356          /* Return segments in order from oldest to newest.*/
125357/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
125358            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
125359/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
125360            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
125361            "ORDER BY level DESC, idx ASC",
125362
125363/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
125364/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
125365
125366/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
125367/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
125368/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
125369/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
125370/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
125371/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
125372/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
125373/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
125374/* 24 */  "",
125375/* 25 */  "",
125376
125377/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
125378/* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
125379
125380  };
125381  int rc = SQLITE_OK;
125382  sqlite3_stmt *pStmt;
125383
125384  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
125385  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
125386
125387  pStmt = p->aStmt[eStmt];
125388  if( !pStmt ){
125389    char *zSql;
125390    if( eStmt==SQL_CONTENT_INSERT ){
125391      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
125392    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
125393      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
125394    }else{
125395      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
125396    }
125397    if( !zSql ){
125398      rc = SQLITE_NOMEM;
125399    }else{
125400      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
125401      sqlite3_free(zSql);
125402      assert( rc==SQLITE_OK || pStmt==0 );
125403      p->aStmt[eStmt] = pStmt;
125404    }
125405  }
125406  if( apVal ){
125407    int i;
125408    int nParam = sqlite3_bind_parameter_count(pStmt);
125409    for(i=0; rc==SQLITE_OK && i<nParam; i++){
125410      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
125411    }
125412  }
125413  *pp = pStmt;
125414  return rc;
125415}
125416
125417static int fts3SelectDocsize(
125418  Fts3Table *pTab,                /* FTS3 table handle */
125419  int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
125420  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
125421  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
125422){
125423  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
125424  int rc;                         /* Return code */
125425
125426  assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
125427
125428  rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
125429  if( rc==SQLITE_OK ){
125430    if( eStmt==SQL_SELECT_DOCSIZE ){
125431      sqlite3_bind_int64(pStmt, 1, iDocid);
125432    }
125433    rc = sqlite3_step(pStmt);
125434    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
125435      rc = sqlite3_reset(pStmt);
125436      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
125437      pStmt = 0;
125438    }else{
125439      rc = SQLITE_OK;
125440    }
125441  }
125442
125443  *ppStmt = pStmt;
125444  return rc;
125445}
125446
125447SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
125448  Fts3Table *pTab,                /* Fts3 table handle */
125449  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
125450){
125451  return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
125452}
125453
125454SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
125455  Fts3Table *pTab,                /* Fts3 table handle */
125456  sqlite3_int64 iDocid,           /* Docid to read size data for */
125457  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
125458){
125459  return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
125460}
125461
125462/*
125463** Similar to fts3SqlStmt(). Except, after binding the parameters in
125464** array apVal[] to the SQL statement identified by eStmt, the statement
125465** is executed.
125466**
125467** Returns SQLITE_OK if the statement is successfully executed, or an
125468** SQLite error code otherwise.
125469*/
125470static void fts3SqlExec(
125471  int *pRC,                /* Result code */
125472  Fts3Table *p,            /* The FTS3 table */
125473  int eStmt,               /* Index of statement to evaluate */
125474  sqlite3_value **apVal    /* Parameters to bind */
125475){
125476  sqlite3_stmt *pStmt;
125477  int rc;
125478  if( *pRC ) return;
125479  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
125480  if( rc==SQLITE_OK ){
125481    sqlite3_step(pStmt);
125482    rc = sqlite3_reset(pStmt);
125483  }
125484  *pRC = rc;
125485}
125486
125487
125488/*
125489** This function ensures that the caller has obtained a shared-cache
125490** table-lock on the %_content table. This is required before reading
125491** data from the fts3 table. If this lock is not acquired first, then
125492** the caller may end up holding read-locks on the %_segments and %_segdir
125493** tables, but no read-lock on the %_content table. If this happens
125494** a second connection will be able to write to the fts3 table, but
125495** attempting to commit those writes might return SQLITE_LOCKED or
125496** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
125497** write-locks on the %_segments and %_segdir ** tables).
125498**
125499** We try to avoid this because if FTS3 returns any error when committing
125500** a transaction, the whole transaction will be rolled back. And this is
125501** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
125502** still happen if the user reads data directly from the %_segments or
125503** %_segdir tables instead of going through FTS3 though.
125504**
125505** This reasoning does not apply to a content=xxx table.
125506*/
125507SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
125508  int rc;                         /* Return code */
125509  sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
125510
125511  if( p->zContentTbl==0 ){
125512    rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
125513    if( rc==SQLITE_OK ){
125514      sqlite3_bind_null(pStmt, 1);
125515      sqlite3_step(pStmt);
125516      rc = sqlite3_reset(pStmt);
125517    }
125518  }else{
125519    rc = SQLITE_OK;
125520  }
125521
125522  return rc;
125523}
125524
125525/*
125526** FTS maintains a separate indexes for each language-id (a 32-bit integer).
125527** Within each language id, a separate index is maintained to store the
125528** document terms, and each configured prefix size (configured the FTS
125529** "prefix=" option). And each index consists of multiple levels ("relative
125530** levels").
125531**
125532** All three of these values (the language id, the specific index and the
125533** level within the index) are encoded in 64-bit integer values stored
125534** in the %_segdir table on disk. This function is used to convert three
125535** separate component values into the single 64-bit integer value that
125536** can be used to query the %_segdir table.
125537**
125538** Specifically, each language-id/index combination is allocated 1024
125539** 64-bit integer level values ("absolute levels"). The main terms index
125540** for language-id 0 is allocate values 0-1023. The first prefix index
125541** (if any) for language-id 0 is allocated values 1024-2047. And so on.
125542** Language 1 indexes are allocated immediately following language 0.
125543**
125544** So, for a system with nPrefix prefix indexes configured, the block of
125545** absolute levels that corresponds to language-id iLangid and index
125546** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
125547*/
125548static sqlite3_int64 getAbsoluteLevel(
125549  Fts3Table *p,
125550  int iLangid,
125551  int iIndex,
125552  int iLevel
125553){
125554  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
125555  assert( iLangid>=0 );
125556  assert( p->nIndex>0 );
125557  assert( iIndex>=0 && iIndex<p->nIndex );
125558
125559  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
125560  return iBase + iLevel;
125561}
125562
125563
125564/*
125565** Set *ppStmt to a statement handle that may be used to iterate through
125566** all rows in the %_segdir table, from oldest to newest. If successful,
125567** return SQLITE_OK. If an error occurs while preparing the statement,
125568** return an SQLite error code.
125569**
125570** There is only ever one instance of this SQL statement compiled for
125571** each FTS3 table.
125572**
125573** The statement returns the following columns from the %_segdir table:
125574**
125575**   0: idx
125576**   1: start_block
125577**   2: leaves_end_block
125578**   3: end_block
125579**   4: root
125580*/
125581SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
125582  Fts3Table *p,                   /* FTS3 table */
125583  int iLangid,                    /* Language being queried */
125584  int iIndex,                     /* Index for p->aIndex[] */
125585  int iLevel,                     /* Level to select (relative level) */
125586  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
125587){
125588  int rc;
125589  sqlite3_stmt *pStmt = 0;
125590
125591  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
125592  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
125593  assert( iIndex>=0 && iIndex<p->nIndex );
125594
125595  if( iLevel<0 ){
125596    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
125597    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
125598    if( rc==SQLITE_OK ){
125599      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
125600      sqlite3_bind_int64(pStmt, 2,
125601          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
125602      );
125603    }
125604  }else{
125605    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
125606    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
125607    if( rc==SQLITE_OK ){
125608      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
125609    }
125610  }
125611  *ppStmt = pStmt;
125612  return rc;
125613}
125614
125615
125616/*
125617** Append a single varint to a PendingList buffer. SQLITE_OK is returned
125618** if successful, or an SQLite error code otherwise.
125619**
125620** This function also serves to allocate the PendingList structure itself.
125621** For example, to create a new PendingList structure containing two
125622** varints:
125623**
125624**   PendingList *p = 0;
125625**   fts3PendingListAppendVarint(&p, 1);
125626**   fts3PendingListAppendVarint(&p, 2);
125627*/
125628static int fts3PendingListAppendVarint(
125629  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
125630  sqlite3_int64 i                 /* Value to append to data */
125631){
125632  PendingList *p = *pp;
125633
125634  /* Allocate or grow the PendingList as required. */
125635  if( !p ){
125636    p = sqlite3_malloc(sizeof(*p) + 100);
125637    if( !p ){
125638      return SQLITE_NOMEM;
125639    }
125640    p->nSpace = 100;
125641    p->aData = (char *)&p[1];
125642    p->nData = 0;
125643  }
125644  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
125645    int nNew = p->nSpace * 2;
125646    p = sqlite3_realloc(p, sizeof(*p) + nNew);
125647    if( !p ){
125648      sqlite3_free(*pp);
125649      *pp = 0;
125650      return SQLITE_NOMEM;
125651    }
125652    p->nSpace = nNew;
125653    p->aData = (char *)&p[1];
125654  }
125655
125656  /* Append the new serialized varint to the end of the list. */
125657  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
125658  p->aData[p->nData] = '\0';
125659  *pp = p;
125660  return SQLITE_OK;
125661}
125662
125663/*
125664** Add a docid/column/position entry to a PendingList structure. Non-zero
125665** is returned if the structure is sqlite3_realloced as part of adding
125666** the entry. Otherwise, zero.
125667**
125668** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
125669** Zero is always returned in this case. Otherwise, if no OOM error occurs,
125670** it is set to SQLITE_OK.
125671*/
125672static int fts3PendingListAppend(
125673  PendingList **pp,               /* IN/OUT: PendingList structure */
125674  sqlite3_int64 iDocid,           /* Docid for entry to add */
125675  sqlite3_int64 iCol,             /* Column for entry to add */
125676  sqlite3_int64 iPos,             /* Position of term for entry to add */
125677  int *pRc                        /* OUT: Return code */
125678){
125679  PendingList *p = *pp;
125680  int rc = SQLITE_OK;
125681
125682  assert( !p || p->iLastDocid<=iDocid );
125683
125684  if( !p || p->iLastDocid!=iDocid ){
125685    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
125686    if( p ){
125687      assert( p->nData<p->nSpace );
125688      assert( p->aData[p->nData]==0 );
125689      p->nData++;
125690    }
125691    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
125692      goto pendinglistappend_out;
125693    }
125694    p->iLastCol = -1;
125695    p->iLastPos = 0;
125696    p->iLastDocid = iDocid;
125697  }
125698  if( iCol>0 && p->iLastCol!=iCol ){
125699    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
125700     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
125701    ){
125702      goto pendinglistappend_out;
125703    }
125704    p->iLastCol = iCol;
125705    p->iLastPos = 0;
125706  }
125707  if( iCol>=0 ){
125708    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
125709    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
125710    if( rc==SQLITE_OK ){
125711      p->iLastPos = iPos;
125712    }
125713  }
125714
125715 pendinglistappend_out:
125716  *pRc = rc;
125717  if( p!=*pp ){
125718    *pp = p;
125719    return 1;
125720  }
125721  return 0;
125722}
125723
125724/*
125725** Free a PendingList object allocated by fts3PendingListAppend().
125726*/
125727static void fts3PendingListDelete(PendingList *pList){
125728  sqlite3_free(pList);
125729}
125730
125731/*
125732** Add an entry to one of the pending-terms hash tables.
125733*/
125734static int fts3PendingTermsAddOne(
125735  Fts3Table *p,
125736  int iCol,
125737  int iPos,
125738  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
125739  const char *zToken,
125740  int nToken
125741){
125742  PendingList *pList;
125743  int rc = SQLITE_OK;
125744
125745  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
125746  if( pList ){
125747    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
125748  }
125749  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
125750    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
125751      /* Malloc failed while inserting the new entry. This can only
125752      ** happen if there was no previous entry for this token.
125753      */
125754      assert( 0==fts3HashFind(pHash, zToken, nToken) );
125755      sqlite3_free(pList);
125756      rc = SQLITE_NOMEM;
125757    }
125758  }
125759  if( rc==SQLITE_OK ){
125760    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
125761  }
125762  return rc;
125763}
125764
125765/*
125766** Tokenize the nul-terminated string zText and add all tokens to the
125767** pending-terms hash-table. The docid used is that currently stored in
125768** p->iPrevDocid, and the column is specified by argument iCol.
125769**
125770** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
125771*/
125772static int fts3PendingTermsAdd(
125773  Fts3Table *p,                   /* Table into which text will be inserted */
125774  int iLangid,                    /* Language id to use */
125775  const char *zText,              /* Text of document to be inserted */
125776  int iCol,                       /* Column into which text is being inserted */
125777  u32 *pnWord                     /* OUT: Number of tokens inserted */
125778){
125779  int rc;
125780  int iStart;
125781  int iEnd;
125782  int iPos;
125783  int nWord = 0;
125784
125785  char const *zToken;
125786  int nToken;
125787
125788  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
125789  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
125790  sqlite3_tokenizer_cursor *pCsr;
125791  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
125792      const char**,int*,int*,int*,int*);
125793
125794  assert( pTokenizer && pModule );
125795
125796  /* If the user has inserted a NULL value, this function may be called with
125797  ** zText==0. In this case, add zero token entries to the hash table and
125798  ** return early. */
125799  if( zText==0 ){
125800    *pnWord = 0;
125801    return SQLITE_OK;
125802  }
125803
125804  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
125805  if( rc!=SQLITE_OK ){
125806    return rc;
125807  }
125808
125809  xNext = pModule->xNext;
125810  while( SQLITE_OK==rc
125811      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
125812  ){
125813    int i;
125814    if( iPos>=nWord ) nWord = iPos+1;
125815
125816    /* Positions cannot be negative; we use -1 as a terminator internally.
125817    ** Tokens must have a non-zero length.
125818    */
125819    if( iPos<0 || !zToken || nToken<=0 ){
125820      rc = SQLITE_ERROR;
125821      break;
125822    }
125823
125824    /* Add the term to the terms index */
125825    rc = fts3PendingTermsAddOne(
125826        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
125827    );
125828
125829    /* Add the term to each of the prefix indexes that it is not too
125830    ** short for. */
125831    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
125832      struct Fts3Index *pIndex = &p->aIndex[i];
125833      if( nToken<pIndex->nPrefix ) continue;
125834      rc = fts3PendingTermsAddOne(
125835          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
125836      );
125837    }
125838  }
125839
125840  pModule->xClose(pCsr);
125841  *pnWord = nWord;
125842  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
125843}
125844
125845/*
125846** Calling this function indicates that subsequent calls to
125847** fts3PendingTermsAdd() are to add term/position-list pairs for the
125848** contents of the document with docid iDocid.
125849*/
125850static int fts3PendingTermsDocid(
125851  Fts3Table *p,                   /* Full-text table handle */
125852  int iLangid,                    /* Language id of row being written */
125853  sqlite_int64 iDocid             /* Docid of row being written */
125854){
125855  assert( iLangid>=0 );
125856
125857  /* TODO(shess) Explore whether partially flushing the buffer on
125858  ** forced-flush would provide better performance.  I suspect that if
125859  ** we ordered the doclists by size and flushed the largest until the
125860  ** buffer was half empty, that would let the less frequent terms
125861  ** generate longer doclists.
125862  */
125863  if( iDocid<=p->iPrevDocid
125864   || p->iPrevLangid!=iLangid
125865   || p->nPendingData>p->nMaxPendingData
125866  ){
125867    int rc = sqlite3Fts3PendingTermsFlush(p);
125868    if( rc!=SQLITE_OK ) return rc;
125869  }
125870  p->iPrevDocid = iDocid;
125871  p->iPrevLangid = iLangid;
125872  return SQLITE_OK;
125873}
125874
125875/*
125876** Discard the contents of the pending-terms hash tables.
125877*/
125878SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
125879  int i;
125880  for(i=0; i<p->nIndex; i++){
125881    Fts3HashElem *pElem;
125882    Fts3Hash *pHash = &p->aIndex[i].hPending;
125883    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
125884      PendingList *pList = (PendingList *)fts3HashData(pElem);
125885      fts3PendingListDelete(pList);
125886    }
125887    fts3HashClear(pHash);
125888  }
125889  p->nPendingData = 0;
125890}
125891
125892/*
125893** This function is called by the xUpdate() method as part of an INSERT
125894** operation. It adds entries for each term in the new record to the
125895** pendingTerms hash table.
125896**
125897** Argument apVal is the same as the similarly named argument passed to
125898** fts3InsertData(). Parameter iDocid is the docid of the new row.
125899*/
125900static int fts3InsertTerms(
125901  Fts3Table *p,
125902  int iLangid,
125903  sqlite3_value **apVal,
125904  u32 *aSz
125905){
125906  int i;                          /* Iterator variable */
125907  for(i=2; i<p->nColumn+2; i++){
125908    const char *zText = (const char *)sqlite3_value_text(apVal[i]);
125909    int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
125910    if( rc!=SQLITE_OK ){
125911      return rc;
125912    }
125913    aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
125914  }
125915  return SQLITE_OK;
125916}
125917
125918/*
125919** This function is called by the xUpdate() method for an INSERT operation.
125920** The apVal parameter is passed a copy of the apVal argument passed by
125921** SQLite to the xUpdate() method. i.e:
125922**
125923**   apVal[0]                Not used for INSERT.
125924**   apVal[1]                rowid
125925**   apVal[2]                Left-most user-defined column
125926**   ...
125927**   apVal[p->nColumn+1]     Right-most user-defined column
125928**   apVal[p->nColumn+2]     Hidden column with same name as table
125929**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
125930**   apVal[p->nColumn+4]     Hidden languageid column
125931*/
125932static int fts3InsertData(
125933  Fts3Table *p,                   /* Full-text table */
125934  sqlite3_value **apVal,          /* Array of values to insert */
125935  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
125936){
125937  int rc;                         /* Return code */
125938  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
125939
125940  if( p->zContentTbl ){
125941    sqlite3_value *pRowid = apVal[p->nColumn+3];
125942    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
125943      pRowid = apVal[1];
125944    }
125945    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
125946      return SQLITE_CONSTRAINT;
125947    }
125948    *piDocid = sqlite3_value_int64(pRowid);
125949    return SQLITE_OK;
125950  }
125951
125952  /* Locate the statement handle used to insert data into the %_content
125953  ** table. The SQL for this statement is:
125954  **
125955  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
125956  **
125957  ** The statement features N '?' variables, where N is the number of user
125958  ** defined columns in the FTS3 table, plus one for the docid field.
125959  */
125960  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
125961  if( rc==SQLITE_OK && p->zLanguageid ){
125962    rc = sqlite3_bind_int(
125963        pContentInsert, p->nColumn+2,
125964        sqlite3_value_int(apVal[p->nColumn+4])
125965    );
125966  }
125967  if( rc!=SQLITE_OK ) return rc;
125968
125969  /* There is a quirk here. The users INSERT statement may have specified
125970  ** a value for the "rowid" field, for the "docid" field, or for both.
125971  ** Which is a problem, since "rowid" and "docid" are aliases for the
125972  ** same value. For example:
125973  **
125974  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
125975  **
125976  ** In FTS3, this is an error. It is an error to specify non-NULL values
125977  ** for both docid and some other rowid alias.
125978  */
125979  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
125980    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
125981     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
125982    ){
125983      /* A rowid/docid conflict. */
125984      return SQLITE_ERROR;
125985    }
125986    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
125987    if( rc!=SQLITE_OK ) return rc;
125988  }
125989
125990  /* Execute the statement to insert the record. Set *piDocid to the
125991  ** new docid value.
125992  */
125993  sqlite3_step(pContentInsert);
125994  rc = sqlite3_reset(pContentInsert);
125995
125996  *piDocid = sqlite3_last_insert_rowid(p->db);
125997  return rc;
125998}
125999
126000
126001
126002/*
126003** Remove all data from the FTS3 table. Clear the hash table containing
126004** pending terms.
126005*/
126006static int fts3DeleteAll(Fts3Table *p, int bContent){
126007  int rc = SQLITE_OK;             /* Return code */
126008
126009  /* Discard the contents of the pending-terms hash table. */
126010  sqlite3Fts3PendingTermsClear(p);
126011
126012  /* Delete everything from the shadow tables. Except, leave %_content as
126013  ** is if bContent is false.  */
126014  assert( p->zContentTbl==0 || bContent==0 );
126015  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
126016  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
126017  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
126018  if( p->bHasDocsize ){
126019    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
126020  }
126021  if( p->bHasStat ){
126022    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
126023  }
126024  return rc;
126025}
126026
126027/*
126028**
126029*/
126030static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
126031  int iLangid = 0;
126032  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
126033  return iLangid;
126034}
126035
126036/*
126037** The first element in the apVal[] array is assumed to contain the docid
126038** (an integer) of a row about to be deleted. Remove all terms from the
126039** full-text index.
126040*/
126041static void fts3DeleteTerms(
126042  int *pRC,               /* Result code */
126043  Fts3Table *p,           /* The FTS table to delete from */
126044  sqlite3_value *pRowid,  /* The docid to be deleted */
126045  u32 *aSz                /* Sizes of deleted document written here */
126046){
126047  int rc;
126048  sqlite3_stmt *pSelect;
126049
126050  if( *pRC ) return;
126051  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
126052  if( rc==SQLITE_OK ){
126053    if( SQLITE_ROW==sqlite3_step(pSelect) ){
126054      int i;
126055      int iLangid = langidFromSelect(p, pSelect);
126056      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
126057      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
126058        const char *zText = (const char *)sqlite3_column_text(pSelect, i);
126059        rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
126060        aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
126061      }
126062      if( rc!=SQLITE_OK ){
126063        sqlite3_reset(pSelect);
126064        *pRC = rc;
126065        return;
126066      }
126067    }
126068    rc = sqlite3_reset(pSelect);
126069  }else{
126070    sqlite3_reset(pSelect);
126071  }
126072  *pRC = rc;
126073}
126074
126075/*
126076** Forward declaration to account for the circular dependency between
126077** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
126078*/
126079static int fts3SegmentMerge(Fts3Table *, int, int, int);
126080
126081/*
126082** This function allocates a new level iLevel index in the segdir table.
126083** Usually, indexes are allocated within a level sequentially starting
126084** with 0, so the allocated index is one greater than the value returned
126085** by:
126086**
126087**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
126088**
126089** However, if there are already FTS3_MERGE_COUNT indexes at the requested
126090** level, they are merged into a single level (iLevel+1) segment and the
126091** allocated index is 0.
126092**
126093** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
126094** returned. Otherwise, an SQLite error code is returned.
126095*/
126096static int fts3AllocateSegdirIdx(
126097  Fts3Table *p,
126098  int iLangid,                    /* Language id */
126099  int iIndex,                     /* Index for p->aIndex */
126100  int iLevel,
126101  int *piIdx
126102){
126103  int rc;                         /* Return Code */
126104  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
126105  int iNext = 0;                  /* Result of query pNextIdx */
126106
126107  assert( iLangid>=0 );
126108  assert( p->nIndex>=1 );
126109
126110  /* Set variable iNext to the next available segdir index at level iLevel. */
126111  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
126112  if( rc==SQLITE_OK ){
126113    sqlite3_bind_int64(
126114        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
126115    );
126116    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
126117      iNext = sqlite3_column_int(pNextIdx, 0);
126118    }
126119    rc = sqlite3_reset(pNextIdx);
126120  }
126121
126122  if( rc==SQLITE_OK ){
126123    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
126124    ** full, merge all segments in level iLevel into a single iLevel+1
126125    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
126126    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
126127    */
126128    if( iNext>=FTS3_MERGE_COUNT ){
126129      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
126130      *piIdx = 0;
126131    }else{
126132      *piIdx = iNext;
126133    }
126134  }
126135
126136  return rc;
126137}
126138
126139/*
126140** The %_segments table is declared as follows:
126141**
126142**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
126143**
126144** This function reads data from a single row of the %_segments table. The
126145** specific row is identified by the iBlockid parameter. If paBlob is not
126146** NULL, then a buffer is allocated using sqlite3_malloc() and populated
126147** with the contents of the blob stored in the "block" column of the
126148** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
126149** to the size of the blob in bytes before returning.
126150**
126151** If an error occurs, or the table does not contain the specified row,
126152** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
126153** paBlob is non-NULL, then it is the responsibility of the caller to
126154** eventually free the returned buffer.
126155**
126156** This function may leave an open sqlite3_blob* handle in the
126157** Fts3Table.pSegments variable. This handle is reused by subsequent calls
126158** to this function. The handle may be closed by calling the
126159** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
126160** performance improvement, but the blob handle should always be closed
126161** before control is returned to the user (to prevent a lock being held
126162** on the database file for longer than necessary). Thus, any virtual table
126163** method (xFilter etc.) that may directly or indirectly call this function
126164** must call sqlite3Fts3SegmentsClose() before returning.
126165*/
126166SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
126167  Fts3Table *p,                   /* FTS3 table handle */
126168  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
126169  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
126170  int *pnBlob,                    /* OUT: Size of blob data */
126171  int *pnLoad                     /* OUT: Bytes actually loaded */
126172){
126173  int rc;                         /* Return code */
126174
126175  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
126176  assert( pnBlob);
126177
126178  if( p->pSegments ){
126179    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
126180  }else{
126181    if( 0==p->zSegmentsTbl ){
126182      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
126183      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
126184    }
126185    rc = sqlite3_blob_open(
126186       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
126187    );
126188  }
126189
126190  if( rc==SQLITE_OK ){
126191    int nByte = sqlite3_blob_bytes(p->pSegments);
126192    *pnBlob = nByte;
126193    if( paBlob ){
126194      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
126195      if( !aByte ){
126196        rc = SQLITE_NOMEM;
126197      }else{
126198        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
126199          nByte = FTS3_NODE_CHUNKSIZE;
126200          *pnLoad = nByte;
126201        }
126202        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
126203        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
126204        if( rc!=SQLITE_OK ){
126205          sqlite3_free(aByte);
126206          aByte = 0;
126207        }
126208      }
126209      *paBlob = aByte;
126210    }
126211  }
126212
126213  return rc;
126214}
126215
126216/*
126217** Close the blob handle at p->pSegments, if it is open. See comments above
126218** the sqlite3Fts3ReadBlock() function for details.
126219*/
126220SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
126221  sqlite3_blob_close(p->pSegments);
126222  p->pSegments = 0;
126223}
126224
126225static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
126226  int nRead;                      /* Number of bytes to read */
126227  int rc;                         /* Return code */
126228
126229  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
126230  rc = sqlite3_blob_read(
126231      pReader->pBlob,
126232      &pReader->aNode[pReader->nPopulate],
126233      nRead,
126234      pReader->nPopulate
126235  );
126236
126237  if( rc==SQLITE_OK ){
126238    pReader->nPopulate += nRead;
126239    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
126240    if( pReader->nPopulate==pReader->nNode ){
126241      sqlite3_blob_close(pReader->pBlob);
126242      pReader->pBlob = 0;
126243      pReader->nPopulate = 0;
126244    }
126245  }
126246  return rc;
126247}
126248
126249static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
126250  int rc = SQLITE_OK;
126251  assert( !pReader->pBlob
126252       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
126253  );
126254  while( pReader->pBlob && rc==SQLITE_OK
126255     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
126256  ){
126257    rc = fts3SegReaderIncrRead(pReader);
126258  }
126259  return rc;
126260}
126261
126262/*
126263** Set an Fts3SegReader cursor to point at EOF.
126264*/
126265static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
126266  if( !fts3SegReaderIsRootOnly(pSeg) ){
126267    sqlite3_free(pSeg->aNode);
126268    sqlite3_blob_close(pSeg->pBlob);
126269    pSeg->pBlob = 0;
126270  }
126271  pSeg->aNode = 0;
126272}
126273
126274/*
126275** Move the iterator passed as the first argument to the next term in the
126276** segment. If successful, SQLITE_OK is returned. If there is no next term,
126277** SQLITE_DONE. Otherwise, an SQLite error code.
126278*/
126279static int fts3SegReaderNext(
126280  Fts3Table *p,
126281  Fts3SegReader *pReader,
126282  int bIncr
126283){
126284  int rc;                         /* Return code of various sub-routines */
126285  char *pNext;                    /* Cursor variable */
126286  int nPrefix;                    /* Number of bytes in term prefix */
126287  int nSuffix;                    /* Number of bytes in term suffix */
126288
126289  if( !pReader->aDoclist ){
126290    pNext = pReader->aNode;
126291  }else{
126292    pNext = &pReader->aDoclist[pReader->nDoclist];
126293  }
126294
126295  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
126296
126297    if( fts3SegReaderIsPending(pReader) ){
126298      Fts3HashElem *pElem = *(pReader->ppNextElem);
126299      if( pElem==0 ){
126300        pReader->aNode = 0;
126301      }else{
126302        PendingList *pList = (PendingList *)fts3HashData(pElem);
126303        pReader->zTerm = (char *)fts3HashKey(pElem);
126304        pReader->nTerm = fts3HashKeysize(pElem);
126305        pReader->nNode = pReader->nDoclist = pList->nData + 1;
126306        pReader->aNode = pReader->aDoclist = pList->aData;
126307        pReader->ppNextElem++;
126308        assert( pReader->aNode );
126309      }
126310      return SQLITE_OK;
126311    }
126312
126313    fts3SegReaderSetEof(pReader);
126314
126315    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
126316    ** blocks have already been traversed.  */
126317    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
126318    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
126319      return SQLITE_OK;
126320    }
126321
126322    rc = sqlite3Fts3ReadBlock(
126323        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
126324        (bIncr ? &pReader->nPopulate : 0)
126325    );
126326    if( rc!=SQLITE_OK ) return rc;
126327    assert( pReader->pBlob==0 );
126328    if( bIncr && pReader->nPopulate<pReader->nNode ){
126329      pReader->pBlob = p->pSegments;
126330      p->pSegments = 0;
126331    }
126332    pNext = pReader->aNode;
126333  }
126334
126335  assert( !fts3SegReaderIsPending(pReader) );
126336
126337  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
126338  if( rc!=SQLITE_OK ) return rc;
126339
126340  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
126341  ** safe (no risk of overread) even if the node data is corrupted. */
126342  pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
126343  pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
126344  if( nPrefix<0 || nSuffix<=0
126345   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
126346  ){
126347    return FTS_CORRUPT_VTAB;
126348  }
126349
126350  if( nPrefix+nSuffix>pReader->nTermAlloc ){
126351    int nNew = (nPrefix+nSuffix)*2;
126352    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
126353    if( !zNew ){
126354      return SQLITE_NOMEM;
126355    }
126356    pReader->zTerm = zNew;
126357    pReader->nTermAlloc = nNew;
126358  }
126359
126360  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
126361  if( rc!=SQLITE_OK ) return rc;
126362
126363  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
126364  pReader->nTerm = nPrefix+nSuffix;
126365  pNext += nSuffix;
126366  pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
126367  pReader->aDoclist = pNext;
126368  pReader->pOffsetList = 0;
126369
126370  /* Check that the doclist does not appear to extend past the end of the
126371  ** b-tree node. And that the final byte of the doclist is 0x00. If either
126372  ** of these statements is untrue, then the data structure is corrupt.
126373  */
126374  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
126375   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
126376  ){
126377    return FTS_CORRUPT_VTAB;
126378  }
126379  return SQLITE_OK;
126380}
126381
126382/*
126383** Set the SegReader to point to the first docid in the doclist associated
126384** with the current term.
126385*/
126386static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
126387  int rc = SQLITE_OK;
126388  assert( pReader->aDoclist );
126389  assert( !pReader->pOffsetList );
126390  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
126391    u8 bEof = 0;
126392    pReader->iDocid = 0;
126393    pReader->nOffsetList = 0;
126394    sqlite3Fts3DoclistPrev(0,
126395        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
126396        &pReader->iDocid, &pReader->nOffsetList, &bEof
126397    );
126398  }else{
126399    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
126400    if( rc==SQLITE_OK ){
126401      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
126402      pReader->pOffsetList = &pReader->aDoclist[n];
126403    }
126404  }
126405  return rc;
126406}
126407
126408/*
126409** Advance the SegReader to point to the next docid in the doclist
126410** associated with the current term.
126411**
126412** If arguments ppOffsetList and pnOffsetList are not NULL, then
126413** *ppOffsetList is set to point to the first column-offset list
126414** in the doclist entry (i.e. immediately past the docid varint).
126415** *pnOffsetList is set to the length of the set of column-offset
126416** lists, not including the nul-terminator byte. For example:
126417*/
126418static int fts3SegReaderNextDocid(
126419  Fts3Table *pTab,
126420  Fts3SegReader *pReader,         /* Reader to advance to next docid */
126421  char **ppOffsetList,            /* OUT: Pointer to current position-list */
126422  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
126423){
126424  int rc = SQLITE_OK;
126425  char *p = pReader->pOffsetList;
126426  char c = 0;
126427
126428  assert( p );
126429
126430  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
126431    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
126432    ** Pending-terms doclists are always built up in ascending order, so
126433    ** we have to iterate through them backwards here. */
126434    u8 bEof = 0;
126435    if( ppOffsetList ){
126436      *ppOffsetList = pReader->pOffsetList;
126437      *pnOffsetList = pReader->nOffsetList - 1;
126438    }
126439    sqlite3Fts3DoclistPrev(0,
126440        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
126441        &pReader->nOffsetList, &bEof
126442    );
126443    if( bEof ){
126444      pReader->pOffsetList = 0;
126445    }else{
126446      pReader->pOffsetList = p;
126447    }
126448  }else{
126449    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
126450
126451    /* Pointer p currently points at the first byte of an offset list. The
126452    ** following block advances it to point one byte past the end of
126453    ** the same offset list. */
126454    while( 1 ){
126455
126456      /* The following line of code (and the "p++" below the while() loop) is
126457      ** normally all that is required to move pointer p to the desired
126458      ** position. The exception is if this node is being loaded from disk
126459      ** incrementally and pointer "p" now points to the first byte passed
126460      ** the populated part of pReader->aNode[].
126461      */
126462      while( *p | c ) c = *p++ & 0x80;
126463      assert( *p==0 );
126464
126465      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
126466      rc = fts3SegReaderIncrRead(pReader);
126467      if( rc!=SQLITE_OK ) return rc;
126468    }
126469    p++;
126470
126471    /* If required, populate the output variables with a pointer to and the
126472    ** size of the previous offset-list.
126473    */
126474    if( ppOffsetList ){
126475      *ppOffsetList = pReader->pOffsetList;
126476      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
126477    }
126478
126479    while( p<pEnd && *p==0 ) p++;
126480
126481    /* If there are no more entries in the doclist, set pOffsetList to
126482    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
126483    ** Fts3SegReader.pOffsetList to point to the next offset list before
126484    ** returning.
126485    */
126486    if( p>=pEnd ){
126487      pReader->pOffsetList = 0;
126488    }else{
126489      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
126490      if( rc==SQLITE_OK ){
126491        sqlite3_int64 iDelta;
126492        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
126493        if( pTab->bDescIdx ){
126494          pReader->iDocid -= iDelta;
126495        }else{
126496          pReader->iDocid += iDelta;
126497        }
126498      }
126499    }
126500  }
126501
126502  return SQLITE_OK;
126503}
126504
126505
126506SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
126507  Fts3Cursor *pCsr,
126508  Fts3MultiSegReader *pMsr,
126509  int *pnOvfl
126510){
126511  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
126512  int nOvfl = 0;
126513  int ii;
126514  int rc = SQLITE_OK;
126515  int pgsz = p->nPgsz;
126516
126517  assert( p->bHasStat );
126518  assert( pgsz>0 );
126519
126520  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
126521    Fts3SegReader *pReader = pMsr->apSegment[ii];
126522    if( !fts3SegReaderIsPending(pReader)
126523     && !fts3SegReaderIsRootOnly(pReader)
126524    ){
126525      sqlite3_int64 jj;
126526      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
126527        int nBlob;
126528        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
126529        if( rc!=SQLITE_OK ) break;
126530        if( (nBlob+35)>pgsz ){
126531          nOvfl += (nBlob + 34)/pgsz;
126532        }
126533      }
126534    }
126535  }
126536  *pnOvfl = nOvfl;
126537  return rc;
126538}
126539
126540/*
126541** Free all allocations associated with the iterator passed as the
126542** second argument.
126543*/
126544SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
126545  if( pReader && !fts3SegReaderIsPending(pReader) ){
126546    sqlite3_free(pReader->zTerm);
126547    if( !fts3SegReaderIsRootOnly(pReader) ){
126548      sqlite3_free(pReader->aNode);
126549      sqlite3_blob_close(pReader->pBlob);
126550    }
126551  }
126552  sqlite3_free(pReader);
126553}
126554
126555/*
126556** Allocate a new SegReader object.
126557*/
126558SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
126559  int iAge,                       /* Segment "age". */
126560  int bLookup,                    /* True for a lookup only */
126561  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
126562  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
126563  sqlite3_int64 iEndBlock,        /* Final block of segment */
126564  const char *zRoot,              /* Buffer containing root node */
126565  int nRoot,                      /* Size of buffer containing root node */
126566  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
126567){
126568  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
126569  int nExtra = 0;                 /* Bytes to allocate segment root node */
126570
126571  assert( iStartLeaf<=iEndLeaf );
126572  if( iStartLeaf==0 ){
126573    nExtra = nRoot + FTS3_NODE_PADDING;
126574  }
126575
126576  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
126577  if( !pReader ){
126578    return SQLITE_NOMEM;
126579  }
126580  memset(pReader, 0, sizeof(Fts3SegReader));
126581  pReader->iIdx = iAge;
126582  pReader->bLookup = bLookup;
126583  pReader->iStartBlock = iStartLeaf;
126584  pReader->iLeafEndBlock = iEndLeaf;
126585  pReader->iEndBlock = iEndBlock;
126586
126587  if( nExtra ){
126588    /* The entire segment is stored in the root node. */
126589    pReader->aNode = (char *)&pReader[1];
126590    pReader->nNode = nRoot;
126591    memcpy(pReader->aNode, zRoot, nRoot);
126592    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
126593  }else{
126594    pReader->iCurrentBlock = iStartLeaf-1;
126595  }
126596  *ppReader = pReader;
126597  return SQLITE_OK;
126598}
126599
126600/*
126601** This is a comparison function used as a qsort() callback when sorting
126602** an array of pending terms by term. This occurs as part of flushing
126603** the contents of the pending-terms hash table to the database.
126604*/
126605static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
126606  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
126607  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
126608  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
126609  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
126610
126611  int n = (n1<n2 ? n1 : n2);
126612  int c = memcmp(z1, z2, n);
126613  if( c==0 ){
126614    c = n1 - n2;
126615  }
126616  return c;
126617}
126618
126619/*
126620** This function is used to allocate an Fts3SegReader that iterates through
126621** a subset of the terms stored in the Fts3Table.pendingTerms array.
126622**
126623** If the isPrefixIter parameter is zero, then the returned SegReader iterates
126624** through each term in the pending-terms table. Or, if isPrefixIter is
126625** non-zero, it iterates through each term and its prefixes. For example, if
126626** the pending terms hash table contains the terms "sqlite", "mysql" and
126627** "firebird", then the iterator visits the following 'terms' (in the order
126628** shown):
126629**
126630**   f fi fir fire fireb firebi firebir firebird
126631**   m my mys mysq mysql
126632**   s sq sql sqli sqlit sqlite
126633**
126634** Whereas if isPrefixIter is zero, the terms visited are:
126635**
126636**   firebird mysql sqlite
126637*/
126638SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
126639  Fts3Table *p,                   /* Virtual table handle */
126640  int iIndex,                     /* Index for p->aIndex */
126641  const char *zTerm,              /* Term to search for */
126642  int nTerm,                      /* Size of buffer zTerm */
126643  int bPrefix,                    /* True for a prefix iterator */
126644  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
126645){
126646  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
126647  Fts3HashElem *pE;               /* Iterator variable */
126648  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
126649  int nElem = 0;                  /* Size of array at aElem */
126650  int rc = SQLITE_OK;             /* Return Code */
126651  Fts3Hash *pHash;
126652
126653  pHash = &p->aIndex[iIndex].hPending;
126654  if( bPrefix ){
126655    int nAlloc = 0;               /* Size of allocated array at aElem */
126656
126657    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
126658      char *zKey = (char *)fts3HashKey(pE);
126659      int nKey = fts3HashKeysize(pE);
126660      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
126661        if( nElem==nAlloc ){
126662          Fts3HashElem **aElem2;
126663          nAlloc += 16;
126664          aElem2 = (Fts3HashElem **)sqlite3_realloc(
126665              aElem, nAlloc*sizeof(Fts3HashElem *)
126666          );
126667          if( !aElem2 ){
126668            rc = SQLITE_NOMEM;
126669            nElem = 0;
126670            break;
126671          }
126672          aElem = aElem2;
126673        }
126674
126675        aElem[nElem++] = pE;
126676      }
126677    }
126678
126679    /* If more than one term matches the prefix, sort the Fts3HashElem
126680    ** objects in term order using qsort(). This uses the same comparison
126681    ** callback as is used when flushing terms to disk.
126682    */
126683    if( nElem>1 ){
126684      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
126685    }
126686
126687  }else{
126688    /* The query is a simple term lookup that matches at most one term in
126689    ** the index. All that is required is a straight hash-lookup.
126690    **
126691    ** Because the stack address of pE may be accessed via the aElem pointer
126692    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
126693    ** within this entire function, not just this "else{...}" block.
126694    */
126695    pE = fts3HashFindElem(pHash, zTerm, nTerm);
126696    if( pE ){
126697      aElem = &pE;
126698      nElem = 1;
126699    }
126700  }
126701
126702  if( nElem>0 ){
126703    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
126704    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
126705    if( !pReader ){
126706      rc = SQLITE_NOMEM;
126707    }else{
126708      memset(pReader, 0, nByte);
126709      pReader->iIdx = 0x7FFFFFFF;
126710      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
126711      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
126712    }
126713  }
126714
126715  if( bPrefix ){
126716    sqlite3_free(aElem);
126717  }
126718  *ppReader = pReader;
126719  return rc;
126720}
126721
126722/*
126723** Compare the entries pointed to by two Fts3SegReader structures.
126724** Comparison is as follows:
126725**
126726**   1) EOF is greater than not EOF.
126727**
126728**   2) The current terms (if any) are compared using memcmp(). If one
126729**      term is a prefix of another, the longer term is considered the
126730**      larger.
126731**
126732**   3) By segment age. An older segment is considered larger.
126733*/
126734static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
126735  int rc;
126736  if( pLhs->aNode && pRhs->aNode ){
126737    int rc2 = pLhs->nTerm - pRhs->nTerm;
126738    if( rc2<0 ){
126739      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
126740    }else{
126741      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
126742    }
126743    if( rc==0 ){
126744      rc = rc2;
126745    }
126746  }else{
126747    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
126748  }
126749  if( rc==0 ){
126750    rc = pRhs->iIdx - pLhs->iIdx;
126751  }
126752  assert( rc!=0 );
126753  return rc;
126754}
126755
126756/*
126757** A different comparison function for SegReader structures. In this
126758** version, it is assumed that each SegReader points to an entry in
126759** a doclist for identical terms. Comparison is made as follows:
126760**
126761**   1) EOF (end of doclist in this case) is greater than not EOF.
126762**
126763**   2) By current docid.
126764**
126765**   3) By segment age. An older segment is considered larger.
126766*/
126767static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
126768  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
126769  if( rc==0 ){
126770    if( pLhs->iDocid==pRhs->iDocid ){
126771      rc = pRhs->iIdx - pLhs->iIdx;
126772    }else{
126773      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
126774    }
126775  }
126776  assert( pLhs->aNode && pRhs->aNode );
126777  return rc;
126778}
126779static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
126780  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
126781  if( rc==0 ){
126782    if( pLhs->iDocid==pRhs->iDocid ){
126783      rc = pRhs->iIdx - pLhs->iIdx;
126784    }else{
126785      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
126786    }
126787  }
126788  assert( pLhs->aNode && pRhs->aNode );
126789  return rc;
126790}
126791
126792/*
126793** Compare the term that the Fts3SegReader object passed as the first argument
126794** points to with the term specified by arguments zTerm and nTerm.
126795**
126796** If the pSeg iterator is already at EOF, return 0. Otherwise, return
126797** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
126798** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
126799*/
126800static int fts3SegReaderTermCmp(
126801  Fts3SegReader *pSeg,            /* Segment reader object */
126802  const char *zTerm,              /* Term to compare to */
126803  int nTerm                       /* Size of term zTerm in bytes */
126804){
126805  int res = 0;
126806  if( pSeg->aNode ){
126807    if( pSeg->nTerm>nTerm ){
126808      res = memcmp(pSeg->zTerm, zTerm, nTerm);
126809    }else{
126810      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
126811    }
126812    if( res==0 ){
126813      res = pSeg->nTerm-nTerm;
126814    }
126815  }
126816  return res;
126817}
126818
126819/*
126820** Argument apSegment is an array of nSegment elements. It is known that
126821** the final (nSegment-nSuspect) members are already in sorted order
126822** (according to the comparison function provided). This function shuffles
126823** the array around until all entries are in sorted order.
126824*/
126825static void fts3SegReaderSort(
126826  Fts3SegReader **apSegment,                     /* Array to sort entries of */
126827  int nSegment,                                  /* Size of apSegment array */
126828  int nSuspect,                                  /* Unsorted entry count */
126829  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
126830){
126831  int i;                          /* Iterator variable */
126832
126833  assert( nSuspect<=nSegment );
126834
126835  if( nSuspect==nSegment ) nSuspect--;
126836  for(i=nSuspect-1; i>=0; i--){
126837    int j;
126838    for(j=i; j<(nSegment-1); j++){
126839      Fts3SegReader *pTmp;
126840      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
126841      pTmp = apSegment[j+1];
126842      apSegment[j+1] = apSegment[j];
126843      apSegment[j] = pTmp;
126844    }
126845  }
126846
126847#ifndef NDEBUG
126848  /* Check that the list really is sorted now. */
126849  for(i=0; i<(nSuspect-1); i++){
126850    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
126851  }
126852#endif
126853}
126854
126855/*
126856** Insert a record into the %_segments table.
126857*/
126858static int fts3WriteSegment(
126859  Fts3Table *p,                   /* Virtual table handle */
126860  sqlite3_int64 iBlock,           /* Block id for new block */
126861  char *z,                        /* Pointer to buffer containing block data */
126862  int n                           /* Size of buffer z in bytes */
126863){
126864  sqlite3_stmt *pStmt;
126865  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
126866  if( rc==SQLITE_OK ){
126867    sqlite3_bind_int64(pStmt, 1, iBlock);
126868    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
126869    sqlite3_step(pStmt);
126870    rc = sqlite3_reset(pStmt);
126871  }
126872  return rc;
126873}
126874
126875/*
126876** Insert a record into the %_segdir table.
126877*/
126878static int fts3WriteSegdir(
126879  Fts3Table *p,                   /* Virtual table handle */
126880  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
126881  int iIdx,                       /* Value for "idx" field */
126882  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
126883  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
126884  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
126885  char *zRoot,                    /* Blob value for "root" field */
126886  int nRoot                       /* Number of bytes in buffer zRoot */
126887){
126888  sqlite3_stmt *pStmt;
126889  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
126890  if( rc==SQLITE_OK ){
126891    sqlite3_bind_int64(pStmt, 1, iLevel);
126892    sqlite3_bind_int(pStmt, 2, iIdx);
126893    sqlite3_bind_int64(pStmt, 3, iStartBlock);
126894    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
126895    sqlite3_bind_int64(pStmt, 5, iEndBlock);
126896    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
126897    sqlite3_step(pStmt);
126898    rc = sqlite3_reset(pStmt);
126899  }
126900  return rc;
126901}
126902
126903/*
126904** Return the size of the common prefix (if any) shared by zPrev and
126905** zNext, in bytes. For example,
126906**
126907**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
126908**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
126909**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
126910*/
126911static int fts3PrefixCompress(
126912  const char *zPrev,              /* Buffer containing previous term */
126913  int nPrev,                      /* Size of buffer zPrev in bytes */
126914  const char *zNext,              /* Buffer containing next term */
126915  int nNext                       /* Size of buffer zNext in bytes */
126916){
126917  int n;
126918  UNUSED_PARAMETER(nNext);
126919  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
126920  return n;
126921}
126922
126923/*
126924** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
126925** (according to memcmp) than the previous term.
126926*/
126927static int fts3NodeAddTerm(
126928  Fts3Table *p,                   /* Virtual table handle */
126929  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
126930  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
126931  const char *zTerm,              /* Pointer to buffer containing term */
126932  int nTerm                       /* Size of term in bytes */
126933){
126934  SegmentNode *pTree = *ppTree;
126935  int rc;
126936  SegmentNode *pNew;
126937
126938  /* First try to append the term to the current node. Return early if
126939  ** this is possible.
126940  */
126941  if( pTree ){
126942    int nData = pTree->nData;     /* Current size of node in bytes */
126943    int nReq = nData;             /* Required space after adding zTerm */
126944    int nPrefix;                  /* Number of bytes of prefix compression */
126945    int nSuffix;                  /* Suffix length */
126946
126947    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
126948    nSuffix = nTerm-nPrefix;
126949
126950    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
126951    if( nReq<=p->nNodeSize || !pTree->zTerm ){
126952
126953      if( nReq>p->nNodeSize ){
126954        /* An unusual case: this is the first term to be added to the node
126955        ** and the static node buffer (p->nNodeSize bytes) is not large
126956        ** enough. Use a separately malloced buffer instead This wastes
126957        ** p->nNodeSize bytes, but since this scenario only comes about when
126958        ** the database contain two terms that share a prefix of almost 2KB,
126959        ** this is not expected to be a serious problem.
126960        */
126961        assert( pTree->aData==(char *)&pTree[1] );
126962        pTree->aData = (char *)sqlite3_malloc(nReq);
126963        if( !pTree->aData ){
126964          return SQLITE_NOMEM;
126965        }
126966      }
126967
126968      if( pTree->zTerm ){
126969        /* There is no prefix-length field for first term in a node */
126970        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
126971      }
126972
126973      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
126974      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
126975      pTree->nData = nData + nSuffix;
126976      pTree->nEntry++;
126977
126978      if( isCopyTerm ){
126979        if( pTree->nMalloc<nTerm ){
126980          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
126981          if( !zNew ){
126982            return SQLITE_NOMEM;
126983          }
126984          pTree->nMalloc = nTerm*2;
126985          pTree->zMalloc = zNew;
126986        }
126987        pTree->zTerm = pTree->zMalloc;
126988        memcpy(pTree->zTerm, zTerm, nTerm);
126989        pTree->nTerm = nTerm;
126990      }else{
126991        pTree->zTerm = (char *)zTerm;
126992        pTree->nTerm = nTerm;
126993      }
126994      return SQLITE_OK;
126995    }
126996  }
126997
126998  /* If control flows to here, it was not possible to append zTerm to the
126999  ** current node. Create a new node (a right-sibling of the current node).
127000  ** If this is the first node in the tree, the term is added to it.
127001  **
127002  ** Otherwise, the term is not added to the new node, it is left empty for
127003  ** now. Instead, the term is inserted into the parent of pTree. If pTree
127004  ** has no parent, one is created here.
127005  */
127006  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
127007  if( !pNew ){
127008    return SQLITE_NOMEM;
127009  }
127010  memset(pNew, 0, sizeof(SegmentNode));
127011  pNew->nData = 1 + FTS3_VARINT_MAX;
127012  pNew->aData = (char *)&pNew[1];
127013
127014  if( pTree ){
127015    SegmentNode *pParent = pTree->pParent;
127016    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
127017    if( pTree->pParent==0 ){
127018      pTree->pParent = pParent;
127019    }
127020    pTree->pRight = pNew;
127021    pNew->pLeftmost = pTree->pLeftmost;
127022    pNew->pParent = pParent;
127023    pNew->zMalloc = pTree->zMalloc;
127024    pNew->nMalloc = pTree->nMalloc;
127025    pTree->zMalloc = 0;
127026  }else{
127027    pNew->pLeftmost = pNew;
127028    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
127029  }
127030
127031  *ppTree = pNew;
127032  return rc;
127033}
127034
127035/*
127036** Helper function for fts3NodeWrite().
127037*/
127038static int fts3TreeFinishNode(
127039  SegmentNode *pTree,
127040  int iHeight,
127041  sqlite3_int64 iLeftChild
127042){
127043  int nStart;
127044  assert( iHeight>=1 && iHeight<128 );
127045  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
127046  pTree->aData[nStart] = (char)iHeight;
127047  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
127048  return nStart;
127049}
127050
127051/*
127052** Write the buffer for the segment node pTree and all of its peers to the
127053** database. Then call this function recursively to write the parent of
127054** pTree and its peers to the database.
127055**
127056** Except, if pTree is a root node, do not write it to the database. Instead,
127057** set output variables *paRoot and *pnRoot to contain the root node.
127058**
127059** If successful, SQLITE_OK is returned and output variable *piLast is
127060** set to the largest blockid written to the database (or zero if no
127061** blocks were written to the db). Otherwise, an SQLite error code is
127062** returned.
127063*/
127064static int fts3NodeWrite(
127065  Fts3Table *p,                   /* Virtual table handle */
127066  SegmentNode *pTree,             /* SegmentNode handle */
127067  int iHeight,                    /* Height of this node in tree */
127068  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
127069  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
127070  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
127071  char **paRoot,                  /* OUT: Data for root node */
127072  int *pnRoot                     /* OUT: Size of root node in bytes */
127073){
127074  int rc = SQLITE_OK;
127075
127076  if( !pTree->pParent ){
127077    /* Root node of the tree. */
127078    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
127079    *piLast = iFree-1;
127080    *pnRoot = pTree->nData - nStart;
127081    *paRoot = &pTree->aData[nStart];
127082  }else{
127083    SegmentNode *pIter;
127084    sqlite3_int64 iNextFree = iFree;
127085    sqlite3_int64 iNextLeaf = iLeaf;
127086    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
127087      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
127088      int nWrite = pIter->nData - nStart;
127089
127090      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
127091      iNextFree++;
127092      iNextLeaf += (pIter->nEntry+1);
127093    }
127094    if( rc==SQLITE_OK ){
127095      assert( iNextLeaf==iFree );
127096      rc = fts3NodeWrite(
127097          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
127098      );
127099    }
127100  }
127101
127102  return rc;
127103}
127104
127105/*
127106** Free all memory allocations associated with the tree pTree.
127107*/
127108static void fts3NodeFree(SegmentNode *pTree){
127109  if( pTree ){
127110    SegmentNode *p = pTree->pLeftmost;
127111    fts3NodeFree(p->pParent);
127112    while( p ){
127113      SegmentNode *pRight = p->pRight;
127114      if( p->aData!=(char *)&p[1] ){
127115        sqlite3_free(p->aData);
127116      }
127117      assert( pRight==0 || p->zMalloc==0 );
127118      sqlite3_free(p->zMalloc);
127119      sqlite3_free(p);
127120      p = pRight;
127121    }
127122  }
127123}
127124
127125/*
127126** Add a term to the segment being constructed by the SegmentWriter object
127127** *ppWriter. When adding the first term to a segment, *ppWriter should
127128** be passed NULL. This function will allocate a new SegmentWriter object
127129** and return it via the input/output variable *ppWriter in this case.
127130**
127131** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
127132*/
127133static int fts3SegWriterAdd(
127134  Fts3Table *p,                   /* Virtual table handle */
127135  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
127136  int isCopyTerm,                 /* True if buffer zTerm must be copied */
127137  const char *zTerm,              /* Pointer to buffer containing term */
127138  int nTerm,                      /* Size of term in bytes */
127139  const char *aDoclist,           /* Pointer to buffer containing doclist */
127140  int nDoclist                    /* Size of doclist in bytes */
127141){
127142  int nPrefix;                    /* Size of term prefix in bytes */
127143  int nSuffix;                    /* Size of term suffix in bytes */
127144  int nReq;                       /* Number of bytes required on leaf page */
127145  int nData;
127146  SegmentWriter *pWriter = *ppWriter;
127147
127148  if( !pWriter ){
127149    int rc;
127150    sqlite3_stmt *pStmt;
127151
127152    /* Allocate the SegmentWriter structure */
127153    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
127154    if( !pWriter ) return SQLITE_NOMEM;
127155    memset(pWriter, 0, sizeof(SegmentWriter));
127156    *ppWriter = pWriter;
127157
127158    /* Allocate a buffer in which to accumulate data */
127159    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
127160    if( !pWriter->aData ) return SQLITE_NOMEM;
127161    pWriter->nSize = p->nNodeSize;
127162
127163    /* Find the next free blockid in the %_segments table */
127164    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
127165    if( rc!=SQLITE_OK ) return rc;
127166    if( SQLITE_ROW==sqlite3_step(pStmt) ){
127167      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
127168      pWriter->iFirst = pWriter->iFree;
127169    }
127170    rc = sqlite3_reset(pStmt);
127171    if( rc!=SQLITE_OK ) return rc;
127172  }
127173  nData = pWriter->nData;
127174
127175  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
127176  nSuffix = nTerm-nPrefix;
127177
127178  /* Figure out how many bytes are required by this new entry */
127179  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
127180    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
127181    nSuffix +                               /* Term suffix */
127182    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
127183    nDoclist;                               /* Doclist data */
127184
127185  if( nData>0 && nData+nReq>p->nNodeSize ){
127186    int rc;
127187
127188    /* The current leaf node is full. Write it out to the database. */
127189    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
127190    if( rc!=SQLITE_OK ) return rc;
127191
127192    /* Add the current term to the interior node tree. The term added to
127193    ** the interior tree must:
127194    **
127195    **   a) be greater than the largest term on the leaf node just written
127196    **      to the database (still available in pWriter->zTerm), and
127197    **
127198    **   b) be less than or equal to the term about to be added to the new
127199    **      leaf node (zTerm/nTerm).
127200    **
127201    ** In other words, it must be the prefix of zTerm 1 byte longer than
127202    ** the common prefix (if any) of zTerm and pWriter->zTerm.
127203    */
127204    assert( nPrefix<nTerm );
127205    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
127206    if( rc!=SQLITE_OK ) return rc;
127207
127208    nData = 0;
127209    pWriter->nTerm = 0;
127210
127211    nPrefix = 0;
127212    nSuffix = nTerm;
127213    nReq = 1 +                              /* varint containing prefix size */
127214      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
127215      nTerm +                               /* Term suffix */
127216      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
127217      nDoclist;                             /* Doclist data */
127218  }
127219
127220  /* If the buffer currently allocated is too small for this entry, realloc
127221  ** the buffer to make it large enough.
127222  */
127223  if( nReq>pWriter->nSize ){
127224    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
127225    if( !aNew ) return SQLITE_NOMEM;
127226    pWriter->aData = aNew;
127227    pWriter->nSize = nReq;
127228  }
127229  assert( nData+nReq<=pWriter->nSize );
127230
127231  /* Append the prefix-compressed term and doclist to the buffer. */
127232  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
127233  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
127234  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
127235  nData += nSuffix;
127236  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
127237  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
127238  pWriter->nData = nData + nDoclist;
127239
127240  /* Save the current term so that it can be used to prefix-compress the next.
127241  ** If the isCopyTerm parameter is true, then the buffer pointed to by
127242  ** zTerm is transient, so take a copy of the term data. Otherwise, just
127243  ** store a copy of the pointer.
127244  */
127245  if( isCopyTerm ){
127246    if( nTerm>pWriter->nMalloc ){
127247      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
127248      if( !zNew ){
127249        return SQLITE_NOMEM;
127250      }
127251      pWriter->nMalloc = nTerm*2;
127252      pWriter->zMalloc = zNew;
127253      pWriter->zTerm = zNew;
127254    }
127255    assert( pWriter->zTerm==pWriter->zMalloc );
127256    memcpy(pWriter->zTerm, zTerm, nTerm);
127257  }else{
127258    pWriter->zTerm = (char *)zTerm;
127259  }
127260  pWriter->nTerm = nTerm;
127261
127262  return SQLITE_OK;
127263}
127264
127265/*
127266** Flush all data associated with the SegmentWriter object pWriter to the
127267** database. This function must be called after all terms have been added
127268** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
127269** returned. Otherwise, an SQLite error code.
127270*/
127271static int fts3SegWriterFlush(
127272  Fts3Table *p,                   /* Virtual table handle */
127273  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
127274  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
127275  int iIdx                        /* Value for 'idx' column of %_segdir */
127276){
127277  int rc;                         /* Return code */
127278  if( pWriter->pTree ){
127279    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
127280    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
127281    char *zRoot = NULL;           /* Pointer to buffer containing root node */
127282    int nRoot = 0;                /* Size of buffer zRoot */
127283
127284    iLastLeaf = pWriter->iFree;
127285    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
127286    if( rc==SQLITE_OK ){
127287      rc = fts3NodeWrite(p, pWriter->pTree, 1,
127288          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
127289    }
127290    if( rc==SQLITE_OK ){
127291      rc = fts3WriteSegdir(
127292          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
127293    }
127294  }else{
127295    /* The entire tree fits on the root node. Write it to the segdir table. */
127296    rc = fts3WriteSegdir(
127297        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
127298  }
127299  return rc;
127300}
127301
127302/*
127303** Release all memory held by the SegmentWriter object passed as the
127304** first argument.
127305*/
127306static void fts3SegWriterFree(SegmentWriter *pWriter){
127307  if( pWriter ){
127308    sqlite3_free(pWriter->aData);
127309    sqlite3_free(pWriter->zMalloc);
127310    fts3NodeFree(pWriter->pTree);
127311    sqlite3_free(pWriter);
127312  }
127313}
127314
127315/*
127316** The first value in the apVal[] array is assumed to contain an integer.
127317** This function tests if there exist any documents with docid values that
127318** are different from that integer. i.e. if deleting the document with docid
127319** pRowid would mean the FTS3 table were empty.
127320**
127321** If successful, *pisEmpty is set to true if the table is empty except for
127322** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
127323** error occurs, an SQLite error code is returned.
127324*/
127325static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
127326  sqlite3_stmt *pStmt;
127327  int rc;
127328  if( p->zContentTbl ){
127329    /* If using the content=xxx option, assume the table is never empty */
127330    *pisEmpty = 0;
127331    rc = SQLITE_OK;
127332  }else{
127333    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
127334    if( rc==SQLITE_OK ){
127335      if( SQLITE_ROW==sqlite3_step(pStmt) ){
127336        *pisEmpty = sqlite3_column_int(pStmt, 0);
127337      }
127338      rc = sqlite3_reset(pStmt);
127339    }
127340  }
127341  return rc;
127342}
127343
127344/*
127345** Set *pnMax to the largest segment level in the database for the index
127346** iIndex.
127347**
127348** Segment levels are stored in the 'level' column of the %_segdir table.
127349**
127350** Return SQLITE_OK if successful, or an SQLite error code if not.
127351*/
127352static int fts3SegmentMaxLevel(
127353  Fts3Table *p,
127354  int iLangid,
127355  int iIndex,
127356  sqlite3_int64 *pnMax
127357){
127358  sqlite3_stmt *pStmt;
127359  int rc;
127360  assert( iIndex>=0 && iIndex<p->nIndex );
127361
127362  /* Set pStmt to the compiled version of:
127363  **
127364  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
127365  **
127366  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
127367  */
127368  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
127369  if( rc!=SQLITE_OK ) return rc;
127370  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
127371  sqlite3_bind_int64(pStmt, 2,
127372      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
127373  );
127374  if( SQLITE_ROW==sqlite3_step(pStmt) ){
127375    *pnMax = sqlite3_column_int64(pStmt, 0);
127376  }
127377  return sqlite3_reset(pStmt);
127378}
127379
127380/*
127381** This function is used after merging multiple segments into a single large
127382** segment to delete the old, now redundant, segment b-trees. Specifically,
127383** it:
127384**
127385**   1) Deletes all %_segments entries for the segments associated with
127386**      each of the SegReader objects in the array passed as the third
127387**      argument, and
127388**
127389**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
127390**      entries regardless of level if (iLevel<0).
127391**
127392** SQLITE_OK is returned if successful, otherwise an SQLite error code.
127393*/
127394static int fts3DeleteSegdir(
127395  Fts3Table *p,                   /* Virtual table handle */
127396  int iLangid,                    /* Language id */
127397  int iIndex,                     /* Index for p->aIndex */
127398  int iLevel,                     /* Level of %_segdir entries to delete */
127399  Fts3SegReader **apSegment,      /* Array of SegReader objects */
127400  int nReader                     /* Size of array apSegment */
127401){
127402  int rc;                         /* Return Code */
127403  int i;                          /* Iterator variable */
127404  sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
127405
127406  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
127407  for(i=0; rc==SQLITE_OK && i<nReader; i++){
127408    Fts3SegReader *pSegment = apSegment[i];
127409    if( pSegment->iStartBlock ){
127410      sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
127411      sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
127412      sqlite3_step(pDelete);
127413      rc = sqlite3_reset(pDelete);
127414    }
127415  }
127416  if( rc!=SQLITE_OK ){
127417    return rc;
127418  }
127419
127420  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
127421  if( iLevel==FTS3_SEGCURSOR_ALL ){
127422    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
127423    if( rc==SQLITE_OK ){
127424      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
127425      sqlite3_bind_int64(pDelete, 2,
127426          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
127427      );
127428    }
127429  }else{
127430    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
127431    if( rc==SQLITE_OK ){
127432      sqlite3_bind_int64(
127433          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
127434      );
127435    }
127436  }
127437
127438  if( rc==SQLITE_OK ){
127439    sqlite3_step(pDelete);
127440    rc = sqlite3_reset(pDelete);
127441  }
127442
127443  return rc;
127444}
127445
127446/*
127447** When this function is called, buffer *ppList (size *pnList bytes) contains
127448** a position list that may (or may not) feature multiple columns. This
127449** function adjusts the pointer *ppList and the length *pnList so that they
127450** identify the subset of the position list that corresponds to column iCol.
127451**
127452** If there are no entries in the input position list for column iCol, then
127453** *pnList is set to zero before returning.
127454*/
127455static void fts3ColumnFilter(
127456  int iCol,                       /* Column to filter on */
127457  char **ppList,                  /* IN/OUT: Pointer to position list */
127458  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
127459){
127460  char *pList = *ppList;
127461  int nList = *pnList;
127462  char *pEnd = &pList[nList];
127463  int iCurrent = 0;
127464  char *p = pList;
127465
127466  assert( iCol>=0 );
127467  while( 1 ){
127468    char c = 0;
127469    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
127470
127471    if( iCol==iCurrent ){
127472      nList = (int)(p - pList);
127473      break;
127474    }
127475
127476    nList -= (int)(p - pList);
127477    pList = p;
127478    if( nList==0 ){
127479      break;
127480    }
127481    p = &pList[1];
127482    p += sqlite3Fts3GetVarint32(p, &iCurrent);
127483  }
127484
127485  *ppList = pList;
127486  *pnList = nList;
127487}
127488
127489/*
127490** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
127491** existing data). Grow the buffer if required.
127492**
127493** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
127494** trying to resize the buffer, return SQLITE_NOMEM.
127495*/
127496static int fts3MsrBufferData(
127497  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
127498  char *pList,
127499  int nList
127500){
127501  if( nList>pMsr->nBuffer ){
127502    char *pNew;
127503    pMsr->nBuffer = nList*2;
127504    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
127505    if( !pNew ) return SQLITE_NOMEM;
127506    pMsr->aBuffer = pNew;
127507  }
127508
127509  memcpy(pMsr->aBuffer, pList, nList);
127510  return SQLITE_OK;
127511}
127512
127513SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
127514  Fts3Table *p,                   /* Virtual table handle */
127515  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
127516  sqlite3_int64 *piDocid,         /* OUT: Docid value */
127517  char **paPoslist,               /* OUT: Pointer to position list */
127518  int *pnPoslist                  /* OUT: Size of position list in bytes */
127519){
127520  int nMerge = pMsr->nAdvance;
127521  Fts3SegReader **apSegment = pMsr->apSegment;
127522  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
127523    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
127524  );
127525
127526  if( nMerge==0 ){
127527    *paPoslist = 0;
127528    return SQLITE_OK;
127529  }
127530
127531  while( 1 ){
127532    Fts3SegReader *pSeg;
127533    pSeg = pMsr->apSegment[0];
127534
127535    if( pSeg->pOffsetList==0 ){
127536      *paPoslist = 0;
127537      break;
127538    }else{
127539      int rc;
127540      char *pList;
127541      int nList;
127542      int j;
127543      sqlite3_int64 iDocid = apSegment[0]->iDocid;
127544
127545      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
127546      j = 1;
127547      while( rc==SQLITE_OK
127548        && j<nMerge
127549        && apSegment[j]->pOffsetList
127550        && apSegment[j]->iDocid==iDocid
127551      ){
127552        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
127553        j++;
127554      }
127555      if( rc!=SQLITE_OK ) return rc;
127556      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
127557
127558      if( pMsr->iColFilter>=0 ){
127559        fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
127560      }
127561
127562      if( nList>0 ){
127563        if( fts3SegReaderIsPending(apSegment[0]) ){
127564          rc = fts3MsrBufferData(pMsr, pList, nList+1);
127565          if( rc!=SQLITE_OK ) return rc;
127566          *paPoslist = pMsr->aBuffer;
127567          assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
127568        }else{
127569          *paPoslist = pList;
127570        }
127571        *piDocid = iDocid;
127572        *pnPoslist = nList;
127573        break;
127574      }
127575    }
127576  }
127577
127578  return SQLITE_OK;
127579}
127580
127581static int fts3SegReaderStart(
127582  Fts3Table *p,                   /* Virtual table handle */
127583  Fts3MultiSegReader *pCsr,       /* Cursor object */
127584  const char *zTerm,              /* Term searched for (or NULL) */
127585  int nTerm                       /* Length of zTerm in bytes */
127586){
127587  int i;
127588  int nSeg = pCsr->nSegment;
127589
127590  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
127591  ** for, then advance each segment iterator until it points to a term of
127592  ** equal or greater value than the specified term. This prevents many
127593  ** unnecessary merge/sort operations for the case where single segment
127594  ** b-tree leaf nodes contain more than one term.
127595  */
127596  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
127597    int res = 0;
127598    Fts3SegReader *pSeg = pCsr->apSegment[i];
127599    do {
127600      int rc = fts3SegReaderNext(p, pSeg, 0);
127601      if( rc!=SQLITE_OK ) return rc;
127602    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
127603
127604    if( pSeg->bLookup && res!=0 ){
127605      fts3SegReaderSetEof(pSeg);
127606    }
127607  }
127608  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
127609
127610  return SQLITE_OK;
127611}
127612
127613SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
127614  Fts3Table *p,                   /* Virtual table handle */
127615  Fts3MultiSegReader *pCsr,       /* Cursor object */
127616  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
127617){
127618  pCsr->pFilter = pFilter;
127619  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
127620}
127621
127622SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
127623  Fts3Table *p,                   /* Virtual table handle */
127624  Fts3MultiSegReader *pCsr,       /* Cursor object */
127625  int iCol,                       /* Column to match on. */
127626  const char *zTerm,              /* Term to iterate through a doclist for */
127627  int nTerm                       /* Number of bytes in zTerm */
127628){
127629  int i;
127630  int rc;
127631  int nSegment = pCsr->nSegment;
127632  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
127633    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
127634  );
127635
127636  assert( pCsr->pFilter==0 );
127637  assert( zTerm && nTerm>0 );
127638
127639  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
127640  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
127641  if( rc!=SQLITE_OK ) return rc;
127642
127643  /* Determine how many of the segments actually point to zTerm/nTerm. */
127644  for(i=0; i<nSegment; i++){
127645    Fts3SegReader *pSeg = pCsr->apSegment[i];
127646    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
127647      break;
127648    }
127649  }
127650  pCsr->nAdvance = i;
127651
127652  /* Advance each of the segments to point to the first docid. */
127653  for(i=0; i<pCsr->nAdvance; i++){
127654    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
127655    if( rc!=SQLITE_OK ) return rc;
127656  }
127657  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
127658
127659  assert( iCol<0 || iCol<p->nColumn );
127660  pCsr->iColFilter = iCol;
127661
127662  return SQLITE_OK;
127663}
127664
127665/*
127666** This function is called on a MultiSegReader that has been started using
127667** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
127668** have been made. Calling this function puts the MultiSegReader in such
127669** a state that if the next two calls are:
127670**
127671**   sqlite3Fts3SegReaderStart()
127672**   sqlite3Fts3SegReaderStep()
127673**
127674** then the entire doclist for the term is available in
127675** MultiSegReader.aDoclist/nDoclist.
127676*/
127677SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
127678  int i;                          /* Used to iterate through segment-readers */
127679
127680  assert( pCsr->zTerm==0 );
127681  assert( pCsr->nTerm==0 );
127682  assert( pCsr->aDoclist==0 );
127683  assert( pCsr->nDoclist==0 );
127684
127685  pCsr->nAdvance = 0;
127686  pCsr->bRestart = 1;
127687  for(i=0; i<pCsr->nSegment; i++){
127688    pCsr->apSegment[i]->pOffsetList = 0;
127689    pCsr->apSegment[i]->nOffsetList = 0;
127690    pCsr->apSegment[i]->iDocid = 0;
127691  }
127692
127693  return SQLITE_OK;
127694}
127695
127696
127697SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
127698  Fts3Table *p,                   /* Virtual table handle */
127699  Fts3MultiSegReader *pCsr        /* Cursor object */
127700){
127701  int rc = SQLITE_OK;
127702
127703  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
127704  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
127705  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
127706  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
127707  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
127708  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
127709
127710  Fts3SegReader **apSegment = pCsr->apSegment;
127711  int nSegment = pCsr->nSegment;
127712  Fts3SegFilter *pFilter = pCsr->pFilter;
127713  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
127714    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
127715  );
127716
127717  if( pCsr->nSegment==0 ) return SQLITE_OK;
127718
127719  do {
127720    int nMerge;
127721    int i;
127722
127723    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
127724    ** forward. Then sort the list in order of current term again.
127725    */
127726    for(i=0; i<pCsr->nAdvance; i++){
127727      Fts3SegReader *pSeg = apSegment[i];
127728      if( pSeg->bLookup ){
127729        fts3SegReaderSetEof(pSeg);
127730      }else{
127731        rc = fts3SegReaderNext(p, pSeg, 0);
127732      }
127733      if( rc!=SQLITE_OK ) return rc;
127734    }
127735    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
127736    pCsr->nAdvance = 0;
127737
127738    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
127739    assert( rc==SQLITE_OK );
127740    if( apSegment[0]->aNode==0 ) break;
127741
127742    pCsr->nTerm = apSegment[0]->nTerm;
127743    pCsr->zTerm = apSegment[0]->zTerm;
127744
127745    /* If this is a prefix-search, and if the term that apSegment[0] points
127746    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
127747    ** required callbacks have been made. In this case exit early.
127748    **
127749    ** Similarly, if this is a search for an exact match, and the first term
127750    ** of segment apSegment[0] is not a match, exit early.
127751    */
127752    if( pFilter->zTerm && !isScan ){
127753      if( pCsr->nTerm<pFilter->nTerm
127754       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
127755       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
127756      ){
127757        break;
127758      }
127759    }
127760
127761    nMerge = 1;
127762    while( nMerge<nSegment
127763        && apSegment[nMerge]->aNode
127764        && apSegment[nMerge]->nTerm==pCsr->nTerm
127765        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
127766    ){
127767      nMerge++;
127768    }
127769
127770    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
127771    if( nMerge==1
127772     && !isIgnoreEmpty
127773     && !isFirst
127774     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
127775    ){
127776      pCsr->nDoclist = apSegment[0]->nDoclist;
127777      if( fts3SegReaderIsPending(apSegment[0]) ){
127778        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
127779        pCsr->aDoclist = pCsr->aBuffer;
127780      }else{
127781        pCsr->aDoclist = apSegment[0]->aDoclist;
127782      }
127783      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
127784    }else{
127785      int nDoclist = 0;           /* Size of doclist */
127786      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
127787
127788      /* The current term of the first nMerge entries in the array
127789      ** of Fts3SegReader objects is the same. The doclists must be merged
127790      ** and a single term returned with the merged doclist.
127791      */
127792      for(i=0; i<nMerge; i++){
127793        fts3SegReaderFirstDocid(p, apSegment[i]);
127794      }
127795      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
127796      while( apSegment[0]->pOffsetList ){
127797        int j;                    /* Number of segments that share a docid */
127798        char *pList;
127799        int nList;
127800        int nByte;
127801        sqlite3_int64 iDocid = apSegment[0]->iDocid;
127802        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
127803        j = 1;
127804        while( j<nMerge
127805            && apSegment[j]->pOffsetList
127806            && apSegment[j]->iDocid==iDocid
127807        ){
127808          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
127809          j++;
127810        }
127811
127812        if( isColFilter ){
127813          fts3ColumnFilter(pFilter->iCol, &pList, &nList);
127814        }
127815
127816        if( !isIgnoreEmpty || nList>0 ){
127817
127818          /* Calculate the 'docid' delta value to write into the merged
127819          ** doclist. */
127820          sqlite3_int64 iDelta;
127821          if( p->bDescIdx && nDoclist>0 ){
127822            iDelta = iPrev - iDocid;
127823          }else{
127824            iDelta = iDocid - iPrev;
127825          }
127826          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
127827          assert( nDoclist>0 || iDelta==iDocid );
127828
127829          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
127830          if( nDoclist+nByte>pCsr->nBuffer ){
127831            char *aNew;
127832            pCsr->nBuffer = (nDoclist+nByte)*2;
127833            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
127834            if( !aNew ){
127835              return SQLITE_NOMEM;
127836            }
127837            pCsr->aBuffer = aNew;
127838          }
127839
127840          if( isFirst ){
127841            char *a = &pCsr->aBuffer[nDoclist];
127842            int nWrite;
127843
127844            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
127845            if( nWrite ){
127846              iPrev = iDocid;
127847              nDoclist += nWrite;
127848            }
127849          }else{
127850            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
127851            iPrev = iDocid;
127852            if( isRequirePos ){
127853              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
127854              nDoclist += nList;
127855              pCsr->aBuffer[nDoclist++] = '\0';
127856            }
127857          }
127858        }
127859
127860        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
127861      }
127862      if( nDoclist>0 ){
127863        pCsr->aDoclist = pCsr->aBuffer;
127864        pCsr->nDoclist = nDoclist;
127865        rc = SQLITE_ROW;
127866      }
127867    }
127868    pCsr->nAdvance = nMerge;
127869  }while( rc==SQLITE_OK );
127870
127871  return rc;
127872}
127873
127874
127875SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
127876  Fts3MultiSegReader *pCsr       /* Cursor object */
127877){
127878  if( pCsr ){
127879    int i;
127880    for(i=0; i<pCsr->nSegment; i++){
127881      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
127882    }
127883    sqlite3_free(pCsr->apSegment);
127884    sqlite3_free(pCsr->aBuffer);
127885
127886    pCsr->nSegment = 0;
127887    pCsr->apSegment = 0;
127888    pCsr->aBuffer = 0;
127889  }
127890}
127891
127892/*
127893** Merge all level iLevel segments in the database into a single
127894** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
127895** single segment with a level equal to the numerically largest level
127896** currently present in the database.
127897**
127898** If this function is called with iLevel<0, but there is only one
127899** segment in the database, SQLITE_DONE is returned immediately.
127900** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
127901** an SQLite error code is returned.
127902*/
127903static int fts3SegmentMerge(
127904  Fts3Table *p,
127905  int iLangid,                    /* Language id to merge */
127906  int iIndex,                     /* Index in p->aIndex[] to merge */
127907  int iLevel                      /* Level to merge */
127908){
127909  int rc;                         /* Return code */
127910  int iIdx = 0;                   /* Index of new segment */
127911  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
127912  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
127913  Fts3SegFilter filter;           /* Segment term filter condition */
127914  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
127915  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
127916
127917  assert( iLevel==FTS3_SEGCURSOR_ALL
127918       || iLevel==FTS3_SEGCURSOR_PENDING
127919       || iLevel>=0
127920  );
127921  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
127922  assert( iIndex>=0 && iIndex<p->nIndex );
127923
127924  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
127925  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
127926
127927  if( iLevel==FTS3_SEGCURSOR_ALL ){
127928    /* This call is to merge all segments in the database to a single
127929    ** segment. The level of the new segment is equal to the the numerically
127930    ** greatest segment level currently present in the database for this
127931    ** index. The idx of the new segment is always 0.  */
127932    if( csr.nSegment==1 ){
127933      rc = SQLITE_DONE;
127934      goto finished;
127935    }
127936    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
127937    bIgnoreEmpty = 1;
127938
127939  }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
127940    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
127941    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
127942  }else{
127943    /* This call is to merge all segments at level iLevel. find the next
127944    ** available segment index at level iLevel+1. The call to
127945    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
127946    ** a single iLevel+2 segment if necessary.  */
127947    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
127948    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
127949  }
127950  if( rc!=SQLITE_OK ) goto finished;
127951  assert( csr.nSegment>0 );
127952  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
127953  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
127954
127955  memset(&filter, 0, sizeof(Fts3SegFilter));
127956  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
127957  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
127958
127959  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
127960  while( SQLITE_OK==rc ){
127961    rc = sqlite3Fts3SegReaderStep(p, &csr);
127962    if( rc!=SQLITE_ROW ) break;
127963    rc = fts3SegWriterAdd(p, &pWriter, 1,
127964        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
127965  }
127966  if( rc!=SQLITE_OK ) goto finished;
127967  assert( pWriter );
127968
127969  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
127970    rc = fts3DeleteSegdir(
127971        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
127972    );
127973    if( rc!=SQLITE_OK ) goto finished;
127974  }
127975  rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
127976
127977 finished:
127978  fts3SegWriterFree(pWriter);
127979  sqlite3Fts3SegReaderFinish(&csr);
127980  return rc;
127981}
127982
127983
127984/*
127985** Flush the contents of pendingTerms to level 0 segments.
127986*/
127987SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
127988  int rc = SQLITE_OK;
127989  int i;
127990  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
127991    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
127992    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
127993  }
127994  sqlite3Fts3PendingTermsClear(p);
127995  return rc;
127996}
127997
127998/*
127999** Encode N integers as varints into a blob.
128000*/
128001static void fts3EncodeIntArray(
128002  int N,             /* The number of integers to encode */
128003  u32 *a,            /* The integer values */
128004  char *zBuf,        /* Write the BLOB here */
128005  int *pNBuf         /* Write number of bytes if zBuf[] used here */
128006){
128007  int i, j;
128008  for(i=j=0; i<N; i++){
128009    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
128010  }
128011  *pNBuf = j;
128012}
128013
128014/*
128015** Decode a blob of varints into N integers
128016*/
128017static void fts3DecodeIntArray(
128018  int N,             /* The number of integers to decode */
128019  u32 *a,            /* Write the integer values */
128020  const char *zBuf,  /* The BLOB containing the varints */
128021  int nBuf           /* size of the BLOB */
128022){
128023  int i, j;
128024  UNUSED_PARAMETER(nBuf);
128025  for(i=j=0; i<N; i++){
128026    sqlite3_int64 x;
128027    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
128028    assert(j<=nBuf);
128029    a[i] = (u32)(x & 0xffffffff);
128030  }
128031}
128032
128033/*
128034** Insert the sizes (in tokens) for each column of the document
128035** with docid equal to p->iPrevDocid.  The sizes are encoded as
128036** a blob of varints.
128037*/
128038static void fts3InsertDocsize(
128039  int *pRC,                       /* Result code */
128040  Fts3Table *p,                   /* Table into which to insert */
128041  u32 *aSz                        /* Sizes of each column, in tokens */
128042){
128043  char *pBlob;             /* The BLOB encoding of the document size */
128044  int nBlob;               /* Number of bytes in the BLOB */
128045  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
128046  int rc;                  /* Result code from subfunctions */
128047
128048  if( *pRC ) return;
128049  pBlob = sqlite3_malloc( 10*p->nColumn );
128050  if( pBlob==0 ){
128051    *pRC = SQLITE_NOMEM;
128052    return;
128053  }
128054  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
128055  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
128056  if( rc ){
128057    sqlite3_free(pBlob);
128058    *pRC = rc;
128059    return;
128060  }
128061  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
128062  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
128063  sqlite3_step(pStmt);
128064  *pRC = sqlite3_reset(pStmt);
128065}
128066
128067/*
128068** Record 0 of the %_stat table contains a blob consisting of N varints,
128069** where N is the number of user defined columns in the fts3 table plus
128070** two. If nCol is the number of user defined columns, then values of the
128071** varints are set as follows:
128072**
128073**   Varint 0:       Total number of rows in the table.
128074**
128075**   Varint 1..nCol: For each column, the total number of tokens stored in
128076**                   the column for all rows of the table.
128077**
128078**   Varint 1+nCol:  The total size, in bytes, of all text values in all
128079**                   columns of all rows of the table.
128080**
128081*/
128082static void fts3UpdateDocTotals(
128083  int *pRC,                       /* The result code */
128084  Fts3Table *p,                   /* Table being updated */
128085  u32 *aSzIns,                    /* Size increases */
128086  u32 *aSzDel,                    /* Size decreases */
128087  int nChng                       /* Change in the number of documents */
128088){
128089  char *pBlob;             /* Storage for BLOB written into %_stat */
128090  int nBlob;               /* Size of BLOB written into %_stat */
128091  u32 *a;                  /* Array of integers that becomes the BLOB */
128092  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
128093  int i;                   /* Loop counter */
128094  int rc;                  /* Result code from subfunctions */
128095
128096  const int nStat = p->nColumn+2;
128097
128098  if( *pRC ) return;
128099  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
128100  if( a==0 ){
128101    *pRC = SQLITE_NOMEM;
128102    return;
128103  }
128104  pBlob = (char*)&a[nStat];
128105  rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
128106  if( rc ){
128107    sqlite3_free(a);
128108    *pRC = rc;
128109    return;
128110  }
128111  if( sqlite3_step(pStmt)==SQLITE_ROW ){
128112    fts3DecodeIntArray(nStat, a,
128113         sqlite3_column_blob(pStmt, 0),
128114         sqlite3_column_bytes(pStmt, 0));
128115  }else{
128116    memset(a, 0, sizeof(u32)*(nStat) );
128117  }
128118  sqlite3_reset(pStmt);
128119  if( nChng<0 && a[0]<(u32)(-nChng) ){
128120    a[0] = 0;
128121  }else{
128122    a[0] += nChng;
128123  }
128124  for(i=0; i<p->nColumn+1; i++){
128125    u32 x = a[i+1];
128126    if( x+aSzIns[i] < aSzDel[i] ){
128127      x = 0;
128128    }else{
128129      x = x + aSzIns[i] - aSzDel[i];
128130    }
128131    a[i+1] = x;
128132  }
128133  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
128134  rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
128135  if( rc ){
128136    sqlite3_free(a);
128137    *pRC = rc;
128138    return;
128139  }
128140  sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
128141  sqlite3_step(pStmt);
128142  *pRC = sqlite3_reset(pStmt);
128143  sqlite3_free(a);
128144}
128145
128146/*
128147** Merge the entire database so that there is one segment for each
128148** iIndex/iLangid combination.
128149*/
128150static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
128151  int bSeenDone = 0;
128152  int rc;
128153  sqlite3_stmt *pAllLangid = 0;
128154
128155  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
128156  if( rc==SQLITE_OK ){
128157    int rc2;
128158    sqlite3_bind_int(pAllLangid, 1, p->nIndex);
128159    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
128160      int i;
128161      int iLangid = sqlite3_column_int(pAllLangid, 0);
128162      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
128163        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
128164        if( rc==SQLITE_DONE ){
128165          bSeenDone = 1;
128166          rc = SQLITE_OK;
128167        }
128168      }
128169    }
128170    rc2 = sqlite3_reset(pAllLangid);
128171    if( rc==SQLITE_OK ) rc = rc2;
128172  }
128173
128174  sqlite3Fts3SegmentsClose(p);
128175  sqlite3Fts3PendingTermsClear(p);
128176
128177  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
128178}
128179
128180/*
128181** This function is called when the user executes the following statement:
128182**
128183**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
128184**
128185** The entire FTS index is discarded and rebuilt. If the table is one
128186** created using the content=xxx option, then the new index is based on
128187** the current contents of the xxx table. Otherwise, it is rebuilt based
128188** on the contents of the %_content table.
128189*/
128190static int fts3DoRebuild(Fts3Table *p){
128191  int rc;                         /* Return Code */
128192
128193  rc = fts3DeleteAll(p, 0);
128194  if( rc==SQLITE_OK ){
128195    u32 *aSz = 0;
128196    u32 *aSzIns = 0;
128197    u32 *aSzDel = 0;
128198    sqlite3_stmt *pStmt = 0;
128199    int nEntry = 0;
128200
128201    /* Compose and prepare an SQL statement to loop through the content table */
128202    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
128203    if( !zSql ){
128204      rc = SQLITE_NOMEM;
128205    }else{
128206      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
128207      sqlite3_free(zSql);
128208    }
128209
128210    if( rc==SQLITE_OK ){
128211      int nByte = sizeof(u32) * (p->nColumn+1)*3;
128212      aSz = (u32 *)sqlite3_malloc(nByte);
128213      if( aSz==0 ){
128214        rc = SQLITE_NOMEM;
128215      }else{
128216        memset(aSz, 0, nByte);
128217        aSzIns = &aSz[p->nColumn+1];
128218        aSzDel = &aSzIns[p->nColumn+1];
128219      }
128220    }
128221
128222    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
128223      int iCol;
128224      int iLangid = langidFromSelect(p, pStmt);
128225      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
128226      aSz[p->nColumn] = 0;
128227      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
128228        const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
128229        rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
128230        aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
128231      }
128232      if( p->bHasDocsize ){
128233        fts3InsertDocsize(&rc, p, aSz);
128234      }
128235      if( rc!=SQLITE_OK ){
128236        sqlite3_finalize(pStmt);
128237        pStmt = 0;
128238      }else{
128239        nEntry++;
128240        for(iCol=0; iCol<=p->nColumn; iCol++){
128241          aSzIns[iCol] += aSz[iCol];
128242        }
128243      }
128244    }
128245    if( p->bHasStat ){
128246      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
128247    }
128248    sqlite3_free(aSz);
128249
128250    if( pStmt ){
128251      int rc2 = sqlite3_finalize(pStmt);
128252      if( rc==SQLITE_OK ){
128253        rc = rc2;
128254      }
128255    }
128256  }
128257
128258  return rc;
128259}
128260
128261/*
128262** Handle a 'special' INSERT of the form:
128263**
128264**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
128265**
128266** Argument pVal contains the result of <expr>. Currently the only
128267** meaningful value to insert is the text 'optimize'.
128268*/
128269static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
128270  int rc;                         /* Return Code */
128271  const char *zVal = (const char *)sqlite3_value_text(pVal);
128272  int nVal = sqlite3_value_bytes(pVal);
128273
128274  if( !zVal ){
128275    return SQLITE_NOMEM;
128276  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
128277    rc = fts3DoOptimize(p, 0);
128278  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
128279    rc = fts3DoRebuild(p);
128280#ifdef SQLITE_TEST
128281  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
128282    p->nNodeSize = atoi(&zVal[9]);
128283    rc = SQLITE_OK;
128284  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
128285    p->nMaxPendingData = atoi(&zVal[11]);
128286    rc = SQLITE_OK;
128287#endif
128288  }else{
128289    rc = SQLITE_ERROR;
128290  }
128291
128292  return rc;
128293}
128294
128295/*
128296** Delete all cached deferred doclists. Deferred doclists are cached
128297** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
128298*/
128299SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
128300  Fts3DeferredToken *pDef;
128301  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
128302    fts3PendingListDelete(pDef->pList);
128303    pDef->pList = 0;
128304  }
128305}
128306
128307/*
128308** Free all entries in the pCsr->pDeffered list. Entries are added to
128309** this list using sqlite3Fts3DeferToken().
128310*/
128311SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
128312  Fts3DeferredToken *pDef;
128313  Fts3DeferredToken *pNext;
128314  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
128315    pNext = pDef->pNext;
128316    fts3PendingListDelete(pDef->pList);
128317    sqlite3_free(pDef);
128318  }
128319  pCsr->pDeferred = 0;
128320}
128321
128322/*
128323** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
128324** based on the row that pCsr currently points to.
128325**
128326** A deferred-doclist is like any other doclist with position information
128327** included, except that it only contains entries for a single row of the
128328** table, not for all rows.
128329*/
128330SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
128331  int rc = SQLITE_OK;             /* Return code */
128332  if( pCsr->pDeferred ){
128333    int i;                        /* Used to iterate through table columns */
128334    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
128335    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
128336
128337    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
128338    sqlite3_tokenizer *pT = p->pTokenizer;
128339    sqlite3_tokenizer_module const *pModule = pT->pModule;
128340
128341    assert( pCsr->isRequireSeek==0 );
128342    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
128343
128344    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
128345      const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
128346      sqlite3_tokenizer_cursor *pTC = 0;
128347
128348      rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
128349      while( rc==SQLITE_OK ){
128350        char const *zToken;       /* Buffer containing token */
128351        int nToken;               /* Number of bytes in token */
128352        int iDum1, iDum2;         /* Dummy variables */
128353        int iPos;                 /* Position of token in zText */
128354
128355        rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
128356        for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
128357          Fts3PhraseToken *pPT = pDef->pToken;
128358          if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
128359           && (pPT->bFirst==0 || iPos==0)
128360           && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
128361           && (0==memcmp(zToken, pPT->z, pPT->n))
128362          ){
128363            fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
128364          }
128365        }
128366      }
128367      if( pTC ) pModule->xClose(pTC);
128368      if( rc==SQLITE_DONE ) rc = SQLITE_OK;
128369    }
128370
128371    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
128372      if( pDef->pList ){
128373        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
128374      }
128375    }
128376  }
128377
128378  return rc;
128379}
128380
128381SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
128382  Fts3DeferredToken *p,
128383  char **ppData,
128384  int *pnData
128385){
128386  char *pRet;
128387  int nSkip;
128388  sqlite3_int64 dummy;
128389
128390  *ppData = 0;
128391  *pnData = 0;
128392
128393  if( p->pList==0 ){
128394    return SQLITE_OK;
128395  }
128396
128397  pRet = (char *)sqlite3_malloc(p->pList->nData);
128398  if( !pRet ) return SQLITE_NOMEM;
128399
128400  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
128401  *pnData = p->pList->nData - nSkip;
128402  *ppData = pRet;
128403
128404  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
128405  return SQLITE_OK;
128406}
128407
128408/*
128409** Add an entry for token pToken to the pCsr->pDeferred list.
128410*/
128411SQLITE_PRIVATE int sqlite3Fts3DeferToken(
128412  Fts3Cursor *pCsr,               /* Fts3 table cursor */
128413  Fts3PhraseToken *pToken,        /* Token to defer */
128414  int iCol                        /* Column that token must appear in (or -1) */
128415){
128416  Fts3DeferredToken *pDeferred;
128417  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
128418  if( !pDeferred ){
128419    return SQLITE_NOMEM;
128420  }
128421  memset(pDeferred, 0, sizeof(*pDeferred));
128422  pDeferred->pToken = pToken;
128423  pDeferred->pNext = pCsr->pDeferred;
128424  pDeferred->iCol = iCol;
128425  pCsr->pDeferred = pDeferred;
128426
128427  assert( pToken->pDeferred==0 );
128428  pToken->pDeferred = pDeferred;
128429
128430  return SQLITE_OK;
128431}
128432
128433/*
128434** SQLite value pRowid contains the rowid of a row that may or may not be
128435** present in the FTS3 table. If it is, delete it and adjust the contents
128436** of subsiduary data structures accordingly.
128437*/
128438static int fts3DeleteByRowid(
128439  Fts3Table *p,
128440  sqlite3_value *pRowid,
128441  int *pnDoc,
128442  u32 *aSzDel
128443){
128444  int isEmpty = 0;
128445  int rc = fts3IsEmpty(p, pRowid, &isEmpty);
128446  if( rc==SQLITE_OK ){
128447    if( isEmpty ){
128448      /* Deleting this row means the whole table is empty. In this case
128449      ** delete the contents of all three tables and throw away any
128450      ** data in the pendingTerms hash table.  */
128451      rc = fts3DeleteAll(p, 1);
128452      *pnDoc = *pnDoc - 1;
128453    }else{
128454      fts3DeleteTerms(&rc, p, pRowid, aSzDel);
128455      if( p->zContentTbl==0 ){
128456        fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
128457        if( sqlite3_changes(p->db) ) *pnDoc = *pnDoc - 1;
128458      }else{
128459        *pnDoc = *pnDoc - 1;
128460      }
128461      if( p->bHasDocsize ){
128462        fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
128463      }
128464    }
128465  }
128466
128467  return rc;
128468}
128469
128470/*
128471** This function does the work for the xUpdate method of FTS3 virtual
128472** tables. The schema of the virtual table being:
128473**
128474**     CREATE TABLE <table name>(
128475**       <user COLUMns>,
128476**       <table name> HIDDEN,
128477**       docid HIDDEN,
128478**       <langid> HIDDEN
128479**     );
128480**
128481**
128482*/
128483SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
128484  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
128485  int nArg,                       /* Size of argument array */
128486  sqlite3_value **apVal,          /* Array of arguments */
128487  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
128488){
128489  Fts3Table *p = (Fts3Table *)pVtab;
128490  int rc = SQLITE_OK;             /* Return Code */
128491  int isRemove = 0;               /* True for an UPDATE or DELETE */
128492  u32 *aSzIns = 0;                /* Sizes of inserted documents */
128493  u32 *aSzDel;                    /* Sizes of deleted documents */
128494  int nChng = 0;                  /* Net change in number of documents */
128495  int bInsertDone = 0;
128496
128497  assert( p->pSegments==0 );
128498  assert(
128499      nArg==1                     /* DELETE operations */
128500   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
128501  );
128502
128503  /* Check for a "special" INSERT operation. One of the form:
128504  **
128505  **   INSERT INTO xyz(xyz) VALUES('command');
128506  */
128507  if( nArg>1
128508   && sqlite3_value_type(apVal[0])==SQLITE_NULL
128509   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
128510  ){
128511    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
128512    goto update_out;
128513  }
128514
128515  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
128516    rc = SQLITE_CONSTRAINT;
128517    goto update_out;
128518  }
128519
128520  /* Allocate space to hold the change in document sizes */
128521  aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
128522  if( aSzIns==0 ){
128523    rc = SQLITE_NOMEM;
128524    goto update_out;
128525  }
128526  aSzDel = &aSzIns[p->nColumn+1];
128527  memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
128528
128529  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
128530  ** value, then this operation requires constraint handling.
128531  **
128532  ** If the on-conflict mode is REPLACE, this means that the existing row
128533  ** should be deleted from the database before inserting the new row. Or,
128534  ** if the on-conflict mode is other than REPLACE, then this method must
128535  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
128536  ** modify the database file.
128537  */
128538  if( nArg>1 && p->zContentTbl==0 ){
128539    /* Find the value object that holds the new rowid value. */
128540    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
128541    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
128542      pNewRowid = apVal[1];
128543    }
128544
128545    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
128546        sqlite3_value_type(apVal[0])==SQLITE_NULL
128547     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
128548    )){
128549      /* The new rowid is not NULL (in this case the rowid will be
128550      ** automatically assigned and there is no chance of a conflict), and
128551      ** the statement is either an INSERT or an UPDATE that modifies the
128552      ** rowid column. So if the conflict mode is REPLACE, then delete any
128553      ** existing row with rowid=pNewRowid.
128554      **
128555      ** Or, if the conflict mode is not REPLACE, insert the new record into
128556      ** the %_content table. If we hit the duplicate rowid constraint (or any
128557      ** other error) while doing so, return immediately.
128558      **
128559      ** This branch may also run if pNewRowid contains a value that cannot
128560      ** be losslessly converted to an integer. In this case, the eventual
128561      ** call to fts3InsertData() (either just below or further on in this
128562      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
128563      ** invoked, it will delete zero rows (since no row will have
128564      ** docid=$pNewRowid if $pNewRowid is not an integer value).
128565      */
128566      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
128567        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
128568      }else{
128569        rc = fts3InsertData(p, apVal, pRowid);
128570        bInsertDone = 1;
128571      }
128572    }
128573  }
128574  if( rc!=SQLITE_OK ){
128575    goto update_out;
128576  }
128577
128578  /* If this is a DELETE or UPDATE operation, remove the old record. */
128579  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
128580    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
128581    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
128582    isRemove = 1;
128583  }
128584
128585  /* If this is an INSERT or UPDATE operation, insert the new record. */
128586  if( nArg>1 && rc==SQLITE_OK ){
128587    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
128588    if( bInsertDone==0 ){
128589      rc = fts3InsertData(p, apVal, pRowid);
128590      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
128591        rc = FTS_CORRUPT_VTAB;
128592      }
128593    }
128594    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
128595      rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
128596    }
128597    if( rc==SQLITE_OK ){
128598      assert( p->iPrevDocid==*pRowid );
128599      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
128600    }
128601    if( p->bHasDocsize ){
128602      fts3InsertDocsize(&rc, p, aSzIns);
128603    }
128604    nChng++;
128605  }
128606
128607  if( p->bHasStat ){
128608    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
128609  }
128610
128611 update_out:
128612  sqlite3_free(aSzIns);
128613  sqlite3Fts3SegmentsClose(p);
128614  return rc;
128615}
128616
128617/*
128618** Flush any data in the pending-terms hash table to disk. If successful,
128619** merge all segments in the database (including the new segment, if
128620** there was any data to flush) into a single segment.
128621*/
128622SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
128623  int rc;
128624  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
128625  if( rc==SQLITE_OK ){
128626    rc = fts3DoOptimize(p, 1);
128627    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
128628      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
128629      if( rc2!=SQLITE_OK ) rc = rc2;
128630    }else{
128631      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
128632      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
128633    }
128634  }
128635  sqlite3Fts3SegmentsClose(p);
128636  return rc;
128637}
128638
128639#endif
128640
128641/************** End of fts3_write.c ******************************************/
128642/************** Begin file fts3_snippet.c ************************************/
128643/*
128644** 2009 Oct 23
128645**
128646** The author disclaims copyright to this source code.  In place of
128647** a legal notice, here is a blessing:
128648**
128649**    May you do good and not evil.
128650**    May you find forgiveness for yourself and forgive others.
128651**    May you share freely, never taking more than you give.
128652**
128653******************************************************************************
128654*/
128655
128656#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
128657
128658/* #include <string.h> */
128659/* #include <assert.h> */
128660
128661/*
128662** Characters that may appear in the second argument to matchinfo().
128663*/
128664#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
128665#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
128666#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
128667#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
128668#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
128669#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
128670#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
128671
128672/*
128673** The default value for the second argument to matchinfo().
128674*/
128675#define FTS3_MATCHINFO_DEFAULT   "pcx"
128676
128677
128678/*
128679** Used as an fts3ExprIterate() context when loading phrase doclists to
128680** Fts3Expr.aDoclist[]/nDoclist.
128681*/
128682typedef struct LoadDoclistCtx LoadDoclistCtx;
128683struct LoadDoclistCtx {
128684  Fts3Cursor *pCsr;               /* FTS3 Cursor */
128685  int nPhrase;                    /* Number of phrases seen so far */
128686  int nToken;                     /* Number of tokens seen so far */
128687};
128688
128689/*
128690** The following types are used as part of the implementation of the
128691** fts3BestSnippet() routine.
128692*/
128693typedef struct SnippetIter SnippetIter;
128694typedef struct SnippetPhrase SnippetPhrase;
128695typedef struct SnippetFragment SnippetFragment;
128696
128697struct SnippetIter {
128698  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
128699  int iCol;                       /* Extract snippet from this column */
128700  int nSnippet;                   /* Requested snippet length (in tokens) */
128701  int nPhrase;                    /* Number of phrases in query */
128702  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
128703  int iCurrent;                   /* First token of current snippet */
128704};
128705
128706struct SnippetPhrase {
128707  int nToken;                     /* Number of tokens in phrase */
128708  char *pList;                    /* Pointer to start of phrase position list */
128709  int iHead;                      /* Next value in position list */
128710  char *pHead;                    /* Position list data following iHead */
128711  int iTail;                      /* Next value in trailing position list */
128712  char *pTail;                    /* Position list data following iTail */
128713};
128714
128715struct SnippetFragment {
128716  int iCol;                       /* Column snippet is extracted from */
128717  int iPos;                       /* Index of first token in snippet */
128718  u64 covered;                    /* Mask of query phrases covered */
128719  u64 hlmask;                     /* Mask of snippet terms to highlight */
128720};
128721
128722/*
128723** This type is used as an fts3ExprIterate() context object while
128724** accumulating the data returned by the matchinfo() function.
128725*/
128726typedef struct MatchInfo MatchInfo;
128727struct MatchInfo {
128728  Fts3Cursor *pCursor;            /* FTS3 Cursor */
128729  int nCol;                       /* Number of columns in table */
128730  int nPhrase;                    /* Number of matchable phrases in query */
128731  sqlite3_int64 nDoc;             /* Number of docs in database */
128732  u32 *aMatchinfo;                /* Pre-allocated buffer */
128733};
128734
128735
128736
128737/*
128738** The snippet() and offsets() functions both return text values. An instance
128739** of the following structure is used to accumulate those values while the
128740** functions are running. See fts3StringAppend() for details.
128741*/
128742typedef struct StrBuffer StrBuffer;
128743struct StrBuffer {
128744  char *z;                        /* Pointer to buffer containing string */
128745  int n;                          /* Length of z in bytes (excl. nul-term) */
128746  int nAlloc;                     /* Allocated size of buffer z in bytes */
128747};
128748
128749
128750/*
128751** This function is used to help iterate through a position-list. A position
128752** list is a list of unique integers, sorted from smallest to largest. Each
128753** element of the list is represented by an FTS3 varint that takes the value
128754** of the difference between the current element and the previous one plus
128755** two. For example, to store the position-list:
128756**
128757**     4 9 113
128758**
128759** the three varints:
128760**
128761**     6 7 106
128762**
128763** are encoded.
128764**
128765** When this function is called, *pp points to the start of an element of
128766** the list. *piPos contains the value of the previous entry in the list.
128767** After it returns, *piPos contains the value of the next element of the
128768** list and *pp is advanced to the following varint.
128769*/
128770static void fts3GetDeltaPosition(char **pp, int *piPos){
128771  int iVal;
128772  *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
128773  *piPos += (iVal-2);
128774}
128775
128776/*
128777** Helper function for fts3ExprIterate() (see below).
128778*/
128779static int fts3ExprIterate2(
128780  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
128781  int *piPhrase,                  /* Pointer to phrase counter */
128782  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
128783  void *pCtx                      /* Second argument to pass to callback */
128784){
128785  int rc;                         /* Return code */
128786  int eType = pExpr->eType;       /* Type of expression node pExpr */
128787
128788  if( eType!=FTSQUERY_PHRASE ){
128789    assert( pExpr->pLeft && pExpr->pRight );
128790    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
128791    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
128792      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
128793    }
128794  }else{
128795    rc = x(pExpr, *piPhrase, pCtx);
128796    (*piPhrase)++;
128797  }
128798  return rc;
128799}
128800
128801/*
128802** Iterate through all phrase nodes in an FTS3 query, except those that
128803** are part of a sub-tree that is the right-hand-side of a NOT operator.
128804** For each phrase node found, the supplied callback function is invoked.
128805**
128806** If the callback function returns anything other than SQLITE_OK,
128807** the iteration is abandoned and the error code returned immediately.
128808** Otherwise, SQLITE_OK is returned after a callback has been made for
128809** all eligible phrase nodes.
128810*/
128811static int fts3ExprIterate(
128812  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
128813  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
128814  void *pCtx                      /* Second argument to pass to callback */
128815){
128816  int iPhrase = 0;                /* Variable used as the phrase counter */
128817  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
128818}
128819
128820/*
128821** This is an fts3ExprIterate() callback used while loading the doclists
128822** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
128823** fts3ExprLoadDoclists().
128824*/
128825static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
128826  int rc = SQLITE_OK;
128827  Fts3Phrase *pPhrase = pExpr->pPhrase;
128828  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
128829
128830  UNUSED_PARAMETER(iPhrase);
128831
128832  p->nPhrase++;
128833  p->nToken += pPhrase->nToken;
128834
128835  return rc;
128836}
128837
128838/*
128839** Load the doclists for each phrase in the query associated with FTS3 cursor
128840** pCsr.
128841**
128842** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
128843** phrases in the expression (all phrases except those directly or
128844** indirectly descended from the right-hand-side of a NOT operator). If
128845** pnToken is not NULL, then it is set to the number of tokens in all
128846** matchable phrases of the expression.
128847*/
128848static int fts3ExprLoadDoclists(
128849  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
128850  int *pnPhrase,                  /* OUT: Number of phrases in query */
128851  int *pnToken                    /* OUT: Number of tokens in query */
128852){
128853  int rc;                         /* Return Code */
128854  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
128855  sCtx.pCsr = pCsr;
128856  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
128857  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
128858  if( pnToken ) *pnToken = sCtx.nToken;
128859  return rc;
128860}
128861
128862static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
128863  (*(int *)ctx)++;
128864  UNUSED_PARAMETER(pExpr);
128865  UNUSED_PARAMETER(iPhrase);
128866  return SQLITE_OK;
128867}
128868static int fts3ExprPhraseCount(Fts3Expr *pExpr){
128869  int nPhrase = 0;
128870  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
128871  return nPhrase;
128872}
128873
128874/*
128875** Advance the position list iterator specified by the first two
128876** arguments so that it points to the first element with a value greater
128877** than or equal to parameter iNext.
128878*/
128879static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
128880  char *pIter = *ppIter;
128881  if( pIter ){
128882    int iIter = *piIter;
128883
128884    while( iIter<iNext ){
128885      if( 0==(*pIter & 0xFE) ){
128886        iIter = -1;
128887        pIter = 0;
128888        break;
128889      }
128890      fts3GetDeltaPosition(&pIter, &iIter);
128891    }
128892
128893    *piIter = iIter;
128894    *ppIter = pIter;
128895  }
128896}
128897
128898/*
128899** Advance the snippet iterator to the next candidate snippet.
128900*/
128901static int fts3SnippetNextCandidate(SnippetIter *pIter){
128902  int i;                          /* Loop counter */
128903
128904  if( pIter->iCurrent<0 ){
128905    /* The SnippetIter object has just been initialized. The first snippet
128906    ** candidate always starts at offset 0 (even if this candidate has a
128907    ** score of 0.0).
128908    */
128909    pIter->iCurrent = 0;
128910
128911    /* Advance the 'head' iterator of each phrase to the first offset that
128912    ** is greater than or equal to (iNext+nSnippet).
128913    */
128914    for(i=0; i<pIter->nPhrase; i++){
128915      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128916      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
128917    }
128918  }else{
128919    int iStart;
128920    int iEnd = 0x7FFFFFFF;
128921
128922    for(i=0; i<pIter->nPhrase; i++){
128923      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128924      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
128925        iEnd = pPhrase->iHead;
128926      }
128927    }
128928    if( iEnd==0x7FFFFFFF ){
128929      return 1;
128930    }
128931
128932    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
128933    for(i=0; i<pIter->nPhrase; i++){
128934      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128935      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
128936      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
128937    }
128938  }
128939
128940  return 0;
128941}
128942
128943/*
128944** Retrieve information about the current candidate snippet of snippet
128945** iterator pIter.
128946*/
128947static void fts3SnippetDetails(
128948  SnippetIter *pIter,             /* Snippet iterator */
128949  u64 mCovered,                   /* Bitmask of phrases already covered */
128950  int *piToken,                   /* OUT: First token of proposed snippet */
128951  int *piScore,                   /* OUT: "Score" for this snippet */
128952  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
128953  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
128954){
128955  int iStart = pIter->iCurrent;   /* First token of snippet */
128956  int iScore = 0;                 /* Score of this snippet */
128957  int i;                          /* Loop counter */
128958  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
128959  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
128960
128961  for(i=0; i<pIter->nPhrase; i++){
128962    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128963    if( pPhrase->pTail ){
128964      char *pCsr = pPhrase->pTail;
128965      int iCsr = pPhrase->iTail;
128966
128967      while( iCsr<(iStart+pIter->nSnippet) ){
128968        int j;
128969        u64 mPhrase = (u64)1 << i;
128970        u64 mPos = (u64)1 << (iCsr - iStart);
128971        assert( iCsr>=iStart );
128972        if( (mCover|mCovered)&mPhrase ){
128973          iScore++;
128974        }else{
128975          iScore += 1000;
128976        }
128977        mCover |= mPhrase;
128978
128979        for(j=0; j<pPhrase->nToken; j++){
128980          mHighlight |= (mPos>>j);
128981        }
128982
128983        if( 0==(*pCsr & 0x0FE) ) break;
128984        fts3GetDeltaPosition(&pCsr, &iCsr);
128985      }
128986    }
128987  }
128988
128989  /* Set the output variables before returning. */
128990  *piToken = iStart;
128991  *piScore = iScore;
128992  *pmCover = mCover;
128993  *pmHighlight = mHighlight;
128994}
128995
128996/*
128997** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
128998** Each invocation populates an element of the SnippetIter.aPhrase[] array.
128999*/
129000static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
129001  SnippetIter *p = (SnippetIter *)ctx;
129002  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
129003  char *pCsr;
129004
129005  pPhrase->nToken = pExpr->pPhrase->nToken;
129006
129007  pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
129008  if( pCsr ){
129009    int iFirst = 0;
129010    pPhrase->pList = pCsr;
129011    fts3GetDeltaPosition(&pCsr, &iFirst);
129012    assert( iFirst>=0 );
129013    pPhrase->pHead = pCsr;
129014    pPhrase->pTail = pCsr;
129015    pPhrase->iHead = iFirst;
129016    pPhrase->iTail = iFirst;
129017  }else{
129018    assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
129019  }
129020
129021  return SQLITE_OK;
129022}
129023
129024/*
129025** Select the fragment of text consisting of nFragment contiguous tokens
129026** from column iCol that represent the "best" snippet. The best snippet
129027** is the snippet with the highest score, where scores are calculated
129028** by adding:
129029**
129030**   (a) +1 point for each occurence of a matchable phrase in the snippet.
129031**
129032**   (b) +1000 points for the first occurence of each matchable phrase in
129033**       the snippet for which the corresponding mCovered bit is not set.
129034**
129035** The selected snippet parameters are stored in structure *pFragment before
129036** returning. The score of the selected snippet is stored in *piScore
129037** before returning.
129038*/
129039static int fts3BestSnippet(
129040  int nSnippet,                   /* Desired snippet length */
129041  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
129042  int iCol,                       /* Index of column to create snippet from */
129043  u64 mCovered,                   /* Mask of phrases already covered */
129044  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
129045  SnippetFragment *pFragment,     /* OUT: Best snippet found */
129046  int *piScore                    /* OUT: Score of snippet pFragment */
129047){
129048  int rc;                         /* Return Code */
129049  int nList;                      /* Number of phrases in expression */
129050  SnippetIter sIter;              /* Iterates through snippet candidates */
129051  int nByte;                      /* Number of bytes of space to allocate */
129052  int iBestScore = -1;            /* Best snippet score found so far */
129053  int i;                          /* Loop counter */
129054
129055  memset(&sIter, 0, sizeof(sIter));
129056
129057  /* Iterate through the phrases in the expression to count them. The same
129058  ** callback makes sure the doclists are loaded for each phrase.
129059  */
129060  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
129061  if( rc!=SQLITE_OK ){
129062    return rc;
129063  }
129064
129065  /* Now that it is known how many phrases there are, allocate and zero
129066  ** the required space using malloc().
129067  */
129068  nByte = sizeof(SnippetPhrase) * nList;
129069  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
129070  if( !sIter.aPhrase ){
129071    return SQLITE_NOMEM;
129072  }
129073  memset(sIter.aPhrase, 0, nByte);
129074
129075  /* Initialize the contents of the SnippetIter object. Then iterate through
129076  ** the set of phrases in the expression to populate the aPhrase[] array.
129077  */
129078  sIter.pCsr = pCsr;
129079  sIter.iCol = iCol;
129080  sIter.nSnippet = nSnippet;
129081  sIter.nPhrase = nList;
129082  sIter.iCurrent = -1;
129083  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
129084
129085  /* Set the *pmSeen output variable. */
129086  for(i=0; i<nList; i++){
129087    if( sIter.aPhrase[i].pHead ){
129088      *pmSeen |= (u64)1 << i;
129089    }
129090  }
129091
129092  /* Loop through all candidate snippets. Store the best snippet in
129093  ** *pFragment. Store its associated 'score' in iBestScore.
129094  */
129095  pFragment->iCol = iCol;
129096  while( !fts3SnippetNextCandidate(&sIter) ){
129097    int iPos;
129098    int iScore;
129099    u64 mCover;
129100    u64 mHighlight;
129101    fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
129102    assert( iScore>=0 );
129103    if( iScore>iBestScore ){
129104      pFragment->iPos = iPos;
129105      pFragment->hlmask = mHighlight;
129106      pFragment->covered = mCover;
129107      iBestScore = iScore;
129108    }
129109  }
129110
129111  sqlite3_free(sIter.aPhrase);
129112  *piScore = iBestScore;
129113  return SQLITE_OK;
129114}
129115
129116
129117/*
129118** Append a string to the string-buffer passed as the first argument.
129119**
129120** If nAppend is negative, then the length of the string zAppend is
129121** determined using strlen().
129122*/
129123static int fts3StringAppend(
129124  StrBuffer *pStr,                /* Buffer to append to */
129125  const char *zAppend,            /* Pointer to data to append to buffer */
129126  int nAppend                     /* Size of zAppend in bytes (or -1) */
129127){
129128  if( nAppend<0 ){
129129    nAppend = (int)strlen(zAppend);
129130  }
129131
129132  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
129133  ** to grow the buffer until so that it is big enough to accomadate the
129134  ** appended data.
129135  */
129136  if( pStr->n+nAppend+1>=pStr->nAlloc ){
129137    int nAlloc = pStr->nAlloc+nAppend+100;
129138    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
129139    if( !zNew ){
129140      return SQLITE_NOMEM;
129141    }
129142    pStr->z = zNew;
129143    pStr->nAlloc = nAlloc;
129144  }
129145
129146  /* Append the data to the string buffer. */
129147  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
129148  pStr->n += nAppend;
129149  pStr->z[pStr->n] = '\0';
129150
129151  return SQLITE_OK;
129152}
129153
129154/*
129155** The fts3BestSnippet() function often selects snippets that end with a
129156** query term. That is, the final term of the snippet is always a term
129157** that requires highlighting. For example, if 'X' is a highlighted term
129158** and '.' is a non-highlighted term, BestSnippet() may select:
129159**
129160**     ........X.....X
129161**
129162** This function "shifts" the beginning of the snippet forward in the
129163** document so that there are approximately the same number of
129164** non-highlighted terms to the right of the final highlighted term as there
129165** are to the left of the first highlighted term. For example, to this:
129166**
129167**     ....X.....X....
129168**
129169** This is done as part of extracting the snippet text, not when selecting
129170** the snippet. Snippet selection is done based on doclists only, so there
129171** is no way for fts3BestSnippet() to know whether or not the document
129172** actually contains terms that follow the final highlighted term.
129173*/
129174static int fts3SnippetShift(
129175  Fts3Table *pTab,                /* FTS3 table snippet comes from */
129176  int iLangid,                    /* Language id to use in tokenizing */
129177  int nSnippet,                   /* Number of tokens desired for snippet */
129178  const char *zDoc,               /* Document text to extract snippet from */
129179  int nDoc,                       /* Size of buffer zDoc in bytes */
129180  int *piPos,                     /* IN/OUT: First token of snippet */
129181  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
129182){
129183  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
129184
129185  if( hlmask ){
129186    int nLeft;                    /* Tokens to the left of first highlight */
129187    int nRight;                   /* Tokens to the right of last highlight */
129188    int nDesired;                 /* Ideal number of tokens to shift forward */
129189
129190    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
129191    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
129192    nDesired = (nLeft-nRight)/2;
129193
129194    /* Ideally, the start of the snippet should be pushed forward in the
129195    ** document nDesired tokens. This block checks if there are actually
129196    ** nDesired tokens to the right of the snippet. If so, *piPos and
129197    ** *pHlMask are updated to shift the snippet nDesired tokens to the
129198    ** right. Otherwise, the snippet is shifted by the number of tokens
129199    ** available.
129200    */
129201    if( nDesired>0 ){
129202      int nShift;                 /* Number of tokens to shift snippet by */
129203      int iCurrent = 0;           /* Token counter */
129204      int rc;                     /* Return Code */
129205      sqlite3_tokenizer_module *pMod;
129206      sqlite3_tokenizer_cursor *pC;
129207      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
129208
129209      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
129210      ** or more tokens in zDoc/nDoc.
129211      */
129212      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
129213      if( rc!=SQLITE_OK ){
129214        return rc;
129215      }
129216      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
129217        const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
129218        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
129219      }
129220      pMod->xClose(pC);
129221      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
129222
129223      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
129224      assert( nShift<=nDesired );
129225      if( nShift>0 ){
129226        *piPos += nShift;
129227        *pHlmask = hlmask >> nShift;
129228      }
129229    }
129230  }
129231  return SQLITE_OK;
129232}
129233
129234/*
129235** Extract the snippet text for fragment pFragment from cursor pCsr and
129236** append it to string buffer pOut.
129237*/
129238static int fts3SnippetText(
129239  Fts3Cursor *pCsr,               /* FTS3 Cursor */
129240  SnippetFragment *pFragment,     /* Snippet to extract */
129241  int iFragment,                  /* Fragment number */
129242  int isLast,                     /* True for final fragment in snippet */
129243  int nSnippet,                   /* Number of tokens in extracted snippet */
129244  const char *zOpen,              /* String inserted before highlighted term */
129245  const char *zClose,             /* String inserted after highlighted term */
129246  const char *zEllipsis,          /* String inserted between snippets */
129247  StrBuffer *pOut                 /* Write output here */
129248){
129249  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129250  int rc;                         /* Return code */
129251  const char *zDoc;               /* Document text to extract snippet from */
129252  int nDoc;                       /* Size of zDoc in bytes */
129253  int iCurrent = 0;               /* Current token number of document */
129254  int iEnd = 0;                   /* Byte offset of end of current token */
129255  int isShiftDone = 0;            /* True after snippet is shifted */
129256  int iPos = pFragment->iPos;     /* First token of snippet */
129257  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
129258  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
129259  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
129260  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
129261  const char *ZDUMMY;             /* Dummy argument used with tokenizer */
129262  int DUMMY1;                     /* Dummy argument used with tokenizer */
129263
129264  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
129265  if( zDoc==0 ){
129266    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
129267      return SQLITE_NOMEM;
129268    }
129269    return SQLITE_OK;
129270  }
129271  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
129272
129273  /* Open a token cursor on the document. */
129274  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
129275  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
129276  if( rc!=SQLITE_OK ){
129277    return rc;
129278  }
129279
129280  while( rc==SQLITE_OK ){
129281    int iBegin;                   /* Offset in zDoc of start of token */
129282    int iFin;                     /* Offset in zDoc of end of token */
129283    int isHighlight;              /* True for highlighted terms */
129284
129285    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
129286    if( rc!=SQLITE_OK ){
129287      if( rc==SQLITE_DONE ){
129288        /* Special case - the last token of the snippet is also the last token
129289        ** of the column. Append any punctuation that occurred between the end
129290        ** of the previous token and the end of the document to the output.
129291        ** Then break out of the loop. */
129292        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
129293      }
129294      break;
129295    }
129296    if( iCurrent<iPos ){ continue; }
129297
129298    if( !isShiftDone ){
129299      int n = nDoc - iBegin;
129300      rc = fts3SnippetShift(
129301          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
129302      );
129303      isShiftDone = 1;
129304
129305      /* Now that the shift has been done, check if the initial "..." are
129306      ** required. They are required if (a) this is not the first fragment,
129307      ** or (b) this fragment does not begin at position 0 of its column.
129308      */
129309      if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
129310        rc = fts3StringAppend(pOut, zEllipsis, -1);
129311      }
129312      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
129313    }
129314
129315    if( iCurrent>=(iPos+nSnippet) ){
129316      if( isLast ){
129317        rc = fts3StringAppend(pOut, zEllipsis, -1);
129318      }
129319      break;
129320    }
129321
129322    /* Set isHighlight to true if this term should be highlighted. */
129323    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
129324
129325    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
129326    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
129327    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
129328    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
129329
129330    iEnd = iFin;
129331  }
129332
129333  pMod->xClose(pC);
129334  return rc;
129335}
129336
129337
129338/*
129339** This function is used to count the entries in a column-list (a
129340** delta-encoded list of term offsets within a single column of a single
129341** row). When this function is called, *ppCollist should point to the
129342** beginning of the first varint in the column-list (the varint that
129343** contains the position of the first matching term in the column data).
129344** Before returning, *ppCollist is set to point to the first byte after
129345** the last varint in the column-list (either the 0x00 signifying the end
129346** of the position-list, or the 0x01 that precedes the column number of
129347** the next column in the position-list).
129348**
129349** The number of elements in the column-list is returned.
129350*/
129351static int fts3ColumnlistCount(char **ppCollist){
129352  char *pEnd = *ppCollist;
129353  char c = 0;
129354  int nEntry = 0;
129355
129356  /* A column-list is terminated by either a 0x01 or 0x00. */
129357  while( 0xFE & (*pEnd | c) ){
129358    c = *pEnd++ & 0x80;
129359    if( !c ) nEntry++;
129360  }
129361
129362  *ppCollist = pEnd;
129363  return nEntry;
129364}
129365
129366/*
129367** fts3ExprIterate() callback used to collect the "global" matchinfo stats
129368** for a single query.
129369**
129370** fts3ExprIterate() callback to load the 'global' elements of a
129371** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
129372** of the matchinfo array that are constant for all rows returned by the
129373** current query.
129374**
129375** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
129376** function populates Matchinfo.aMatchinfo[] as follows:
129377**
129378**   for(iCol=0; iCol<nCol; iCol++){
129379**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
129380**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
129381**   }
129382**
129383** where X is the number of matches for phrase iPhrase is column iCol of all
129384** rows of the table. Y is the number of rows for which column iCol contains
129385** at least one instance of phrase iPhrase.
129386**
129387** If the phrase pExpr consists entirely of deferred tokens, then all X and
129388** Y values are set to nDoc, where nDoc is the number of documents in the
129389** file system. This is done because the full-text index doclist is required
129390** to calculate these values properly, and the full-text index doclist is
129391** not available for deferred tokens.
129392*/
129393static int fts3ExprGlobalHitsCb(
129394  Fts3Expr *pExpr,                /* Phrase expression node */
129395  int iPhrase,                    /* Phrase number (numbered from zero) */
129396  void *pCtx                      /* Pointer to MatchInfo structure */
129397){
129398  MatchInfo *p = (MatchInfo *)pCtx;
129399  return sqlite3Fts3EvalPhraseStats(
129400      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
129401  );
129402}
129403
129404/*
129405** fts3ExprIterate() callback used to collect the "local" part of the
129406** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
129407** array that are different for each row returned by the query.
129408*/
129409static int fts3ExprLocalHitsCb(
129410  Fts3Expr *pExpr,                /* Phrase expression node */
129411  int iPhrase,                    /* Phrase number */
129412  void *pCtx                      /* Pointer to MatchInfo structure */
129413){
129414  MatchInfo *p = (MatchInfo *)pCtx;
129415  int iStart = iPhrase * p->nCol * 3;
129416  int i;
129417
129418  for(i=0; i<p->nCol; i++){
129419    char *pCsr;
129420    pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i);
129421    if( pCsr ){
129422      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
129423    }else{
129424      p->aMatchinfo[iStart+i*3] = 0;
129425    }
129426  }
129427
129428  return SQLITE_OK;
129429}
129430
129431static int fts3MatchinfoCheck(
129432  Fts3Table *pTab,
129433  char cArg,
129434  char **pzErr
129435){
129436  if( (cArg==FTS3_MATCHINFO_NPHRASE)
129437   || (cArg==FTS3_MATCHINFO_NCOL)
129438   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
129439   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
129440   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
129441   || (cArg==FTS3_MATCHINFO_LCS)
129442   || (cArg==FTS3_MATCHINFO_HITS)
129443  ){
129444    return SQLITE_OK;
129445  }
129446  *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
129447  return SQLITE_ERROR;
129448}
129449
129450static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
129451  int nVal;                       /* Number of integers output by cArg */
129452
129453  switch( cArg ){
129454    case FTS3_MATCHINFO_NDOC:
129455    case FTS3_MATCHINFO_NPHRASE:
129456    case FTS3_MATCHINFO_NCOL:
129457      nVal = 1;
129458      break;
129459
129460    case FTS3_MATCHINFO_AVGLENGTH:
129461    case FTS3_MATCHINFO_LENGTH:
129462    case FTS3_MATCHINFO_LCS:
129463      nVal = pInfo->nCol;
129464      break;
129465
129466    default:
129467      assert( cArg==FTS3_MATCHINFO_HITS );
129468      nVal = pInfo->nCol * pInfo->nPhrase * 3;
129469      break;
129470  }
129471
129472  return nVal;
129473}
129474
129475static int fts3MatchinfoSelectDoctotal(
129476  Fts3Table *pTab,
129477  sqlite3_stmt **ppStmt,
129478  sqlite3_int64 *pnDoc,
129479  const char **paLen
129480){
129481  sqlite3_stmt *pStmt;
129482  const char *a;
129483  sqlite3_int64 nDoc;
129484
129485  if( !*ppStmt ){
129486    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
129487    if( rc!=SQLITE_OK ) return rc;
129488  }
129489  pStmt = *ppStmt;
129490  assert( sqlite3_data_count(pStmt)==1 );
129491
129492  a = sqlite3_column_blob(pStmt, 0);
129493  a += sqlite3Fts3GetVarint(a, &nDoc);
129494  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
129495  *pnDoc = (u32)nDoc;
129496
129497  if( paLen ) *paLen = a;
129498  return SQLITE_OK;
129499}
129500
129501/*
129502** An instance of the following structure is used to store state while
129503** iterating through a multi-column position-list corresponding to the
129504** hits for a single phrase on a single row in order to calculate the
129505** values for a matchinfo() FTS3_MATCHINFO_LCS request.
129506*/
129507typedef struct LcsIterator LcsIterator;
129508struct LcsIterator {
129509  Fts3Expr *pExpr;                /* Pointer to phrase expression */
129510  int iPosOffset;                 /* Tokens count up to end of this phrase */
129511  char *pRead;                    /* Cursor used to iterate through aDoclist */
129512  int iPos;                       /* Current position */
129513};
129514
129515/*
129516** If LcsIterator.iCol is set to the following value, the iterator has
129517** finished iterating through all offsets for all columns.
129518*/
129519#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
129520
129521static int fts3MatchinfoLcsCb(
129522  Fts3Expr *pExpr,                /* Phrase expression node */
129523  int iPhrase,                    /* Phrase number (numbered from zero) */
129524  void *pCtx                      /* Pointer to MatchInfo structure */
129525){
129526  LcsIterator *aIter = (LcsIterator *)pCtx;
129527  aIter[iPhrase].pExpr = pExpr;
129528  return SQLITE_OK;
129529}
129530
129531/*
129532** Advance the iterator passed as an argument to the next position. Return
129533** 1 if the iterator is at EOF or if it now points to the start of the
129534** position list for the next column.
129535*/
129536static int fts3LcsIteratorAdvance(LcsIterator *pIter){
129537  char *pRead = pIter->pRead;
129538  sqlite3_int64 iRead;
129539  int rc = 0;
129540
129541  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
129542  if( iRead==0 || iRead==1 ){
129543    pRead = 0;
129544    rc = 1;
129545  }else{
129546    pIter->iPos += (int)(iRead-2);
129547  }
129548
129549  pIter->pRead = pRead;
129550  return rc;
129551}
129552
129553/*
129554** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
129555**
129556** If the call is successful, the longest-common-substring lengths for each
129557** column are written into the first nCol elements of the pInfo->aMatchinfo[]
129558** array before returning. SQLITE_OK is returned in this case.
129559**
129560** Otherwise, if an error occurs, an SQLite error code is returned and the
129561** data written to the first nCol elements of pInfo->aMatchinfo[] is
129562** undefined.
129563*/
129564static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
129565  LcsIterator *aIter;
129566  int i;
129567  int iCol;
129568  int nToken = 0;
129569
129570  /* Allocate and populate the array of LcsIterator objects. The array
129571  ** contains one element for each matchable phrase in the query.
129572  **/
129573  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
129574  if( !aIter ) return SQLITE_NOMEM;
129575  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
129576  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
129577
129578  for(i=0; i<pInfo->nPhrase; i++){
129579    LcsIterator *pIter = &aIter[i];
129580    nToken -= pIter->pExpr->pPhrase->nToken;
129581    pIter->iPosOffset = nToken;
129582  }
129583
129584  for(iCol=0; iCol<pInfo->nCol; iCol++){
129585    int nLcs = 0;                 /* LCS value for this column */
129586    int nLive = 0;                /* Number of iterators in aIter not at EOF */
129587
129588    for(i=0; i<pInfo->nPhrase; i++){
129589      LcsIterator *pIt = &aIter[i];
129590      pIt->pRead = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol);
129591      if( pIt->pRead ){
129592        pIt->iPos = pIt->iPosOffset;
129593        fts3LcsIteratorAdvance(&aIter[i]);
129594        nLive++;
129595      }
129596    }
129597
129598    while( nLive>0 ){
129599      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
129600      int nThisLcs = 0;           /* LCS for the current iterator positions */
129601
129602      for(i=0; i<pInfo->nPhrase; i++){
129603        LcsIterator *pIter = &aIter[i];
129604        if( pIter->pRead==0 ){
129605          /* This iterator is already at EOF for this column. */
129606          nThisLcs = 0;
129607        }else{
129608          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
129609            pAdv = pIter;
129610          }
129611          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
129612            nThisLcs++;
129613          }else{
129614            nThisLcs = 1;
129615          }
129616          if( nThisLcs>nLcs ) nLcs = nThisLcs;
129617        }
129618      }
129619      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
129620    }
129621
129622    pInfo->aMatchinfo[iCol] = nLcs;
129623  }
129624
129625  sqlite3_free(aIter);
129626  return SQLITE_OK;
129627}
129628
129629/*
129630** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
129631** be returned by the matchinfo() function. Argument zArg contains the
129632** format string passed as the second argument to matchinfo (or the
129633** default value "pcx" if no second argument was specified). The format
129634** string has already been validated and the pInfo->aMatchinfo[] array
129635** is guaranteed to be large enough for the output.
129636**
129637** If bGlobal is true, then populate all fields of the matchinfo() output.
129638** If it is false, then assume that those fields that do not change between
129639** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
129640** have already been populated.
129641**
129642** Return SQLITE_OK if successful, or an SQLite error code if an error
129643** occurs. If a value other than SQLITE_OK is returned, the state the
129644** pInfo->aMatchinfo[] buffer is left in is undefined.
129645*/
129646static int fts3MatchinfoValues(
129647  Fts3Cursor *pCsr,               /* FTS3 cursor object */
129648  int bGlobal,                    /* True to grab the global stats */
129649  MatchInfo *pInfo,               /* Matchinfo context object */
129650  const char *zArg                /* Matchinfo format string */
129651){
129652  int rc = SQLITE_OK;
129653  int i;
129654  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129655  sqlite3_stmt *pSelect = 0;
129656
129657  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
129658
129659    switch( zArg[i] ){
129660      case FTS3_MATCHINFO_NPHRASE:
129661        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
129662        break;
129663
129664      case FTS3_MATCHINFO_NCOL:
129665        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
129666        break;
129667
129668      case FTS3_MATCHINFO_NDOC:
129669        if( bGlobal ){
129670          sqlite3_int64 nDoc = 0;
129671          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
129672          pInfo->aMatchinfo[0] = (u32)nDoc;
129673        }
129674        break;
129675
129676      case FTS3_MATCHINFO_AVGLENGTH:
129677        if( bGlobal ){
129678          sqlite3_int64 nDoc;     /* Number of rows in table */
129679          const char *a;          /* Aggregate column length array */
129680
129681          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
129682          if( rc==SQLITE_OK ){
129683            int iCol;
129684            for(iCol=0; iCol<pInfo->nCol; iCol++){
129685              u32 iVal;
129686              sqlite3_int64 nToken;
129687              a += sqlite3Fts3GetVarint(a, &nToken);
129688              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
129689              pInfo->aMatchinfo[iCol] = iVal;
129690            }
129691          }
129692        }
129693        break;
129694
129695      case FTS3_MATCHINFO_LENGTH: {
129696        sqlite3_stmt *pSelectDocsize = 0;
129697        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
129698        if( rc==SQLITE_OK ){
129699          int iCol;
129700          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
129701          for(iCol=0; iCol<pInfo->nCol; iCol++){
129702            sqlite3_int64 nToken;
129703            a += sqlite3Fts3GetVarint(a, &nToken);
129704            pInfo->aMatchinfo[iCol] = (u32)nToken;
129705          }
129706        }
129707        sqlite3_reset(pSelectDocsize);
129708        break;
129709      }
129710
129711      case FTS3_MATCHINFO_LCS:
129712        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
129713        if( rc==SQLITE_OK ){
129714          rc = fts3MatchinfoLcs(pCsr, pInfo);
129715        }
129716        break;
129717
129718      default: {
129719        Fts3Expr *pExpr;
129720        assert( zArg[i]==FTS3_MATCHINFO_HITS );
129721        pExpr = pCsr->pExpr;
129722        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
129723        if( rc!=SQLITE_OK ) break;
129724        if( bGlobal ){
129725          if( pCsr->pDeferred ){
129726            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
129727            if( rc!=SQLITE_OK ) break;
129728          }
129729          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
129730          if( rc!=SQLITE_OK ) break;
129731        }
129732        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
129733        break;
129734      }
129735    }
129736
129737    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
129738  }
129739
129740  sqlite3_reset(pSelect);
129741  return rc;
129742}
129743
129744
129745/*
129746** Populate pCsr->aMatchinfo[] with data for the current row. The
129747** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
129748*/
129749static int fts3GetMatchinfo(
129750  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
129751  const char *zArg                /* Second argument to matchinfo() function */
129752){
129753  MatchInfo sInfo;
129754  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129755  int rc = SQLITE_OK;
129756  int bGlobal = 0;                /* Collect 'global' stats as well as local */
129757
129758  memset(&sInfo, 0, sizeof(MatchInfo));
129759  sInfo.pCursor = pCsr;
129760  sInfo.nCol = pTab->nColumn;
129761
129762  /* If there is cached matchinfo() data, but the format string for the
129763  ** cache does not match the format string for this request, discard
129764  ** the cached data. */
129765  if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
129766    assert( pCsr->aMatchinfo );
129767    sqlite3_free(pCsr->aMatchinfo);
129768    pCsr->zMatchinfo = 0;
129769    pCsr->aMatchinfo = 0;
129770  }
129771
129772  /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
129773  ** matchinfo function has been called for this query. In this case
129774  ** allocate the array used to accumulate the matchinfo data and
129775  ** initialize those elements that are constant for every row.
129776  */
129777  if( pCsr->aMatchinfo==0 ){
129778    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
129779    int nArg;                     /* Bytes in zArg */
129780    int i;                        /* Used to iterate through zArg */
129781
129782    /* Determine the number of phrases in the query */
129783    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
129784    sInfo.nPhrase = pCsr->nPhrase;
129785
129786    /* Determine the number of integers in the buffer returned by this call. */
129787    for(i=0; zArg[i]; i++){
129788      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
129789    }
129790
129791    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
129792    nArg = (int)strlen(zArg);
129793    pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
129794    if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
129795
129796    pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
129797    pCsr->nMatchinfo = nMatchinfo;
129798    memcpy(pCsr->zMatchinfo, zArg, nArg+1);
129799    memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
129800    pCsr->isMatchinfoNeeded = 1;
129801    bGlobal = 1;
129802  }
129803
129804  sInfo.aMatchinfo = pCsr->aMatchinfo;
129805  sInfo.nPhrase = pCsr->nPhrase;
129806  if( pCsr->isMatchinfoNeeded ){
129807    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
129808    pCsr->isMatchinfoNeeded = 0;
129809  }
129810
129811  return rc;
129812}
129813
129814/*
129815** Implementation of snippet() function.
129816*/
129817SQLITE_PRIVATE void sqlite3Fts3Snippet(
129818  sqlite3_context *pCtx,          /* SQLite function call context */
129819  Fts3Cursor *pCsr,               /* Cursor object */
129820  const char *zStart,             /* Snippet start text - "<b>" */
129821  const char *zEnd,               /* Snippet end text - "</b>" */
129822  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
129823  int iCol,                       /* Extract snippet from this column */
129824  int nToken                      /* Approximate number of tokens in snippet */
129825){
129826  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129827  int rc = SQLITE_OK;
129828  int i;
129829  StrBuffer res = {0, 0, 0};
129830
129831  /* The returned text includes up to four fragments of text extracted from
129832  ** the data in the current row. The first iteration of the for(...) loop
129833  ** below attempts to locate a single fragment of text nToken tokens in
129834  ** size that contains at least one instance of all phrases in the query
129835  ** expression that appear in the current row. If such a fragment of text
129836  ** cannot be found, the second iteration of the loop attempts to locate
129837  ** a pair of fragments, and so on.
129838  */
129839  int nSnippet = 0;               /* Number of fragments in this snippet */
129840  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
129841  int nFToken = -1;               /* Number of tokens in each fragment */
129842
129843  if( !pCsr->pExpr ){
129844    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
129845    return;
129846  }
129847
129848  for(nSnippet=1; 1; nSnippet++){
129849
129850    int iSnip;                    /* Loop counter 0..nSnippet-1 */
129851    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
129852    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
129853
129854    if( nToken>=0 ){
129855      nFToken = (nToken+nSnippet-1) / nSnippet;
129856    }else{
129857      nFToken = -1 * nToken;
129858    }
129859
129860    for(iSnip=0; iSnip<nSnippet; iSnip++){
129861      int iBestScore = -1;        /* Best score of columns checked so far */
129862      int iRead;                  /* Used to iterate through columns */
129863      SnippetFragment *pFragment = &aSnippet[iSnip];
129864
129865      memset(pFragment, 0, sizeof(*pFragment));
129866
129867      /* Loop through all columns of the table being considered for snippets.
129868      ** If the iCol argument to this function was negative, this means all
129869      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
129870      */
129871      for(iRead=0; iRead<pTab->nColumn; iRead++){
129872        SnippetFragment sF = {0, 0, 0, 0};
129873        int iS;
129874        if( iCol>=0 && iRead!=iCol ) continue;
129875
129876        /* Find the best snippet of nFToken tokens in column iRead. */
129877        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
129878        if( rc!=SQLITE_OK ){
129879          goto snippet_out;
129880        }
129881        if( iS>iBestScore ){
129882          *pFragment = sF;
129883          iBestScore = iS;
129884        }
129885      }
129886
129887      mCovered |= pFragment->covered;
129888    }
129889
129890    /* If all query phrases seen by fts3BestSnippet() are present in at least
129891    ** one of the nSnippet snippet fragments, break out of the loop.
129892    */
129893    assert( (mCovered&mSeen)==mCovered );
129894    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
129895  }
129896
129897  assert( nFToken>0 );
129898
129899  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
129900    rc = fts3SnippetText(pCsr, &aSnippet[i],
129901        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
129902    );
129903  }
129904
129905 snippet_out:
129906  sqlite3Fts3SegmentsClose(pTab);
129907  if( rc!=SQLITE_OK ){
129908    sqlite3_result_error_code(pCtx, rc);
129909    sqlite3_free(res.z);
129910  }else{
129911    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
129912  }
129913}
129914
129915
129916typedef struct TermOffset TermOffset;
129917typedef struct TermOffsetCtx TermOffsetCtx;
129918
129919struct TermOffset {
129920  char *pList;                    /* Position-list */
129921  int iPos;                       /* Position just read from pList */
129922  int iOff;                       /* Offset of this term from read positions */
129923};
129924
129925struct TermOffsetCtx {
129926  Fts3Cursor *pCsr;
129927  int iCol;                       /* Column of table to populate aTerm for */
129928  int iTerm;
129929  sqlite3_int64 iDocid;
129930  TermOffset *aTerm;
129931};
129932
129933/*
129934** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
129935*/
129936static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
129937  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
129938  int nTerm;                      /* Number of tokens in phrase */
129939  int iTerm;                      /* For looping through nTerm phrase terms */
129940  char *pList;                    /* Pointer to position list for phrase */
129941  int iPos = 0;                   /* First position in position-list */
129942
129943  UNUSED_PARAMETER(iPhrase);
129944  pList = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
129945  nTerm = pExpr->pPhrase->nToken;
129946  if( pList ){
129947    fts3GetDeltaPosition(&pList, &iPos);
129948    assert( iPos>=0 );
129949  }
129950
129951  for(iTerm=0; iTerm<nTerm; iTerm++){
129952    TermOffset *pT = &p->aTerm[p->iTerm++];
129953    pT->iOff = nTerm-iTerm-1;
129954    pT->pList = pList;
129955    pT->iPos = iPos;
129956  }
129957
129958  return SQLITE_OK;
129959}
129960
129961/*
129962** Implementation of offsets() function.
129963*/
129964SQLITE_PRIVATE void sqlite3Fts3Offsets(
129965  sqlite3_context *pCtx,          /* SQLite function call context */
129966  Fts3Cursor *pCsr                /* Cursor object */
129967){
129968  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129969  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
129970  const char *ZDUMMY;             /* Dummy argument used with xNext() */
129971  int NDUMMY;                     /* Dummy argument used with xNext() */
129972  int rc;                         /* Return Code */
129973  int nToken;                     /* Number of tokens in query */
129974  int iCol;                       /* Column currently being processed */
129975  StrBuffer res = {0, 0, 0};      /* Result string */
129976  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
129977
129978  if( !pCsr->pExpr ){
129979    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
129980    return;
129981  }
129982
129983  memset(&sCtx, 0, sizeof(sCtx));
129984  assert( pCsr->isRequireSeek==0 );
129985
129986  /* Count the number of terms in the query */
129987  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
129988  if( rc!=SQLITE_OK ) goto offsets_out;
129989
129990  /* Allocate the array of TermOffset iterators. */
129991  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
129992  if( 0==sCtx.aTerm ){
129993    rc = SQLITE_NOMEM;
129994    goto offsets_out;
129995  }
129996  sCtx.iDocid = pCsr->iPrevId;
129997  sCtx.pCsr = pCsr;
129998
129999  /* Loop through the table columns, appending offset information to
130000  ** string-buffer res for each column.
130001  */
130002  for(iCol=0; iCol<pTab->nColumn; iCol++){
130003    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
130004    int iStart;
130005    int iEnd;
130006    int iCurrent;
130007    const char *zDoc;
130008    int nDoc;
130009
130010    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
130011    ** no way that this operation can fail, so the return code from
130012    ** fts3ExprIterate() can be discarded.
130013    */
130014    sCtx.iCol = iCol;
130015    sCtx.iTerm = 0;
130016    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
130017
130018    /* Retreive the text stored in column iCol. If an SQL NULL is stored
130019    ** in column iCol, jump immediately to the next iteration of the loop.
130020    ** If an OOM occurs while retrieving the data (this can happen if SQLite
130021    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
130022    ** to the caller.
130023    */
130024    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
130025    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
130026    if( zDoc==0 ){
130027      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
130028        continue;
130029      }
130030      rc = SQLITE_NOMEM;
130031      goto offsets_out;
130032    }
130033
130034    /* Initialize a tokenizer iterator to iterate through column iCol. */
130035    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
130036        zDoc, nDoc, &pC
130037    );
130038    if( rc!=SQLITE_OK ) goto offsets_out;
130039
130040    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
130041    while( rc==SQLITE_OK ){
130042      int i;                      /* Used to loop through terms */
130043      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
130044      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
130045
130046      for(i=0; i<nToken; i++){
130047        TermOffset *pT = &sCtx.aTerm[i];
130048        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
130049          iMinPos = pT->iPos-pT->iOff;
130050          pTerm = pT;
130051        }
130052      }
130053
130054      if( !pTerm ){
130055        /* All offsets for this column have been gathered. */
130056        rc = SQLITE_DONE;
130057      }else{
130058        assert( iCurrent<=iMinPos );
130059        if( 0==(0xFE&*pTerm->pList) ){
130060          pTerm->pList = 0;
130061        }else{
130062          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
130063        }
130064        while( rc==SQLITE_OK && iCurrent<iMinPos ){
130065          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
130066        }
130067        if( rc==SQLITE_OK ){
130068          char aBuffer[64];
130069          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
130070              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
130071          );
130072          rc = fts3StringAppend(&res, aBuffer, -1);
130073        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
130074          rc = FTS_CORRUPT_VTAB;
130075        }
130076      }
130077    }
130078    if( rc==SQLITE_DONE ){
130079      rc = SQLITE_OK;
130080    }
130081
130082    pMod->xClose(pC);
130083    if( rc!=SQLITE_OK ) goto offsets_out;
130084  }
130085
130086 offsets_out:
130087  sqlite3_free(sCtx.aTerm);
130088  assert( rc!=SQLITE_DONE );
130089  sqlite3Fts3SegmentsClose(pTab);
130090  if( rc!=SQLITE_OK ){
130091    sqlite3_result_error_code(pCtx,  rc);
130092    sqlite3_free(res.z);
130093  }else{
130094    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
130095  }
130096  return;
130097}
130098
130099/*
130100** Implementation of matchinfo() function.
130101*/
130102SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
130103  sqlite3_context *pContext,      /* Function call context */
130104  Fts3Cursor *pCsr,               /* FTS3 table cursor */
130105  const char *zArg                /* Second arg to matchinfo() function */
130106){
130107  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
130108  int rc;
130109  int i;
130110  const char *zFormat;
130111
130112  if( zArg ){
130113    for(i=0; zArg[i]; i++){
130114      char *zErr = 0;
130115      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
130116        sqlite3_result_error(pContext, zErr, -1);
130117        sqlite3_free(zErr);
130118        return;
130119      }
130120    }
130121    zFormat = zArg;
130122  }else{
130123    zFormat = FTS3_MATCHINFO_DEFAULT;
130124  }
130125
130126  if( !pCsr->pExpr ){
130127    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
130128    return;
130129  }
130130
130131  /* Retrieve matchinfo() data. */
130132  rc = fts3GetMatchinfo(pCsr, zFormat);
130133  sqlite3Fts3SegmentsClose(pTab);
130134
130135  if( rc!=SQLITE_OK ){
130136    sqlite3_result_error_code(pContext, rc);
130137  }else{
130138    int n = pCsr->nMatchinfo * sizeof(u32);
130139    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
130140  }
130141}
130142
130143#endif
130144
130145/************** End of fts3_snippet.c ****************************************/
130146/************** Begin file rtree.c *******************************************/
130147/*
130148** 2001 September 15
130149**
130150** The author disclaims copyright to this source code.  In place of
130151** a legal notice, here is a blessing:
130152**
130153**    May you do good and not evil.
130154**    May you find forgiveness for yourself and forgive others.
130155**    May you share freely, never taking more than you give.
130156**
130157*************************************************************************
130158** This file contains code for implementations of the r-tree and r*-tree
130159** algorithms packaged as an SQLite virtual table module.
130160*/
130161
130162/*
130163** Database Format of R-Tree Tables
130164** --------------------------------
130165**
130166** The data structure for a single virtual r-tree table is stored in three
130167** native SQLite tables declared as follows. In each case, the '%' character
130168** in the table name is replaced with the user-supplied name of the r-tree
130169** table.
130170**
130171**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
130172**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
130173**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
130174**
130175** The data for each node of the r-tree structure is stored in the %_node
130176** table. For each node that is not the root node of the r-tree, there is
130177** an entry in the %_parent table associating the node with its parent.
130178** And for each row of data in the table, there is an entry in the %_rowid
130179** table that maps from the entries rowid to the id of the node that it
130180** is stored on.
130181**
130182** The root node of an r-tree always exists, even if the r-tree table is
130183** empty. The nodeno of the root node is always 1. All other nodes in the
130184** table must be the same size as the root node. The content of each node
130185** is formatted as follows:
130186**
130187**   1. If the node is the root node (node 1), then the first 2 bytes
130188**      of the node contain the tree depth as a big-endian integer.
130189**      For non-root nodes, the first 2 bytes are left unused.
130190**
130191**   2. The next 2 bytes contain the number of entries currently
130192**      stored in the node.
130193**
130194**   3. The remainder of the node contains the node entries. Each entry
130195**      consists of a single 8-byte integer followed by an even number
130196**      of 4-byte coordinates. For leaf nodes the integer is the rowid
130197**      of a record. For internal nodes it is the node number of a
130198**      child page.
130199*/
130200
130201#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
130202
130203/*
130204** This file contains an implementation of a couple of different variants
130205** of the r-tree algorithm. See the README file for further details. The
130206** same data-structure is used for all, but the algorithms for insert and
130207** delete operations vary. The variants used are selected at compile time
130208** by defining the following symbols:
130209*/
130210
130211/* Either, both or none of the following may be set to activate
130212** r*tree variant algorithms.
130213*/
130214#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
130215#define VARIANT_RSTARTREE_REINSERT      1
130216
130217/*
130218** Exactly one of the following must be set to 1.
130219*/
130220#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
130221#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
130222#define VARIANT_RSTARTREE_SPLIT         1
130223
130224#define VARIANT_GUTTMAN_SPLIT \
130225        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
130226
130227#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
130228  #define PickNext QuadraticPickNext
130229  #define PickSeeds QuadraticPickSeeds
130230  #define AssignCells splitNodeGuttman
130231#endif
130232#if VARIANT_GUTTMAN_LINEAR_SPLIT
130233  #define PickNext LinearPickNext
130234  #define PickSeeds LinearPickSeeds
130235  #define AssignCells splitNodeGuttman
130236#endif
130237#if VARIANT_RSTARTREE_SPLIT
130238  #define AssignCells splitNodeStartree
130239#endif
130240
130241#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
130242# define NDEBUG 1
130243#endif
130244
130245#ifndef SQLITE_CORE
130246  SQLITE_EXTENSION_INIT1
130247#else
130248#endif
130249
130250/* #include <string.h> */
130251/* #include <assert.h> */
130252
130253#ifndef SQLITE_AMALGAMATION
130254#include "sqlite3rtree.h"
130255typedef sqlite3_int64 i64;
130256typedef unsigned char u8;
130257typedef unsigned int u32;
130258#endif
130259
130260/*  The following macro is used to suppress compiler warnings.
130261*/
130262#ifndef UNUSED_PARAMETER
130263# define UNUSED_PARAMETER(x) (void)(x)
130264#endif
130265
130266typedef struct Rtree Rtree;
130267typedef struct RtreeCursor RtreeCursor;
130268typedef struct RtreeNode RtreeNode;
130269typedef struct RtreeCell RtreeCell;
130270typedef struct RtreeConstraint RtreeConstraint;
130271typedef struct RtreeMatchArg RtreeMatchArg;
130272typedef struct RtreeGeomCallback RtreeGeomCallback;
130273typedef union RtreeCoord RtreeCoord;
130274
130275/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
130276#define RTREE_MAX_DIMENSIONS 5
130277
130278/* Size of hash table Rtree.aHash. This hash table is not expected to
130279** ever contain very many entries, so a fixed number of buckets is
130280** used.
130281*/
130282#define HASHSIZE 128
130283
130284/*
130285** An rtree virtual-table object.
130286*/
130287struct Rtree {
130288  sqlite3_vtab base;
130289  sqlite3 *db;                /* Host database connection */
130290  int iNodeSize;              /* Size in bytes of each node in the node table */
130291  int nDim;                   /* Number of dimensions */
130292  int nBytesPerCell;          /* Bytes consumed per cell */
130293  int iDepth;                 /* Current depth of the r-tree structure */
130294  char *zDb;                  /* Name of database containing r-tree table */
130295  char *zName;                /* Name of r-tree table */
130296  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
130297  int nBusy;                  /* Current number of users of this structure */
130298
130299  /* List of nodes removed during a CondenseTree operation. List is
130300  ** linked together via the pointer normally used for hash chains -
130301  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
130302  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
130303  */
130304  RtreeNode *pDeleted;
130305  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
130306
130307  /* Statements to read/write/delete a record from xxx_node */
130308  sqlite3_stmt *pReadNode;
130309  sqlite3_stmt *pWriteNode;
130310  sqlite3_stmt *pDeleteNode;
130311
130312  /* Statements to read/write/delete a record from xxx_rowid */
130313  sqlite3_stmt *pReadRowid;
130314  sqlite3_stmt *pWriteRowid;
130315  sqlite3_stmt *pDeleteRowid;
130316
130317  /* Statements to read/write/delete a record from xxx_parent */
130318  sqlite3_stmt *pReadParent;
130319  sqlite3_stmt *pWriteParent;
130320  sqlite3_stmt *pDeleteParent;
130321
130322  int eCoordType;
130323};
130324
130325/* Possible values for eCoordType: */
130326#define RTREE_COORD_REAL32 0
130327#define RTREE_COORD_INT32  1
130328
130329/*
130330** The minimum number of cells allowed for a node is a third of the
130331** maximum. In Gutman's notation:
130332**
130333**     m = M/3
130334**
130335** If an R*-tree "Reinsert" operation is required, the same number of
130336** cells are removed from the overfull node and reinserted into the tree.
130337*/
130338#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
130339#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
130340#define RTREE_MAXCELLS 51
130341
130342/*
130343** The smallest possible node-size is (512-64)==448 bytes. And the largest
130344** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
130345** Therefore all non-root nodes must contain at least 3 entries. Since
130346** 2^40 is greater than 2^64, an r-tree structure always has a depth of
130347** 40 or less.
130348*/
130349#define RTREE_MAX_DEPTH 40
130350
130351/*
130352** An rtree cursor object.
130353*/
130354struct RtreeCursor {
130355  sqlite3_vtab_cursor base;
130356  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
130357  int iCell;                        /* Index of current cell in pNode */
130358  int iStrategy;                    /* Copy of idxNum search parameter */
130359  int nConstraint;                  /* Number of entries in aConstraint */
130360  RtreeConstraint *aConstraint;     /* Search constraints. */
130361};
130362
130363union RtreeCoord {
130364  float f;
130365  int i;
130366};
130367
130368/*
130369** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
130370** formatted as a double. This macro assumes that local variable pRtree points
130371** to the Rtree structure associated with the RtreeCoord.
130372*/
130373#define DCOORD(coord) (                           \
130374  (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
130375    ((double)coord.f) :                           \
130376    ((double)coord.i)                             \
130377)
130378
130379/*
130380** A search constraint.
130381*/
130382struct RtreeConstraint {
130383  int iCoord;                     /* Index of constrained coordinate */
130384  int op;                         /* Constraining operation */
130385  double rValue;                  /* Constraint value. */
130386  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
130387  sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
130388};
130389
130390/* Possible values for RtreeConstraint.op */
130391#define RTREE_EQ    0x41
130392#define RTREE_LE    0x42
130393#define RTREE_LT    0x43
130394#define RTREE_GE    0x44
130395#define RTREE_GT    0x45
130396#define RTREE_MATCH 0x46
130397
130398/*
130399** An rtree structure node.
130400*/
130401struct RtreeNode {
130402  RtreeNode *pParent;               /* Parent node */
130403  i64 iNode;
130404  int nRef;
130405  int isDirty;
130406  u8 *zData;
130407  RtreeNode *pNext;                 /* Next node in this hash chain */
130408};
130409#define NCELL(pNode) readInt16(&(pNode)->zData[2])
130410
130411/*
130412** Structure to store a deserialized rtree record.
130413*/
130414struct RtreeCell {
130415  i64 iRowid;
130416  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
130417};
130418
130419
130420/*
130421** Value for the first field of every RtreeMatchArg object. The MATCH
130422** operator tests that the first field of a blob operand matches this
130423** value to avoid operating on invalid blobs (which could cause a segfault).
130424*/
130425#define RTREE_GEOMETRY_MAGIC 0x891245AB
130426
130427/*
130428** An instance of this structure must be supplied as a blob argument to
130429** the right-hand-side of an SQL MATCH operator used to constrain an
130430** r-tree query.
130431*/
130432struct RtreeMatchArg {
130433  u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
130434  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
130435  void *pContext;
130436  int nParam;
130437  double aParam[1];
130438};
130439
130440/*
130441** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
130442** a single instance of the following structure is allocated. It is used
130443** as the context for the user-function created by by s_r_g_c(). The object
130444** is eventually deleted by the destructor mechanism provided by
130445** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
130446** the geometry callback function).
130447*/
130448struct RtreeGeomCallback {
130449  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
130450  void *pContext;
130451};
130452
130453#ifndef MAX
130454# define MAX(x,y) ((x) < (y) ? (y) : (x))
130455#endif
130456#ifndef MIN
130457# define MIN(x,y) ((x) > (y) ? (y) : (x))
130458#endif
130459
130460/*
130461** Functions to deserialize a 16 bit integer, 32 bit real number and
130462** 64 bit integer. The deserialized value is returned.
130463*/
130464static int readInt16(u8 *p){
130465  return (p[0]<<8) + p[1];
130466}
130467static void readCoord(u8 *p, RtreeCoord *pCoord){
130468  u32 i = (
130469    (((u32)p[0]) << 24) +
130470    (((u32)p[1]) << 16) +
130471    (((u32)p[2]) <<  8) +
130472    (((u32)p[3]) <<  0)
130473  );
130474  *(u32 *)pCoord = i;
130475}
130476static i64 readInt64(u8 *p){
130477  return (
130478    (((i64)p[0]) << 56) +
130479    (((i64)p[1]) << 48) +
130480    (((i64)p[2]) << 40) +
130481    (((i64)p[3]) << 32) +
130482    (((i64)p[4]) << 24) +
130483    (((i64)p[5]) << 16) +
130484    (((i64)p[6]) <<  8) +
130485    (((i64)p[7]) <<  0)
130486  );
130487}
130488
130489/*
130490** Functions to serialize a 16 bit integer, 32 bit real number and
130491** 64 bit integer. The value returned is the number of bytes written
130492** to the argument buffer (always 2, 4 and 8 respectively).
130493*/
130494static int writeInt16(u8 *p, int i){
130495  p[0] = (i>> 8)&0xFF;
130496  p[1] = (i>> 0)&0xFF;
130497  return 2;
130498}
130499static int writeCoord(u8 *p, RtreeCoord *pCoord){
130500  u32 i;
130501  assert( sizeof(RtreeCoord)==4 );
130502  assert( sizeof(u32)==4 );
130503  i = *(u32 *)pCoord;
130504  p[0] = (i>>24)&0xFF;
130505  p[1] = (i>>16)&0xFF;
130506  p[2] = (i>> 8)&0xFF;
130507  p[3] = (i>> 0)&0xFF;
130508  return 4;
130509}
130510static int writeInt64(u8 *p, i64 i){
130511  p[0] = (i>>56)&0xFF;
130512  p[1] = (i>>48)&0xFF;
130513  p[2] = (i>>40)&0xFF;
130514  p[3] = (i>>32)&0xFF;
130515  p[4] = (i>>24)&0xFF;
130516  p[5] = (i>>16)&0xFF;
130517  p[6] = (i>> 8)&0xFF;
130518  p[7] = (i>> 0)&0xFF;
130519  return 8;
130520}
130521
130522/*
130523** Increment the reference count of node p.
130524*/
130525static void nodeReference(RtreeNode *p){
130526  if( p ){
130527    p->nRef++;
130528  }
130529}
130530
130531/*
130532** Clear the content of node p (set all bytes to 0x00).
130533*/
130534static void nodeZero(Rtree *pRtree, RtreeNode *p){
130535  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
130536  p->isDirty = 1;
130537}
130538
130539/*
130540** Given a node number iNode, return the corresponding key to use
130541** in the Rtree.aHash table.
130542*/
130543static int nodeHash(i64 iNode){
130544  return (
130545    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
130546    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
130547  ) % HASHSIZE;
130548}
130549
130550/*
130551** Search the node hash table for node iNode. If found, return a pointer
130552** to it. Otherwise, return 0.
130553*/
130554static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
130555  RtreeNode *p;
130556  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
130557  return p;
130558}
130559
130560/*
130561** Add node pNode to the node hash table.
130562*/
130563static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
130564  int iHash;
130565  assert( pNode->pNext==0 );
130566  iHash = nodeHash(pNode->iNode);
130567  pNode->pNext = pRtree->aHash[iHash];
130568  pRtree->aHash[iHash] = pNode;
130569}
130570
130571/*
130572** Remove node pNode from the node hash table.
130573*/
130574static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
130575  RtreeNode **pp;
130576  if( pNode->iNode!=0 ){
130577    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
130578    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
130579    *pp = pNode->pNext;
130580    pNode->pNext = 0;
130581  }
130582}
130583
130584/*
130585** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
130586** indicating that node has not yet been assigned a node number. It is
130587** assigned a node number when nodeWrite() is called to write the
130588** node contents out to the database.
130589*/
130590static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
130591  RtreeNode *pNode;
130592  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
130593  if( pNode ){
130594    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
130595    pNode->zData = (u8 *)&pNode[1];
130596    pNode->nRef = 1;
130597    pNode->pParent = pParent;
130598    pNode->isDirty = 1;
130599    nodeReference(pParent);
130600  }
130601  return pNode;
130602}
130603
130604/*
130605** Obtain a reference to an r-tree node.
130606*/
130607static int
130608nodeAcquire(
130609  Rtree *pRtree,             /* R-tree structure */
130610  i64 iNode,                 /* Node number to load */
130611  RtreeNode *pParent,        /* Either the parent node or NULL */
130612  RtreeNode **ppNode         /* OUT: Acquired node */
130613){
130614  int rc;
130615  int rc2 = SQLITE_OK;
130616  RtreeNode *pNode;
130617
130618  /* Check if the requested node is already in the hash table. If so,
130619  ** increase its reference count and return it.
130620  */
130621  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
130622    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
130623    if( pParent && !pNode->pParent ){
130624      nodeReference(pParent);
130625      pNode->pParent = pParent;
130626    }
130627    pNode->nRef++;
130628    *ppNode = pNode;
130629    return SQLITE_OK;
130630  }
130631
130632  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
130633  rc = sqlite3_step(pRtree->pReadNode);
130634  if( rc==SQLITE_ROW ){
130635    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
130636    if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
130637      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
130638      if( !pNode ){
130639        rc2 = SQLITE_NOMEM;
130640      }else{
130641        pNode->pParent = pParent;
130642        pNode->zData = (u8 *)&pNode[1];
130643        pNode->nRef = 1;
130644        pNode->iNode = iNode;
130645        pNode->isDirty = 0;
130646        pNode->pNext = 0;
130647        memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
130648        nodeReference(pParent);
130649      }
130650    }
130651  }
130652  rc = sqlite3_reset(pRtree->pReadNode);
130653  if( rc==SQLITE_OK ) rc = rc2;
130654
130655  /* If the root node was just loaded, set pRtree->iDepth to the height
130656  ** of the r-tree structure. A height of zero means all data is stored on
130657  ** the root node. A height of one means the children of the root node
130658  ** are the leaves, and so on. If the depth as specified on the root node
130659  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
130660  */
130661  if( pNode && iNode==1 ){
130662    pRtree->iDepth = readInt16(pNode->zData);
130663    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
130664      rc = SQLITE_CORRUPT_VTAB;
130665    }
130666  }
130667
130668  /* If no error has occurred so far, check if the "number of entries"
130669  ** field on the node is too large. If so, set the return code to
130670  ** SQLITE_CORRUPT_VTAB.
130671  */
130672  if( pNode && rc==SQLITE_OK ){
130673    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
130674      rc = SQLITE_CORRUPT_VTAB;
130675    }
130676  }
130677
130678  if( rc==SQLITE_OK ){
130679    if( pNode!=0 ){
130680      nodeHashInsert(pRtree, pNode);
130681    }else{
130682      rc = SQLITE_CORRUPT_VTAB;
130683    }
130684    *ppNode = pNode;
130685  }else{
130686    sqlite3_free(pNode);
130687    *ppNode = 0;
130688  }
130689
130690  return rc;
130691}
130692
130693/*
130694** Overwrite cell iCell of node pNode with the contents of pCell.
130695*/
130696static void nodeOverwriteCell(
130697  Rtree *pRtree,
130698  RtreeNode *pNode,
130699  RtreeCell *pCell,
130700  int iCell
130701){
130702  int ii;
130703  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
130704  p += writeInt64(p, pCell->iRowid);
130705  for(ii=0; ii<(pRtree->nDim*2); ii++){
130706    p += writeCoord(p, &pCell->aCoord[ii]);
130707  }
130708  pNode->isDirty = 1;
130709}
130710
130711/*
130712** Remove cell the cell with index iCell from node pNode.
130713*/
130714static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
130715  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
130716  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
130717  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
130718  memmove(pDst, pSrc, nByte);
130719  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
130720  pNode->isDirty = 1;
130721}
130722
130723/*
130724** Insert the contents of cell pCell into node pNode. If the insert
130725** is successful, return SQLITE_OK.
130726**
130727** If there is not enough free space in pNode, return SQLITE_FULL.
130728*/
130729static int
130730nodeInsertCell(
130731  Rtree *pRtree,
130732  RtreeNode *pNode,
130733  RtreeCell *pCell
130734){
130735  int nCell;                    /* Current number of cells in pNode */
130736  int nMaxCell;                 /* Maximum number of cells for pNode */
130737
130738  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
130739  nCell = NCELL(pNode);
130740
130741  assert( nCell<=nMaxCell );
130742  if( nCell<nMaxCell ){
130743    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
130744    writeInt16(&pNode->zData[2], nCell+1);
130745    pNode->isDirty = 1;
130746  }
130747
130748  return (nCell==nMaxCell);
130749}
130750
130751/*
130752** If the node is dirty, write it out to the database.
130753*/
130754static int
130755nodeWrite(Rtree *pRtree, RtreeNode *pNode){
130756  int rc = SQLITE_OK;
130757  if( pNode->isDirty ){
130758    sqlite3_stmt *p = pRtree->pWriteNode;
130759    if( pNode->iNode ){
130760      sqlite3_bind_int64(p, 1, pNode->iNode);
130761    }else{
130762      sqlite3_bind_null(p, 1);
130763    }
130764    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
130765    sqlite3_step(p);
130766    pNode->isDirty = 0;
130767    rc = sqlite3_reset(p);
130768    if( pNode->iNode==0 && rc==SQLITE_OK ){
130769      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
130770      nodeHashInsert(pRtree, pNode);
130771    }
130772  }
130773  return rc;
130774}
130775
130776/*
130777** Release a reference to a node. If the node is dirty and the reference
130778** count drops to zero, the node data is written to the database.
130779*/
130780static int
130781nodeRelease(Rtree *pRtree, RtreeNode *pNode){
130782  int rc = SQLITE_OK;
130783  if( pNode ){
130784    assert( pNode->nRef>0 );
130785    pNode->nRef--;
130786    if( pNode->nRef==0 ){
130787      if( pNode->iNode==1 ){
130788        pRtree->iDepth = -1;
130789      }
130790      if( pNode->pParent ){
130791        rc = nodeRelease(pRtree, pNode->pParent);
130792      }
130793      if( rc==SQLITE_OK ){
130794        rc = nodeWrite(pRtree, pNode);
130795      }
130796      nodeHashDelete(pRtree, pNode);
130797      sqlite3_free(pNode);
130798    }
130799  }
130800  return rc;
130801}
130802
130803/*
130804** Return the 64-bit integer value associated with cell iCell of
130805** node pNode. If pNode is a leaf node, this is a rowid. If it is
130806** an internal node, then the 64-bit integer is a child page number.
130807*/
130808static i64 nodeGetRowid(
130809  Rtree *pRtree,
130810  RtreeNode *pNode,
130811  int iCell
130812){
130813  assert( iCell<NCELL(pNode) );
130814  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
130815}
130816
130817/*
130818** Return coordinate iCoord from cell iCell in node pNode.
130819*/
130820static void nodeGetCoord(
130821  Rtree *pRtree,
130822  RtreeNode *pNode,
130823  int iCell,
130824  int iCoord,
130825  RtreeCoord *pCoord           /* Space to write result to */
130826){
130827  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
130828}
130829
130830/*
130831** Deserialize cell iCell of node pNode. Populate the structure pointed
130832** to by pCell with the results.
130833*/
130834static void nodeGetCell(
130835  Rtree *pRtree,
130836  RtreeNode *pNode,
130837  int iCell,
130838  RtreeCell *pCell
130839){
130840  int ii;
130841  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
130842  for(ii=0; ii<pRtree->nDim*2; ii++){
130843    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
130844  }
130845}
130846
130847
130848/* Forward declaration for the function that does the work of
130849** the virtual table module xCreate() and xConnect() methods.
130850*/
130851static int rtreeInit(
130852  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
130853);
130854
130855/*
130856** Rtree virtual table module xCreate method.
130857*/
130858static int rtreeCreate(
130859  sqlite3 *db,
130860  void *pAux,
130861  int argc, const char *const*argv,
130862  sqlite3_vtab **ppVtab,
130863  char **pzErr
130864){
130865  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
130866}
130867
130868/*
130869** Rtree virtual table module xConnect method.
130870*/
130871static int rtreeConnect(
130872  sqlite3 *db,
130873  void *pAux,
130874  int argc, const char *const*argv,
130875  sqlite3_vtab **ppVtab,
130876  char **pzErr
130877){
130878  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
130879}
130880
130881/*
130882** Increment the r-tree reference count.
130883*/
130884static void rtreeReference(Rtree *pRtree){
130885  pRtree->nBusy++;
130886}
130887
130888/*
130889** Decrement the r-tree reference count. When the reference count reaches
130890** zero the structure is deleted.
130891*/
130892static void rtreeRelease(Rtree *pRtree){
130893  pRtree->nBusy--;
130894  if( pRtree->nBusy==0 ){
130895    sqlite3_finalize(pRtree->pReadNode);
130896    sqlite3_finalize(pRtree->pWriteNode);
130897    sqlite3_finalize(pRtree->pDeleteNode);
130898    sqlite3_finalize(pRtree->pReadRowid);
130899    sqlite3_finalize(pRtree->pWriteRowid);
130900    sqlite3_finalize(pRtree->pDeleteRowid);
130901    sqlite3_finalize(pRtree->pReadParent);
130902    sqlite3_finalize(pRtree->pWriteParent);
130903    sqlite3_finalize(pRtree->pDeleteParent);
130904    sqlite3_free(pRtree);
130905  }
130906}
130907
130908/*
130909** Rtree virtual table module xDisconnect method.
130910*/
130911static int rtreeDisconnect(sqlite3_vtab *pVtab){
130912  rtreeRelease((Rtree *)pVtab);
130913  return SQLITE_OK;
130914}
130915
130916/*
130917** Rtree virtual table module xDestroy method.
130918*/
130919static int rtreeDestroy(sqlite3_vtab *pVtab){
130920  Rtree *pRtree = (Rtree *)pVtab;
130921  int rc;
130922  char *zCreate = sqlite3_mprintf(
130923    "DROP TABLE '%q'.'%q_node';"
130924    "DROP TABLE '%q'.'%q_rowid';"
130925    "DROP TABLE '%q'.'%q_parent';",
130926    pRtree->zDb, pRtree->zName,
130927    pRtree->zDb, pRtree->zName,
130928    pRtree->zDb, pRtree->zName
130929  );
130930  if( !zCreate ){
130931    rc = SQLITE_NOMEM;
130932  }else{
130933    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
130934    sqlite3_free(zCreate);
130935  }
130936  if( rc==SQLITE_OK ){
130937    rtreeRelease(pRtree);
130938  }
130939
130940  return rc;
130941}
130942
130943/*
130944** Rtree virtual table module xOpen method.
130945*/
130946static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
130947  int rc = SQLITE_NOMEM;
130948  RtreeCursor *pCsr;
130949
130950  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
130951  if( pCsr ){
130952    memset(pCsr, 0, sizeof(RtreeCursor));
130953    pCsr->base.pVtab = pVTab;
130954    rc = SQLITE_OK;
130955  }
130956  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
130957
130958  return rc;
130959}
130960
130961
130962/*
130963** Free the RtreeCursor.aConstraint[] array and its contents.
130964*/
130965static void freeCursorConstraints(RtreeCursor *pCsr){
130966  if( pCsr->aConstraint ){
130967    int i;                        /* Used to iterate through constraint array */
130968    for(i=0; i<pCsr->nConstraint; i++){
130969      sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
130970      if( pGeom ){
130971        if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
130972        sqlite3_free(pGeom);
130973      }
130974    }
130975    sqlite3_free(pCsr->aConstraint);
130976    pCsr->aConstraint = 0;
130977  }
130978}
130979
130980/*
130981** Rtree virtual table module xClose method.
130982*/
130983static int rtreeClose(sqlite3_vtab_cursor *cur){
130984  Rtree *pRtree = (Rtree *)(cur->pVtab);
130985  int rc;
130986  RtreeCursor *pCsr = (RtreeCursor *)cur;
130987  freeCursorConstraints(pCsr);
130988  rc = nodeRelease(pRtree, pCsr->pNode);
130989  sqlite3_free(pCsr);
130990  return rc;
130991}
130992
130993/*
130994** Rtree virtual table module xEof method.
130995**
130996** Return non-zero if the cursor does not currently point to a valid
130997** record (i.e if the scan has finished), or zero otherwise.
130998*/
130999static int rtreeEof(sqlite3_vtab_cursor *cur){
131000  RtreeCursor *pCsr = (RtreeCursor *)cur;
131001  return (pCsr->pNode==0);
131002}
131003
131004/*
131005** The r-tree constraint passed as the second argument to this function is
131006** guaranteed to be a MATCH constraint.
131007*/
131008static int testRtreeGeom(
131009  Rtree *pRtree,                  /* R-Tree object */
131010  RtreeConstraint *pConstraint,   /* MATCH constraint to test */
131011  RtreeCell *pCell,               /* Cell to test */
131012  int *pbRes                      /* OUT: Test result */
131013){
131014  int i;
131015  double aCoord[RTREE_MAX_DIMENSIONS*2];
131016  int nCoord = pRtree->nDim*2;
131017
131018  assert( pConstraint->op==RTREE_MATCH );
131019  assert( pConstraint->pGeom );
131020
131021  for(i=0; i<nCoord; i++){
131022    aCoord[i] = DCOORD(pCell->aCoord[i]);
131023  }
131024  return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
131025}
131026
131027/*
131028** Cursor pCursor currently points to a cell in a non-leaf page.
131029** Set *pbEof to true if the sub-tree headed by the cell is filtered
131030** (excluded) by the constraints in the pCursor->aConstraint[]
131031** array, or false otherwise.
131032**
131033** Return SQLITE_OK if successful or an SQLite error code if an error
131034** occurs within a geometry callback.
131035*/
131036static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
131037  RtreeCell cell;
131038  int ii;
131039  int bRes = 0;
131040  int rc = SQLITE_OK;
131041
131042  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
131043  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
131044    RtreeConstraint *p = &pCursor->aConstraint[ii];
131045    double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
131046    double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
131047
131048    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
131049        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
131050    );
131051
131052    switch( p->op ){
131053      case RTREE_LE: case RTREE_LT:
131054        bRes = p->rValue<cell_min;
131055        break;
131056
131057      case RTREE_GE: case RTREE_GT:
131058        bRes = p->rValue>cell_max;
131059        break;
131060
131061      case RTREE_EQ:
131062        bRes = (p->rValue>cell_max || p->rValue<cell_min);
131063        break;
131064
131065      default: {
131066        assert( p->op==RTREE_MATCH );
131067        rc = testRtreeGeom(pRtree, p, &cell, &bRes);
131068        bRes = !bRes;
131069        break;
131070      }
131071    }
131072  }
131073
131074  *pbEof = bRes;
131075  return rc;
131076}
131077
131078/*
131079** Test if the cell that cursor pCursor currently points to
131080** would be filtered (excluded) by the constraints in the
131081** pCursor->aConstraint[] array. If so, set *pbEof to true before
131082** returning. If the cell is not filtered (excluded) by the constraints,
131083** set pbEof to zero.
131084**
131085** Return SQLITE_OK if successful or an SQLite error code if an error
131086** occurs within a geometry callback.
131087**
131088** This function assumes that the cell is part of a leaf node.
131089*/
131090static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
131091  RtreeCell cell;
131092  int ii;
131093  *pbEof = 0;
131094
131095  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
131096  for(ii=0; ii<pCursor->nConstraint; ii++){
131097    RtreeConstraint *p = &pCursor->aConstraint[ii];
131098    double coord = DCOORD(cell.aCoord[p->iCoord]);
131099    int res;
131100    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
131101        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
131102    );
131103    switch( p->op ){
131104      case RTREE_LE: res = (coord<=p->rValue); break;
131105      case RTREE_LT: res = (coord<p->rValue);  break;
131106      case RTREE_GE: res = (coord>=p->rValue); break;
131107      case RTREE_GT: res = (coord>p->rValue);  break;
131108      case RTREE_EQ: res = (coord==p->rValue); break;
131109      default: {
131110        int rc;
131111        assert( p->op==RTREE_MATCH );
131112        rc = testRtreeGeom(pRtree, p, &cell, &res);
131113        if( rc!=SQLITE_OK ){
131114          return rc;
131115        }
131116        break;
131117      }
131118    }
131119
131120    if( !res ){
131121      *pbEof = 1;
131122      return SQLITE_OK;
131123    }
131124  }
131125
131126  return SQLITE_OK;
131127}
131128
131129/*
131130** Cursor pCursor currently points at a node that heads a sub-tree of
131131** height iHeight (if iHeight==0, then the node is a leaf). Descend
131132** to point to the left-most cell of the sub-tree that matches the
131133** configured constraints.
131134*/
131135static int descendToCell(
131136  Rtree *pRtree,
131137  RtreeCursor *pCursor,
131138  int iHeight,
131139  int *pEof                 /* OUT: Set to true if cannot descend */
131140){
131141  int isEof;
131142  int rc;
131143  int ii;
131144  RtreeNode *pChild;
131145  sqlite3_int64 iRowid;
131146
131147  RtreeNode *pSavedNode = pCursor->pNode;
131148  int iSavedCell = pCursor->iCell;
131149
131150  assert( iHeight>=0 );
131151
131152  if( iHeight==0 ){
131153    rc = testRtreeEntry(pRtree, pCursor, &isEof);
131154  }else{
131155    rc = testRtreeCell(pRtree, pCursor, &isEof);
131156  }
131157  if( rc!=SQLITE_OK || isEof || iHeight==0 ){
131158    goto descend_to_cell_out;
131159  }
131160
131161  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
131162  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
131163  if( rc!=SQLITE_OK ){
131164    goto descend_to_cell_out;
131165  }
131166
131167  nodeRelease(pRtree, pCursor->pNode);
131168  pCursor->pNode = pChild;
131169  isEof = 1;
131170  for(ii=0; isEof && ii<NCELL(pChild); ii++){
131171    pCursor->iCell = ii;
131172    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
131173    if( rc!=SQLITE_OK ){
131174      goto descend_to_cell_out;
131175    }
131176  }
131177
131178  if( isEof ){
131179    assert( pCursor->pNode==pChild );
131180    nodeReference(pSavedNode);
131181    nodeRelease(pRtree, pChild);
131182    pCursor->pNode = pSavedNode;
131183    pCursor->iCell = iSavedCell;
131184  }
131185
131186descend_to_cell_out:
131187  *pEof = isEof;
131188  return rc;
131189}
131190
131191/*
131192** One of the cells in node pNode is guaranteed to have a 64-bit
131193** integer value equal to iRowid. Return the index of this cell.
131194*/
131195static int nodeRowidIndex(
131196  Rtree *pRtree,
131197  RtreeNode *pNode,
131198  i64 iRowid,
131199  int *piIndex
131200){
131201  int ii;
131202  int nCell = NCELL(pNode);
131203  for(ii=0; ii<nCell; ii++){
131204    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
131205      *piIndex = ii;
131206      return SQLITE_OK;
131207    }
131208  }
131209  return SQLITE_CORRUPT_VTAB;
131210}
131211
131212/*
131213** Return the index of the cell containing a pointer to node pNode
131214** in its parent. If pNode is the root node, return -1.
131215*/
131216static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
131217  RtreeNode *pParent = pNode->pParent;
131218  if( pParent ){
131219    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
131220  }
131221  *piIndex = -1;
131222  return SQLITE_OK;
131223}
131224
131225/*
131226** Rtree virtual table module xNext method.
131227*/
131228static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
131229  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
131230  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
131231  int rc = SQLITE_OK;
131232
131233  /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
131234  ** already at EOF. It is against the rules to call the xNext() method of
131235  ** a cursor that has already reached EOF.
131236  */
131237  assert( pCsr->pNode );
131238
131239  if( pCsr->iStrategy==1 ){
131240    /* This "scan" is a direct lookup by rowid. There is no next entry. */
131241    nodeRelease(pRtree, pCsr->pNode);
131242    pCsr->pNode = 0;
131243  }else{
131244    /* Move to the next entry that matches the configured constraints. */
131245    int iHeight = 0;
131246    while( pCsr->pNode ){
131247      RtreeNode *pNode = pCsr->pNode;
131248      int nCell = NCELL(pNode);
131249      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
131250        int isEof;
131251        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
131252        if( rc!=SQLITE_OK || !isEof ){
131253          return rc;
131254        }
131255      }
131256      pCsr->pNode = pNode->pParent;
131257      rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
131258      if( rc!=SQLITE_OK ){
131259        return rc;
131260      }
131261      nodeReference(pCsr->pNode);
131262      nodeRelease(pRtree, pNode);
131263      iHeight++;
131264    }
131265  }
131266
131267  return rc;
131268}
131269
131270/*
131271** Rtree virtual table module xRowid method.
131272*/
131273static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
131274  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
131275  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
131276
131277  assert(pCsr->pNode);
131278  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
131279
131280  return SQLITE_OK;
131281}
131282
131283/*
131284** Rtree virtual table module xColumn method.
131285*/
131286static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
131287  Rtree *pRtree = (Rtree *)cur->pVtab;
131288  RtreeCursor *pCsr = (RtreeCursor *)cur;
131289
131290  if( i==0 ){
131291    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
131292    sqlite3_result_int64(ctx, iRowid);
131293  }else{
131294    RtreeCoord c;
131295    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
131296    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
131297      sqlite3_result_double(ctx, c.f);
131298    }else{
131299      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
131300      sqlite3_result_int(ctx, c.i);
131301    }
131302  }
131303
131304  return SQLITE_OK;
131305}
131306
131307/*
131308** Use nodeAcquire() to obtain the leaf node containing the record with
131309** rowid iRowid. If successful, set *ppLeaf to point to the node and
131310** return SQLITE_OK. If there is no such record in the table, set
131311** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
131312** to zero and return an SQLite error code.
131313*/
131314static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
131315  int rc;
131316  *ppLeaf = 0;
131317  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
131318  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
131319    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
131320    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
131321    sqlite3_reset(pRtree->pReadRowid);
131322  }else{
131323    rc = sqlite3_reset(pRtree->pReadRowid);
131324  }
131325  return rc;
131326}
131327
131328/*
131329** This function is called to configure the RtreeConstraint object passed
131330** as the second argument for a MATCH constraint. The value passed as the
131331** first argument to this function is the right-hand operand to the MATCH
131332** operator.
131333*/
131334static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
131335  RtreeMatchArg *p;
131336  sqlite3_rtree_geometry *pGeom;
131337  int nBlob;
131338
131339  /* Check that value is actually a blob. */
131340  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
131341
131342  /* Check that the blob is roughly the right size. */
131343  nBlob = sqlite3_value_bytes(pValue);
131344  if( nBlob<(int)sizeof(RtreeMatchArg)
131345   || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
131346  ){
131347    return SQLITE_ERROR;
131348  }
131349
131350  pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
131351      sizeof(sqlite3_rtree_geometry) + nBlob
131352  );
131353  if( !pGeom ) return SQLITE_NOMEM;
131354  memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
131355  p = (RtreeMatchArg *)&pGeom[1];
131356
131357  memcpy(p, sqlite3_value_blob(pValue), nBlob);
131358  if( p->magic!=RTREE_GEOMETRY_MAGIC
131359   || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
131360  ){
131361    sqlite3_free(pGeom);
131362    return SQLITE_ERROR;
131363  }
131364
131365  pGeom->pContext = p->pContext;
131366  pGeom->nParam = p->nParam;
131367  pGeom->aParam = p->aParam;
131368
131369  pCons->xGeom = p->xGeom;
131370  pCons->pGeom = pGeom;
131371  return SQLITE_OK;
131372}
131373
131374/*
131375** Rtree virtual table module xFilter method.
131376*/
131377static int rtreeFilter(
131378  sqlite3_vtab_cursor *pVtabCursor,
131379  int idxNum, const char *idxStr,
131380  int argc, sqlite3_value **argv
131381){
131382  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
131383  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
131384
131385  RtreeNode *pRoot = 0;
131386  int ii;
131387  int rc = SQLITE_OK;
131388
131389  rtreeReference(pRtree);
131390
131391  freeCursorConstraints(pCsr);
131392  pCsr->iStrategy = idxNum;
131393
131394  if( idxNum==1 ){
131395    /* Special case - lookup by rowid. */
131396    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
131397    i64 iRowid = sqlite3_value_int64(argv[0]);
131398    rc = findLeafNode(pRtree, iRowid, &pLeaf);
131399    pCsr->pNode = pLeaf;
131400    if( pLeaf ){
131401      assert( rc==SQLITE_OK );
131402      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
131403    }
131404  }else{
131405    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
131406    ** with the configured constraints.
131407    */
131408    if( argc>0 ){
131409      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
131410      pCsr->nConstraint = argc;
131411      if( !pCsr->aConstraint ){
131412        rc = SQLITE_NOMEM;
131413      }else{
131414        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
131415        assert( (idxStr==0 && argc==0)
131416                || (idxStr && (int)strlen(idxStr)==argc*2) );
131417        for(ii=0; ii<argc; ii++){
131418          RtreeConstraint *p = &pCsr->aConstraint[ii];
131419          p->op = idxStr[ii*2];
131420          p->iCoord = idxStr[ii*2+1]-'a';
131421          if( p->op==RTREE_MATCH ){
131422            /* A MATCH operator. The right-hand-side must be a blob that
131423            ** can be cast into an RtreeMatchArg object. One created using
131424            ** an sqlite3_rtree_geometry_callback() SQL user function.
131425            */
131426            rc = deserializeGeometry(argv[ii], p);
131427            if( rc!=SQLITE_OK ){
131428              break;
131429            }
131430          }else{
131431            p->rValue = sqlite3_value_double(argv[ii]);
131432          }
131433        }
131434      }
131435    }
131436
131437    if( rc==SQLITE_OK ){
131438      pCsr->pNode = 0;
131439      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
131440    }
131441    if( rc==SQLITE_OK ){
131442      int isEof = 1;
131443      int nCell = NCELL(pRoot);
131444      pCsr->pNode = pRoot;
131445      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
131446        assert( pCsr->pNode==pRoot );
131447        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
131448        if( !isEof ){
131449          break;
131450        }
131451      }
131452      if( rc==SQLITE_OK && isEof ){
131453        assert( pCsr->pNode==pRoot );
131454        nodeRelease(pRtree, pRoot);
131455        pCsr->pNode = 0;
131456      }
131457      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
131458    }
131459  }
131460
131461  rtreeRelease(pRtree);
131462  return rc;
131463}
131464
131465/*
131466** Rtree virtual table module xBestIndex method. There are three
131467** table scan strategies to choose from (in order from most to
131468** least desirable):
131469**
131470**   idxNum     idxStr        Strategy
131471**   ------------------------------------------------
131472**     1        Unused        Direct lookup by rowid.
131473**     2        See below     R-tree query or full-table scan.
131474**   ------------------------------------------------
131475**
131476** If strategy 1 is used, then idxStr is not meaningful. If strategy
131477** 2 is used, idxStr is formatted to contain 2 bytes for each
131478** constraint used. The first two bytes of idxStr correspond to
131479** the constraint in sqlite3_index_info.aConstraintUsage[] with
131480** (argvIndex==1) etc.
131481**
131482** The first of each pair of bytes in idxStr identifies the constraint
131483** operator as follows:
131484**
131485**   Operator    Byte Value
131486**   ----------------------
131487**      =        0x41 ('A')
131488**     <=        0x42 ('B')
131489**      <        0x43 ('C')
131490**     >=        0x44 ('D')
131491**      >        0x45 ('E')
131492**   MATCH       0x46 ('F')
131493**   ----------------------
131494**
131495** The second of each pair of bytes identifies the coordinate column
131496** to which the constraint applies. The leftmost coordinate column
131497** is 'a', the second from the left 'b' etc.
131498*/
131499static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
131500  int rc = SQLITE_OK;
131501  int ii;
131502
131503  int iIdx = 0;
131504  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
131505  memset(zIdxStr, 0, sizeof(zIdxStr));
131506  UNUSED_PARAMETER(tab);
131507
131508  assert( pIdxInfo->idxStr==0 );
131509  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
131510    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
131511
131512    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
131513      /* We have an equality constraint on the rowid. Use strategy 1. */
131514      int jj;
131515      for(jj=0; jj<ii; jj++){
131516        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
131517        pIdxInfo->aConstraintUsage[jj].omit = 0;
131518      }
131519      pIdxInfo->idxNum = 1;
131520      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
131521      pIdxInfo->aConstraintUsage[jj].omit = 1;
131522
131523      /* This strategy involves a two rowid lookups on an B-Tree structures
131524      ** and then a linear search of an R-Tree node. This should be
131525      ** considered almost as quick as a direct rowid lookup (for which
131526      ** sqlite uses an internal cost of 0.0).
131527      */
131528      pIdxInfo->estimatedCost = 10.0;
131529      return SQLITE_OK;
131530    }
131531
131532    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
131533      u8 op;
131534      switch( p->op ){
131535        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
131536        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
131537        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
131538        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
131539        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
131540        default:
131541          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
131542          op = RTREE_MATCH;
131543          break;
131544      }
131545      zIdxStr[iIdx++] = op;
131546      zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
131547      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
131548      pIdxInfo->aConstraintUsage[ii].omit = 1;
131549    }
131550  }
131551
131552  pIdxInfo->idxNum = 2;
131553  pIdxInfo->needToFreeIdxStr = 1;
131554  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
131555    return SQLITE_NOMEM;
131556  }
131557  assert( iIdx>=0 );
131558  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
131559  return rc;
131560}
131561
131562/*
131563** Return the N-dimensional volumn of the cell stored in *p.
131564*/
131565static float cellArea(Rtree *pRtree, RtreeCell *p){
131566  float area = 1.0;
131567  int ii;
131568  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
131569    area = (float)(area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
131570  }
131571  return area;
131572}
131573
131574/*
131575** Return the margin length of cell p. The margin length is the sum
131576** of the objects size in each dimension.
131577*/
131578static float cellMargin(Rtree *pRtree, RtreeCell *p){
131579  float margin = 0.0;
131580  int ii;
131581  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
131582    margin += (float)(DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
131583  }
131584  return margin;
131585}
131586
131587/*
131588** Store the union of cells p1 and p2 in p1.
131589*/
131590static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
131591  int ii;
131592  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
131593    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
131594      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
131595      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
131596    }
131597  }else{
131598    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
131599      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
131600      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
131601    }
131602  }
131603}
131604
131605/*
131606** Return true if the area covered by p2 is a subset of the area covered
131607** by p1. False otherwise.
131608*/
131609static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
131610  int ii;
131611  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
131612  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
131613    RtreeCoord *a1 = &p1->aCoord[ii];
131614    RtreeCoord *a2 = &p2->aCoord[ii];
131615    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
131616     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
131617    ){
131618      return 0;
131619    }
131620  }
131621  return 1;
131622}
131623
131624/*
131625** Return the amount cell p would grow by if it were unioned with pCell.
131626*/
131627static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
131628  float area;
131629  RtreeCell cell;
131630  memcpy(&cell, p, sizeof(RtreeCell));
131631  area = cellArea(pRtree, &cell);
131632  cellUnion(pRtree, &cell, pCell);
131633  return (cellArea(pRtree, &cell)-area);
131634}
131635
131636#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
131637static float cellOverlap(
131638  Rtree *pRtree,
131639  RtreeCell *p,
131640  RtreeCell *aCell,
131641  int nCell,
131642  int iExclude
131643){
131644  int ii;
131645  float overlap = 0.0;
131646  for(ii=0; ii<nCell; ii++){
131647#if VARIANT_RSTARTREE_CHOOSESUBTREE
131648    if( ii!=iExclude )
131649#else
131650    assert( iExclude==-1 );
131651    UNUSED_PARAMETER(iExclude);
131652#endif
131653    {
131654      int jj;
131655      float o = 1.0;
131656      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
131657        double x1;
131658        double x2;
131659
131660        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
131661        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
131662
131663        if( x2<x1 ){
131664          o = 0.0;
131665          break;
131666        }else{
131667          o = o * (float)(x2-x1);
131668        }
131669      }
131670      overlap += o;
131671    }
131672  }
131673  return overlap;
131674}
131675#endif
131676
131677#if VARIANT_RSTARTREE_CHOOSESUBTREE
131678static float cellOverlapEnlargement(
131679  Rtree *pRtree,
131680  RtreeCell *p,
131681  RtreeCell *pInsert,
131682  RtreeCell *aCell,
131683  int nCell,
131684  int iExclude
131685){
131686  double before;
131687  double after;
131688  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
131689  cellUnion(pRtree, p, pInsert);
131690  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
131691  return (float)(after-before);
131692}
131693#endif
131694
131695
131696/*
131697** This function implements the ChooseLeaf algorithm from Gutman[84].
131698** ChooseSubTree in r*tree terminology.
131699*/
131700static int ChooseLeaf(
131701  Rtree *pRtree,               /* Rtree table */
131702  RtreeCell *pCell,            /* Cell to insert into rtree */
131703  int iHeight,                 /* Height of sub-tree rooted at pCell */
131704  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
131705){
131706  int rc;
131707  int ii;
131708  RtreeNode *pNode;
131709  rc = nodeAcquire(pRtree, 1, 0, &pNode);
131710
131711  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
131712    int iCell;
131713    sqlite3_int64 iBest = 0;
131714
131715    float fMinGrowth = 0.0;
131716    float fMinArea = 0.0;
131717#if VARIANT_RSTARTREE_CHOOSESUBTREE
131718    float fMinOverlap = 0.0;
131719    float overlap;
131720#endif
131721
131722    int nCell = NCELL(pNode);
131723    RtreeCell cell;
131724    RtreeNode *pChild;
131725
131726    RtreeCell *aCell = 0;
131727
131728#if VARIANT_RSTARTREE_CHOOSESUBTREE
131729    if( ii==(pRtree->iDepth-1) ){
131730      int jj;
131731      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
131732      if( !aCell ){
131733        rc = SQLITE_NOMEM;
131734        nodeRelease(pRtree, pNode);
131735        pNode = 0;
131736        continue;
131737      }
131738      for(jj=0; jj<nCell; jj++){
131739        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
131740      }
131741    }
131742#endif
131743
131744    /* Select the child node which will be enlarged the least if pCell
131745    ** is inserted into it. Resolve ties by choosing the entry with
131746    ** the smallest area.
131747    */
131748    for(iCell=0; iCell<nCell; iCell++){
131749      int bBest = 0;
131750      float growth;
131751      float area;
131752      nodeGetCell(pRtree, pNode, iCell, &cell);
131753      growth = cellGrowth(pRtree, &cell, pCell);
131754      area = cellArea(pRtree, &cell);
131755
131756#if VARIANT_RSTARTREE_CHOOSESUBTREE
131757      if( ii==(pRtree->iDepth-1) ){
131758        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
131759      }else{
131760        overlap = 0.0;
131761      }
131762      if( (iCell==0)
131763       || (overlap<fMinOverlap)
131764       || (overlap==fMinOverlap && growth<fMinGrowth)
131765       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
131766      ){
131767        bBest = 1;
131768        fMinOverlap = overlap;
131769      }
131770#else
131771      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
131772        bBest = 1;
131773      }
131774#endif
131775      if( bBest ){
131776        fMinGrowth = growth;
131777        fMinArea = area;
131778        iBest = cell.iRowid;
131779      }
131780    }
131781
131782    sqlite3_free(aCell);
131783    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
131784    nodeRelease(pRtree, pNode);
131785    pNode = pChild;
131786  }
131787
131788  *ppLeaf = pNode;
131789  return rc;
131790}
131791
131792/*
131793** A cell with the same content as pCell has just been inserted into
131794** the node pNode. This function updates the bounding box cells in
131795** all ancestor elements.
131796*/
131797static int AdjustTree(
131798  Rtree *pRtree,                    /* Rtree table */
131799  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
131800  RtreeCell *pCell                  /* This cell was just inserted */
131801){
131802  RtreeNode *p = pNode;
131803  while( p->pParent ){
131804    RtreeNode *pParent = p->pParent;
131805    RtreeCell cell;
131806    int iCell;
131807
131808    if( nodeParentIndex(pRtree, p, &iCell) ){
131809      return SQLITE_CORRUPT_VTAB;
131810    }
131811
131812    nodeGetCell(pRtree, pParent, iCell, &cell);
131813    if( !cellContains(pRtree, &cell, pCell) ){
131814      cellUnion(pRtree, &cell, pCell);
131815      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
131816    }
131817
131818    p = pParent;
131819  }
131820  return SQLITE_OK;
131821}
131822
131823/*
131824** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
131825*/
131826static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
131827  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
131828  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
131829  sqlite3_step(pRtree->pWriteRowid);
131830  return sqlite3_reset(pRtree->pWriteRowid);
131831}
131832
131833/*
131834** Write mapping (iNode->iPar) to the <rtree>_parent table.
131835*/
131836static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
131837  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
131838  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
131839  sqlite3_step(pRtree->pWriteParent);
131840  return sqlite3_reset(pRtree->pWriteParent);
131841}
131842
131843static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
131844
131845#if VARIANT_GUTTMAN_LINEAR_SPLIT
131846/*
131847** Implementation of the linear variant of the PickNext() function from
131848** Guttman[84].
131849*/
131850static RtreeCell *LinearPickNext(
131851  Rtree *pRtree,
131852  RtreeCell *aCell,
131853  int nCell,
131854  RtreeCell *pLeftBox,
131855  RtreeCell *pRightBox,
131856  int *aiUsed
131857){
131858  int ii;
131859  for(ii=0; aiUsed[ii]; ii++);
131860  aiUsed[ii] = 1;
131861  return &aCell[ii];
131862}
131863
131864/*
131865** Implementation of the linear variant of the PickSeeds() function from
131866** Guttman[84].
131867*/
131868static void LinearPickSeeds(
131869  Rtree *pRtree,
131870  RtreeCell *aCell,
131871  int nCell,
131872  int *piLeftSeed,
131873  int *piRightSeed
131874){
131875  int i;
131876  int iLeftSeed = 0;
131877  int iRightSeed = 1;
131878  float maxNormalInnerWidth = 0.0;
131879
131880  /* Pick two "seed" cells from the array of cells. The algorithm used
131881  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
131882  ** indices of the two seed cells in the array are stored in local
131883  ** variables iLeftSeek and iRightSeed.
131884  */
131885  for(i=0; i<pRtree->nDim; i++){
131886    float x1 = DCOORD(aCell[0].aCoord[i*2]);
131887    float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
131888    float x3 = x1;
131889    float x4 = x2;
131890    int jj;
131891
131892    int iCellLeft = 0;
131893    int iCellRight = 0;
131894
131895    for(jj=1; jj<nCell; jj++){
131896      float left = DCOORD(aCell[jj].aCoord[i*2]);
131897      float right = DCOORD(aCell[jj].aCoord[i*2+1]);
131898
131899      if( left<x1 ) x1 = left;
131900      if( right>x4 ) x4 = right;
131901      if( left>x3 ){
131902        x3 = left;
131903        iCellRight = jj;
131904      }
131905      if( right<x2 ){
131906        x2 = right;
131907        iCellLeft = jj;
131908      }
131909    }
131910
131911    if( x4!=x1 ){
131912      float normalwidth = (x3 - x2) / (x4 - x1);
131913      if( normalwidth>maxNormalInnerWidth ){
131914        iLeftSeed = iCellLeft;
131915        iRightSeed = iCellRight;
131916      }
131917    }
131918  }
131919
131920  *piLeftSeed = iLeftSeed;
131921  *piRightSeed = iRightSeed;
131922}
131923#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
131924
131925#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
131926/*
131927** Implementation of the quadratic variant of the PickNext() function from
131928** Guttman[84].
131929*/
131930static RtreeCell *QuadraticPickNext(
131931  Rtree *pRtree,
131932  RtreeCell *aCell,
131933  int nCell,
131934  RtreeCell *pLeftBox,
131935  RtreeCell *pRightBox,
131936  int *aiUsed
131937){
131938  #define FABS(a) ((a)<0.0?-1.0*(a):(a))
131939
131940  int iSelect = -1;
131941  float fDiff;
131942  int ii;
131943  for(ii=0; ii<nCell; ii++){
131944    if( aiUsed[ii]==0 ){
131945      float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
131946      float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
131947      float diff = FABS(right-left);
131948      if( iSelect<0 || diff>fDiff ){
131949        fDiff = diff;
131950        iSelect = ii;
131951      }
131952    }
131953  }
131954  aiUsed[iSelect] = 1;
131955  return &aCell[iSelect];
131956}
131957
131958/*
131959** Implementation of the quadratic variant of the PickSeeds() function from
131960** Guttman[84].
131961*/
131962static void QuadraticPickSeeds(
131963  Rtree *pRtree,
131964  RtreeCell *aCell,
131965  int nCell,
131966  int *piLeftSeed,
131967  int *piRightSeed
131968){
131969  int ii;
131970  int jj;
131971
131972  int iLeftSeed = 0;
131973  int iRightSeed = 1;
131974  float fWaste = 0.0;
131975
131976  for(ii=0; ii<nCell; ii++){
131977    for(jj=ii+1; jj<nCell; jj++){
131978      float right = cellArea(pRtree, &aCell[jj]);
131979      float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
131980      float waste = growth - right;
131981
131982      if( waste>fWaste ){
131983        iLeftSeed = ii;
131984        iRightSeed = jj;
131985        fWaste = waste;
131986      }
131987    }
131988  }
131989
131990  *piLeftSeed = iLeftSeed;
131991  *piRightSeed = iRightSeed;
131992}
131993#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
131994
131995/*
131996** Arguments aIdx, aDistance and aSpare all point to arrays of size
131997** nIdx. The aIdx array contains the set of integers from 0 to
131998** (nIdx-1) in no particular order. This function sorts the values
131999** in aIdx according to the indexed values in aDistance. For
132000** example, assuming the inputs:
132001**
132002**   aIdx      = { 0,   1,   2,   3 }
132003**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
132004**
132005** this function sets the aIdx array to contain:
132006**
132007**   aIdx      = { 0,   1,   2,   3 }
132008**
132009** The aSpare array is used as temporary working space by the
132010** sorting algorithm.
132011*/
132012static void SortByDistance(
132013  int *aIdx,
132014  int nIdx,
132015  float *aDistance,
132016  int *aSpare
132017){
132018  if( nIdx>1 ){
132019    int iLeft = 0;
132020    int iRight = 0;
132021
132022    int nLeft = nIdx/2;
132023    int nRight = nIdx-nLeft;
132024    int *aLeft = aIdx;
132025    int *aRight = &aIdx[nLeft];
132026
132027    SortByDistance(aLeft, nLeft, aDistance, aSpare);
132028    SortByDistance(aRight, nRight, aDistance, aSpare);
132029
132030    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
132031    aLeft = aSpare;
132032
132033    while( iLeft<nLeft || iRight<nRight ){
132034      if( iLeft==nLeft ){
132035        aIdx[iLeft+iRight] = aRight[iRight];
132036        iRight++;
132037      }else if( iRight==nRight ){
132038        aIdx[iLeft+iRight] = aLeft[iLeft];
132039        iLeft++;
132040      }else{
132041        float fLeft = aDistance[aLeft[iLeft]];
132042        float fRight = aDistance[aRight[iRight]];
132043        if( fLeft<fRight ){
132044          aIdx[iLeft+iRight] = aLeft[iLeft];
132045          iLeft++;
132046        }else{
132047          aIdx[iLeft+iRight] = aRight[iRight];
132048          iRight++;
132049        }
132050      }
132051    }
132052
132053#if 0
132054    /* Check that the sort worked */
132055    {
132056      int jj;
132057      for(jj=1; jj<nIdx; jj++){
132058        float left = aDistance[aIdx[jj-1]];
132059        float right = aDistance[aIdx[jj]];
132060        assert( left<=right );
132061      }
132062    }
132063#endif
132064  }
132065}
132066
132067/*
132068** Arguments aIdx, aCell and aSpare all point to arrays of size
132069** nIdx. The aIdx array contains the set of integers from 0 to
132070** (nIdx-1) in no particular order. This function sorts the values
132071** in aIdx according to dimension iDim of the cells in aCell. The
132072** minimum value of dimension iDim is considered first, the
132073** maximum used to break ties.
132074**
132075** The aSpare array is used as temporary working space by the
132076** sorting algorithm.
132077*/
132078static void SortByDimension(
132079  Rtree *pRtree,
132080  int *aIdx,
132081  int nIdx,
132082  int iDim,
132083  RtreeCell *aCell,
132084  int *aSpare
132085){
132086  if( nIdx>1 ){
132087
132088    int iLeft = 0;
132089    int iRight = 0;
132090
132091    int nLeft = nIdx/2;
132092    int nRight = nIdx-nLeft;
132093    int *aLeft = aIdx;
132094    int *aRight = &aIdx[nLeft];
132095
132096    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
132097    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
132098
132099    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
132100    aLeft = aSpare;
132101    while( iLeft<nLeft || iRight<nRight ){
132102      double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
132103      double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
132104      double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
132105      double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
132106      if( (iLeft!=nLeft) && ((iRight==nRight)
132107       || (xleft1<xright1)
132108       || (xleft1==xright1 && xleft2<xright2)
132109      )){
132110        aIdx[iLeft+iRight] = aLeft[iLeft];
132111        iLeft++;
132112      }else{
132113        aIdx[iLeft+iRight] = aRight[iRight];
132114        iRight++;
132115      }
132116    }
132117
132118#if 0
132119    /* Check that the sort worked */
132120    {
132121      int jj;
132122      for(jj=1; jj<nIdx; jj++){
132123        float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
132124        float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
132125        float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
132126        float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
132127        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
132128      }
132129    }
132130#endif
132131  }
132132}
132133
132134#if VARIANT_RSTARTREE_SPLIT
132135/*
132136** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
132137*/
132138static int splitNodeStartree(
132139  Rtree *pRtree,
132140  RtreeCell *aCell,
132141  int nCell,
132142  RtreeNode *pLeft,
132143  RtreeNode *pRight,
132144  RtreeCell *pBboxLeft,
132145  RtreeCell *pBboxRight
132146){
132147  int **aaSorted;
132148  int *aSpare;
132149  int ii;
132150
132151  int iBestDim = 0;
132152  int iBestSplit = 0;
132153  float fBestMargin = 0.0;
132154
132155  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
132156
132157  aaSorted = (int **)sqlite3_malloc(nByte);
132158  if( !aaSorted ){
132159    return SQLITE_NOMEM;
132160  }
132161
132162  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
132163  memset(aaSorted, 0, nByte);
132164  for(ii=0; ii<pRtree->nDim; ii++){
132165    int jj;
132166    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
132167    for(jj=0; jj<nCell; jj++){
132168      aaSorted[ii][jj] = jj;
132169    }
132170    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
132171  }
132172
132173  for(ii=0; ii<pRtree->nDim; ii++){
132174    float margin = 0.0;
132175    float fBestOverlap = 0.0;
132176    float fBestArea = 0.0;
132177    int iBestLeft = 0;
132178    int nLeft;
132179
132180    for(
132181      nLeft=RTREE_MINCELLS(pRtree);
132182      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
132183      nLeft++
132184    ){
132185      RtreeCell left;
132186      RtreeCell right;
132187      int kk;
132188      float overlap;
132189      float area;
132190
132191      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
132192      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
132193      for(kk=1; kk<(nCell-1); kk++){
132194        if( kk<nLeft ){
132195          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
132196        }else{
132197          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
132198        }
132199      }
132200      margin += cellMargin(pRtree, &left);
132201      margin += cellMargin(pRtree, &right);
132202      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
132203      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
132204      if( (nLeft==RTREE_MINCELLS(pRtree))
132205       || (overlap<fBestOverlap)
132206       || (overlap==fBestOverlap && area<fBestArea)
132207      ){
132208        iBestLeft = nLeft;
132209        fBestOverlap = overlap;
132210        fBestArea = area;
132211      }
132212    }
132213
132214    if( ii==0 || margin<fBestMargin ){
132215      iBestDim = ii;
132216      fBestMargin = margin;
132217      iBestSplit = iBestLeft;
132218    }
132219  }
132220
132221  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
132222  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
132223  for(ii=0; ii<nCell; ii++){
132224    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
132225    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
132226    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
132227    nodeInsertCell(pRtree, pTarget, pCell);
132228    cellUnion(pRtree, pBbox, pCell);
132229  }
132230
132231  sqlite3_free(aaSorted);
132232  return SQLITE_OK;
132233}
132234#endif
132235
132236#if VARIANT_GUTTMAN_SPLIT
132237/*
132238** Implementation of the regular R-tree SplitNode from Guttman[1984].
132239*/
132240static int splitNodeGuttman(
132241  Rtree *pRtree,
132242  RtreeCell *aCell,
132243  int nCell,
132244  RtreeNode *pLeft,
132245  RtreeNode *pRight,
132246  RtreeCell *pBboxLeft,
132247  RtreeCell *pBboxRight
132248){
132249  int iLeftSeed = 0;
132250  int iRightSeed = 1;
132251  int *aiUsed;
132252  int i;
132253
132254  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
132255  if( !aiUsed ){
132256    return SQLITE_NOMEM;
132257  }
132258  memset(aiUsed, 0, sizeof(int)*nCell);
132259
132260  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
132261
132262  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
132263  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
132264  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
132265  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
132266  aiUsed[iLeftSeed] = 1;
132267  aiUsed[iRightSeed] = 1;
132268
132269  for(i=nCell-2; i>0; i--){
132270    RtreeCell *pNext;
132271    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
132272    float diff =
132273      cellGrowth(pRtree, pBboxLeft, pNext) -
132274      cellGrowth(pRtree, pBboxRight, pNext)
132275    ;
132276    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
132277     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
132278    ){
132279      nodeInsertCell(pRtree, pRight, pNext);
132280      cellUnion(pRtree, pBboxRight, pNext);
132281    }else{
132282      nodeInsertCell(pRtree, pLeft, pNext);
132283      cellUnion(pRtree, pBboxLeft, pNext);
132284    }
132285  }
132286
132287  sqlite3_free(aiUsed);
132288  return SQLITE_OK;
132289}
132290#endif
132291
132292static int updateMapping(
132293  Rtree *pRtree,
132294  i64 iRowid,
132295  RtreeNode *pNode,
132296  int iHeight
132297){
132298  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
132299  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
132300  if( iHeight>0 ){
132301    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
132302    if( pChild ){
132303      nodeRelease(pRtree, pChild->pParent);
132304      nodeReference(pNode);
132305      pChild->pParent = pNode;
132306    }
132307  }
132308  return xSetMapping(pRtree, iRowid, pNode->iNode);
132309}
132310
132311static int SplitNode(
132312  Rtree *pRtree,
132313  RtreeNode *pNode,
132314  RtreeCell *pCell,
132315  int iHeight
132316){
132317  int i;
132318  int newCellIsRight = 0;
132319
132320  int rc = SQLITE_OK;
132321  int nCell = NCELL(pNode);
132322  RtreeCell *aCell;
132323  int *aiUsed;
132324
132325  RtreeNode *pLeft = 0;
132326  RtreeNode *pRight = 0;
132327
132328  RtreeCell leftbbox;
132329  RtreeCell rightbbox;
132330
132331  /* Allocate an array and populate it with a copy of pCell and
132332  ** all cells from node pLeft. Then zero the original node.
132333  */
132334  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
132335  if( !aCell ){
132336    rc = SQLITE_NOMEM;
132337    goto splitnode_out;
132338  }
132339  aiUsed = (int *)&aCell[nCell+1];
132340  memset(aiUsed, 0, sizeof(int)*(nCell+1));
132341  for(i=0; i<nCell; i++){
132342    nodeGetCell(pRtree, pNode, i, &aCell[i]);
132343  }
132344  nodeZero(pRtree, pNode);
132345  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
132346  nCell++;
132347
132348  if( pNode->iNode==1 ){
132349    pRight = nodeNew(pRtree, pNode);
132350    pLeft = nodeNew(pRtree, pNode);
132351    pRtree->iDepth++;
132352    pNode->isDirty = 1;
132353    writeInt16(pNode->zData, pRtree->iDepth);
132354  }else{
132355    pLeft = pNode;
132356    pRight = nodeNew(pRtree, pLeft->pParent);
132357    nodeReference(pLeft);
132358  }
132359
132360  if( !pLeft || !pRight ){
132361    rc = SQLITE_NOMEM;
132362    goto splitnode_out;
132363  }
132364
132365  memset(pLeft->zData, 0, pRtree->iNodeSize);
132366  memset(pRight->zData, 0, pRtree->iNodeSize);
132367
132368  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
132369  if( rc!=SQLITE_OK ){
132370    goto splitnode_out;
132371  }
132372
132373  /* Ensure both child nodes have node numbers assigned to them by calling
132374  ** nodeWrite(). Node pRight always needs a node number, as it was created
132375  ** by nodeNew() above. But node pLeft sometimes already has a node number.
132376  ** In this case avoid the all to nodeWrite().
132377  */
132378  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
132379   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
132380  ){
132381    goto splitnode_out;
132382  }
132383
132384  rightbbox.iRowid = pRight->iNode;
132385  leftbbox.iRowid = pLeft->iNode;
132386
132387  if( pNode->iNode==1 ){
132388    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
132389    if( rc!=SQLITE_OK ){
132390      goto splitnode_out;
132391    }
132392  }else{
132393    RtreeNode *pParent = pLeft->pParent;
132394    int iCell;
132395    rc = nodeParentIndex(pRtree, pLeft, &iCell);
132396    if( rc==SQLITE_OK ){
132397      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
132398      rc = AdjustTree(pRtree, pParent, &leftbbox);
132399    }
132400    if( rc!=SQLITE_OK ){
132401      goto splitnode_out;
132402    }
132403  }
132404  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
132405    goto splitnode_out;
132406  }
132407
132408  for(i=0; i<NCELL(pRight); i++){
132409    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
132410    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
132411    if( iRowid==pCell->iRowid ){
132412      newCellIsRight = 1;
132413    }
132414    if( rc!=SQLITE_OK ){
132415      goto splitnode_out;
132416    }
132417  }
132418  if( pNode->iNode==1 ){
132419    for(i=0; i<NCELL(pLeft); i++){
132420      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
132421      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
132422      if( rc!=SQLITE_OK ){
132423        goto splitnode_out;
132424      }
132425    }
132426  }else if( newCellIsRight==0 ){
132427    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
132428  }
132429
132430  if( rc==SQLITE_OK ){
132431    rc = nodeRelease(pRtree, pRight);
132432    pRight = 0;
132433  }
132434  if( rc==SQLITE_OK ){
132435    rc = nodeRelease(pRtree, pLeft);
132436    pLeft = 0;
132437  }
132438
132439splitnode_out:
132440  nodeRelease(pRtree, pRight);
132441  nodeRelease(pRtree, pLeft);
132442  sqlite3_free(aCell);
132443  return rc;
132444}
132445
132446/*
132447** If node pLeaf is not the root of the r-tree and its pParent pointer is
132448** still NULL, load all ancestor nodes of pLeaf into memory and populate
132449** the pLeaf->pParent chain all the way up to the root node.
132450**
132451** This operation is required when a row is deleted (or updated - an update
132452** is implemented as a delete followed by an insert). SQLite provides the
132453** rowid of the row to delete, which can be used to find the leaf on which
132454** the entry resides (argument pLeaf). Once the leaf is located, this
132455** function is called to determine its ancestry.
132456*/
132457static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
132458  int rc = SQLITE_OK;
132459  RtreeNode *pChild = pLeaf;
132460  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
132461    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
132462    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
132463    rc = sqlite3_step(pRtree->pReadParent);
132464    if( rc==SQLITE_ROW ){
132465      RtreeNode *pTest;           /* Used to test for reference loops */
132466      i64 iNode;                  /* Node number of parent node */
132467
132468      /* Before setting pChild->pParent, test that we are not creating a
132469      ** loop of references (as we would if, say, pChild==pParent). We don't
132470      ** want to do this as it leads to a memory leak when trying to delete
132471      ** the referenced counted node structures.
132472      */
132473      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
132474      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
132475      if( !pTest ){
132476        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
132477      }
132478    }
132479    rc = sqlite3_reset(pRtree->pReadParent);
132480    if( rc==SQLITE_OK ) rc = rc2;
132481    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
132482    pChild = pChild->pParent;
132483  }
132484  return rc;
132485}
132486
132487static int deleteCell(Rtree *, RtreeNode *, int, int);
132488
132489static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
132490  int rc;
132491  int rc2;
132492  RtreeNode *pParent = 0;
132493  int iCell;
132494
132495  assert( pNode->nRef==1 );
132496
132497  /* Remove the entry in the parent cell. */
132498  rc = nodeParentIndex(pRtree, pNode, &iCell);
132499  if( rc==SQLITE_OK ){
132500    pParent = pNode->pParent;
132501    pNode->pParent = 0;
132502    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
132503  }
132504  rc2 = nodeRelease(pRtree, pParent);
132505  if( rc==SQLITE_OK ){
132506    rc = rc2;
132507  }
132508  if( rc!=SQLITE_OK ){
132509    return rc;
132510  }
132511
132512  /* Remove the xxx_node entry. */
132513  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
132514  sqlite3_step(pRtree->pDeleteNode);
132515  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
132516    return rc;
132517  }
132518
132519  /* Remove the xxx_parent entry. */
132520  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
132521  sqlite3_step(pRtree->pDeleteParent);
132522  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
132523    return rc;
132524  }
132525
132526  /* Remove the node from the in-memory hash table and link it into
132527  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
132528  */
132529  nodeHashDelete(pRtree, pNode);
132530  pNode->iNode = iHeight;
132531  pNode->pNext = pRtree->pDeleted;
132532  pNode->nRef++;
132533  pRtree->pDeleted = pNode;
132534
132535  return SQLITE_OK;
132536}
132537
132538static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
132539  RtreeNode *pParent = pNode->pParent;
132540  int rc = SQLITE_OK;
132541  if( pParent ){
132542    int ii;
132543    int nCell = NCELL(pNode);
132544    RtreeCell box;                            /* Bounding box for pNode */
132545    nodeGetCell(pRtree, pNode, 0, &box);
132546    for(ii=1; ii<nCell; ii++){
132547      RtreeCell cell;
132548      nodeGetCell(pRtree, pNode, ii, &cell);
132549      cellUnion(pRtree, &box, &cell);
132550    }
132551    box.iRowid = pNode->iNode;
132552    rc = nodeParentIndex(pRtree, pNode, &ii);
132553    if( rc==SQLITE_OK ){
132554      nodeOverwriteCell(pRtree, pParent, &box, ii);
132555      rc = fixBoundingBox(pRtree, pParent);
132556    }
132557  }
132558  return rc;
132559}
132560
132561/*
132562** Delete the cell at index iCell of node pNode. After removing the
132563** cell, adjust the r-tree data structure if required.
132564*/
132565static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
132566  RtreeNode *pParent;
132567  int rc;
132568
132569  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
132570    return rc;
132571  }
132572
132573  /* Remove the cell from the node. This call just moves bytes around
132574  ** the in-memory node image, so it cannot fail.
132575  */
132576  nodeDeleteCell(pRtree, pNode, iCell);
132577
132578  /* If the node is not the tree root and now has less than the minimum
132579  ** number of cells, remove it from the tree. Otherwise, update the
132580  ** cell in the parent node so that it tightly contains the updated
132581  ** node.
132582  */
132583  pParent = pNode->pParent;
132584  assert( pParent || pNode->iNode==1 );
132585  if( pParent ){
132586    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
132587      rc = removeNode(pRtree, pNode, iHeight);
132588    }else{
132589      rc = fixBoundingBox(pRtree, pNode);
132590    }
132591  }
132592
132593  return rc;
132594}
132595
132596static int Reinsert(
132597  Rtree *pRtree,
132598  RtreeNode *pNode,
132599  RtreeCell *pCell,
132600  int iHeight
132601){
132602  int *aOrder;
132603  int *aSpare;
132604  RtreeCell *aCell;
132605  float *aDistance;
132606  int nCell;
132607  float aCenterCoord[RTREE_MAX_DIMENSIONS];
132608  int iDim;
132609  int ii;
132610  int rc = SQLITE_OK;
132611
132612  memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
132613
132614  nCell = NCELL(pNode)+1;
132615
132616  /* Allocate the buffers used by this operation. The allocation is
132617  ** relinquished before this function returns.
132618  */
132619  aCell = (RtreeCell *)sqlite3_malloc(nCell * (
132620    sizeof(RtreeCell) +         /* aCell array */
132621    sizeof(int)       +         /* aOrder array */
132622    sizeof(int)       +         /* aSpare array */
132623    sizeof(float)               /* aDistance array */
132624  ));
132625  if( !aCell ){
132626    return SQLITE_NOMEM;
132627  }
132628  aOrder    = (int *)&aCell[nCell];
132629  aSpare    = (int *)&aOrder[nCell];
132630  aDistance = (float *)&aSpare[nCell];
132631
132632  for(ii=0; ii<nCell; ii++){
132633    if( ii==(nCell-1) ){
132634      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
132635    }else{
132636      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
132637    }
132638    aOrder[ii] = ii;
132639    for(iDim=0; iDim<pRtree->nDim; iDim++){
132640      aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2]);
132641      aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2+1]);
132642    }
132643  }
132644  for(iDim=0; iDim<pRtree->nDim; iDim++){
132645    aCenterCoord[iDim] = (float)(aCenterCoord[iDim]/((float)nCell*2.0));
132646  }
132647
132648  for(ii=0; ii<nCell; ii++){
132649    aDistance[ii] = 0.0;
132650    for(iDim=0; iDim<pRtree->nDim; iDim++){
132651      float coord = (float)(DCOORD(aCell[ii].aCoord[iDim*2+1]) -
132652          DCOORD(aCell[ii].aCoord[iDim*2]));
132653      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
132654    }
132655  }
132656
132657  SortByDistance(aOrder, nCell, aDistance, aSpare);
132658  nodeZero(pRtree, pNode);
132659
132660  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
132661    RtreeCell *p = &aCell[aOrder[ii]];
132662    nodeInsertCell(pRtree, pNode, p);
132663    if( p->iRowid==pCell->iRowid ){
132664      if( iHeight==0 ){
132665        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
132666      }else{
132667        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
132668      }
132669    }
132670  }
132671  if( rc==SQLITE_OK ){
132672    rc = fixBoundingBox(pRtree, pNode);
132673  }
132674  for(; rc==SQLITE_OK && ii<nCell; ii++){
132675    /* Find a node to store this cell in. pNode->iNode currently contains
132676    ** the height of the sub-tree headed by the cell.
132677    */
132678    RtreeNode *pInsert;
132679    RtreeCell *p = &aCell[aOrder[ii]];
132680    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
132681    if( rc==SQLITE_OK ){
132682      int rc2;
132683      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
132684      rc2 = nodeRelease(pRtree, pInsert);
132685      if( rc==SQLITE_OK ){
132686        rc = rc2;
132687      }
132688    }
132689  }
132690
132691  sqlite3_free(aCell);
132692  return rc;
132693}
132694
132695/*
132696** Insert cell pCell into node pNode. Node pNode is the head of a
132697** subtree iHeight high (leaf nodes have iHeight==0).
132698*/
132699static int rtreeInsertCell(
132700  Rtree *pRtree,
132701  RtreeNode *pNode,
132702  RtreeCell *pCell,
132703  int iHeight
132704){
132705  int rc = SQLITE_OK;
132706  if( iHeight>0 ){
132707    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
132708    if( pChild ){
132709      nodeRelease(pRtree, pChild->pParent);
132710      nodeReference(pNode);
132711      pChild->pParent = pNode;
132712    }
132713  }
132714  if( nodeInsertCell(pRtree, pNode, pCell) ){
132715#if VARIANT_RSTARTREE_REINSERT
132716    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
132717      rc = SplitNode(pRtree, pNode, pCell, iHeight);
132718    }else{
132719      pRtree->iReinsertHeight = iHeight;
132720      rc = Reinsert(pRtree, pNode, pCell, iHeight);
132721    }
132722#else
132723    rc = SplitNode(pRtree, pNode, pCell, iHeight);
132724#endif
132725  }else{
132726    rc = AdjustTree(pRtree, pNode, pCell);
132727    if( rc==SQLITE_OK ){
132728      if( iHeight==0 ){
132729        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
132730      }else{
132731        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
132732      }
132733    }
132734  }
132735  return rc;
132736}
132737
132738static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
132739  int ii;
132740  int rc = SQLITE_OK;
132741  int nCell = NCELL(pNode);
132742
132743  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
132744    RtreeNode *pInsert;
132745    RtreeCell cell;
132746    nodeGetCell(pRtree, pNode, ii, &cell);
132747
132748    /* Find a node to store this cell in. pNode->iNode currently contains
132749    ** the height of the sub-tree headed by the cell.
132750    */
132751    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
132752    if( rc==SQLITE_OK ){
132753      int rc2;
132754      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
132755      rc2 = nodeRelease(pRtree, pInsert);
132756      if( rc==SQLITE_OK ){
132757        rc = rc2;
132758      }
132759    }
132760  }
132761  return rc;
132762}
132763
132764/*
132765** Select a currently unused rowid for a new r-tree record.
132766*/
132767static int newRowid(Rtree *pRtree, i64 *piRowid){
132768  int rc;
132769  sqlite3_bind_null(pRtree->pWriteRowid, 1);
132770  sqlite3_bind_null(pRtree->pWriteRowid, 2);
132771  sqlite3_step(pRtree->pWriteRowid);
132772  rc = sqlite3_reset(pRtree->pWriteRowid);
132773  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
132774  return rc;
132775}
132776
132777/*
132778** Remove the entry with rowid=iDelete from the r-tree structure.
132779*/
132780static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
132781  int rc;                         /* Return code */
132782  RtreeNode *pLeaf;               /* Leaf node containing record iDelete */
132783  int iCell;                      /* Index of iDelete cell in pLeaf */
132784  RtreeNode *pRoot;               /* Root node of rtree structure */
132785
132786
132787  /* Obtain a reference to the root node to initialise Rtree.iDepth */
132788  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
132789
132790  /* Obtain a reference to the leaf node that contains the entry
132791  ** about to be deleted.
132792  */
132793  if( rc==SQLITE_OK ){
132794    rc = findLeafNode(pRtree, iDelete, &pLeaf);
132795  }
132796
132797  /* Delete the cell in question from the leaf node. */
132798  if( rc==SQLITE_OK ){
132799    int rc2;
132800    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
132801    if( rc==SQLITE_OK ){
132802      rc = deleteCell(pRtree, pLeaf, iCell, 0);
132803    }
132804    rc2 = nodeRelease(pRtree, pLeaf);
132805    if( rc==SQLITE_OK ){
132806      rc = rc2;
132807    }
132808  }
132809
132810  /* Delete the corresponding entry in the <rtree>_rowid table. */
132811  if( rc==SQLITE_OK ){
132812    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
132813    sqlite3_step(pRtree->pDeleteRowid);
132814    rc = sqlite3_reset(pRtree->pDeleteRowid);
132815  }
132816
132817  /* Check if the root node now has exactly one child. If so, remove
132818  ** it, schedule the contents of the child for reinsertion and
132819  ** reduce the tree height by one.
132820  **
132821  ** This is equivalent to copying the contents of the child into
132822  ** the root node (the operation that Gutman's paper says to perform
132823  ** in this scenario).
132824  */
132825  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
132826    int rc2;
132827    RtreeNode *pChild;
132828    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
132829    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
132830    if( rc==SQLITE_OK ){
132831      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
132832    }
132833    rc2 = nodeRelease(pRtree, pChild);
132834    if( rc==SQLITE_OK ) rc = rc2;
132835    if( rc==SQLITE_OK ){
132836      pRtree->iDepth--;
132837      writeInt16(pRoot->zData, pRtree->iDepth);
132838      pRoot->isDirty = 1;
132839    }
132840  }
132841
132842  /* Re-insert the contents of any underfull nodes removed from the tree. */
132843  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
132844    if( rc==SQLITE_OK ){
132845      rc = reinsertNodeContent(pRtree, pLeaf);
132846    }
132847    pRtree->pDeleted = pLeaf->pNext;
132848    sqlite3_free(pLeaf);
132849  }
132850
132851  /* Release the reference to the root node. */
132852  if( rc==SQLITE_OK ){
132853    rc = nodeRelease(pRtree, pRoot);
132854  }else{
132855    nodeRelease(pRtree, pRoot);
132856  }
132857
132858  return rc;
132859}
132860
132861/*
132862** The xUpdate method for rtree module virtual tables.
132863*/
132864static int rtreeUpdate(
132865  sqlite3_vtab *pVtab,
132866  int nData,
132867  sqlite3_value **azData,
132868  sqlite_int64 *pRowid
132869){
132870  Rtree *pRtree = (Rtree *)pVtab;
132871  int rc = SQLITE_OK;
132872  RtreeCell cell;                 /* New cell to insert if nData>1 */
132873  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
132874
132875  rtreeReference(pRtree);
132876  assert(nData>=1);
132877
132878  /* Constraint handling. A write operation on an r-tree table may return
132879  ** SQLITE_CONSTRAINT for two reasons:
132880  **
132881  **   1. A duplicate rowid value, or
132882  **   2. The supplied data violates the "x2>=x1" constraint.
132883  **
132884  ** In the first case, if the conflict-handling mode is REPLACE, then
132885  ** the conflicting row can be removed before proceeding. In the second
132886  ** case, SQLITE_CONSTRAINT must be returned regardless of the
132887  ** conflict-handling mode specified by the user.
132888  */
132889  if( nData>1 ){
132890    int ii;
132891
132892    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
132893    assert( nData==(pRtree->nDim*2 + 3) );
132894    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
132895      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
132896        cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
132897        cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
132898        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
132899          rc = SQLITE_CONSTRAINT;
132900          goto constraint;
132901        }
132902      }
132903    }else{
132904      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
132905        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
132906        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
132907        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
132908          rc = SQLITE_CONSTRAINT;
132909          goto constraint;
132910        }
132911      }
132912    }
132913
132914    /* If a rowid value was supplied, check if it is already present in
132915    ** the table. If so, the constraint has failed. */
132916    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
132917      cell.iRowid = sqlite3_value_int64(azData[2]);
132918      if( sqlite3_value_type(azData[0])==SQLITE_NULL
132919       || sqlite3_value_int64(azData[0])!=cell.iRowid
132920      ){
132921        int steprc;
132922        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
132923        steprc = sqlite3_step(pRtree->pReadRowid);
132924        rc = sqlite3_reset(pRtree->pReadRowid);
132925        if( SQLITE_ROW==steprc ){
132926          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
132927            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
132928          }else{
132929            rc = SQLITE_CONSTRAINT;
132930            goto constraint;
132931          }
132932        }
132933      }
132934      bHaveRowid = 1;
132935    }
132936  }
132937
132938  /* If azData[0] is not an SQL NULL value, it is the rowid of a
132939  ** record to delete from the r-tree table. The following block does
132940  ** just that.
132941  */
132942  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
132943    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
132944  }
132945
132946  /* If the azData[] array contains more than one element, elements
132947  ** (azData[2]..azData[argc-1]) contain a new record to insert into
132948  ** the r-tree structure.
132949  */
132950  if( rc==SQLITE_OK && nData>1 ){
132951    /* Insert the new record into the r-tree */
132952    RtreeNode *pLeaf;
132953
132954    /* Figure out the rowid of the new row. */
132955    if( bHaveRowid==0 ){
132956      rc = newRowid(pRtree, &cell.iRowid);
132957    }
132958    *pRowid = cell.iRowid;
132959
132960    if( rc==SQLITE_OK ){
132961      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
132962    }
132963    if( rc==SQLITE_OK ){
132964      int rc2;
132965      pRtree->iReinsertHeight = -1;
132966      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
132967      rc2 = nodeRelease(pRtree, pLeaf);
132968      if( rc==SQLITE_OK ){
132969        rc = rc2;
132970      }
132971    }
132972  }
132973
132974constraint:
132975  rtreeRelease(pRtree);
132976  return rc;
132977}
132978
132979/*
132980** The xRename method for rtree module virtual tables.
132981*/
132982static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
132983  Rtree *pRtree = (Rtree *)pVtab;
132984  int rc = SQLITE_NOMEM;
132985  char *zSql = sqlite3_mprintf(
132986    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
132987    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
132988    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
132989    , pRtree->zDb, pRtree->zName, zNewName
132990    , pRtree->zDb, pRtree->zName, zNewName
132991    , pRtree->zDb, pRtree->zName, zNewName
132992  );
132993  if( zSql ){
132994    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
132995    sqlite3_free(zSql);
132996  }
132997  return rc;
132998}
132999
133000static sqlite3_module rtreeModule = {
133001  0,                          /* iVersion */
133002  rtreeCreate,                /* xCreate - create a table */
133003  rtreeConnect,               /* xConnect - connect to an existing table */
133004  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
133005  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
133006  rtreeDestroy,               /* xDestroy - Drop a table */
133007  rtreeOpen,                  /* xOpen - open a cursor */
133008  rtreeClose,                 /* xClose - close a cursor */
133009  rtreeFilter,                /* xFilter - configure scan constraints */
133010  rtreeNext,                  /* xNext - advance a cursor */
133011  rtreeEof,                   /* xEof */
133012  rtreeColumn,                /* xColumn - read data */
133013  rtreeRowid,                 /* xRowid - read data */
133014  rtreeUpdate,                /* xUpdate - write data */
133015  0,                          /* xBegin - begin transaction */
133016  0,                          /* xSync - sync transaction */
133017  0,                          /* xCommit - commit transaction */
133018  0,                          /* xRollback - rollback transaction */
133019  0,                          /* xFindFunction - function overloading */
133020  rtreeRename,                /* xRename - rename the table */
133021  0,                          /* xSavepoint */
133022  0,                          /* xRelease */
133023  0                           /* xRollbackTo */
133024};
133025
133026static int rtreeSqlInit(
133027  Rtree *pRtree,
133028  sqlite3 *db,
133029  const char *zDb,
133030  const char *zPrefix,
133031  int isCreate
133032){
133033  int rc = SQLITE_OK;
133034
133035  #define N_STATEMENT 9
133036  static const char *azSql[N_STATEMENT] = {
133037    /* Read and write the xxx_node table */
133038    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
133039    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
133040    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
133041
133042    /* Read and write the xxx_rowid table */
133043    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
133044    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
133045    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
133046
133047    /* Read and write the xxx_parent table */
133048    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
133049    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
133050    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
133051  };
133052  sqlite3_stmt **appStmt[N_STATEMENT];
133053  int i;
133054
133055  pRtree->db = db;
133056
133057  if( isCreate ){
133058    char *zCreate = sqlite3_mprintf(
133059"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
133060"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
133061"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
133062"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
133063      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
133064    );
133065    if( !zCreate ){
133066      return SQLITE_NOMEM;
133067    }
133068    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
133069    sqlite3_free(zCreate);
133070    if( rc!=SQLITE_OK ){
133071      return rc;
133072    }
133073  }
133074
133075  appStmt[0] = &pRtree->pReadNode;
133076  appStmt[1] = &pRtree->pWriteNode;
133077  appStmt[2] = &pRtree->pDeleteNode;
133078  appStmt[3] = &pRtree->pReadRowid;
133079  appStmt[4] = &pRtree->pWriteRowid;
133080  appStmt[5] = &pRtree->pDeleteRowid;
133081  appStmt[6] = &pRtree->pReadParent;
133082  appStmt[7] = &pRtree->pWriteParent;
133083  appStmt[8] = &pRtree->pDeleteParent;
133084
133085  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
133086    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
133087    if( zSql ){
133088      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
133089    }else{
133090      rc = SQLITE_NOMEM;
133091    }
133092    sqlite3_free(zSql);
133093  }
133094
133095  return rc;
133096}
133097
133098/*
133099** The second argument to this function contains the text of an SQL statement
133100** that returns a single integer value. The statement is compiled and executed
133101** using database connection db. If successful, the integer value returned
133102** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
133103** code is returned and the value of *piVal after returning is not defined.
133104*/
133105static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
133106  int rc = SQLITE_NOMEM;
133107  if( zSql ){
133108    sqlite3_stmt *pStmt = 0;
133109    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
133110    if( rc==SQLITE_OK ){
133111      if( SQLITE_ROW==sqlite3_step(pStmt) ){
133112        *piVal = sqlite3_column_int(pStmt, 0);
133113      }
133114      rc = sqlite3_finalize(pStmt);
133115    }
133116  }
133117  return rc;
133118}
133119
133120/*
133121** This function is called from within the xConnect() or xCreate() method to
133122** determine the node-size used by the rtree table being created or connected
133123** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
133124** Otherwise, an SQLite error code is returned.
133125**
133126** If this function is being called as part of an xConnect(), then the rtree
133127** table already exists. In this case the node-size is determined by inspecting
133128** the root node of the tree.
133129**
133130** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
133131** This ensures that each node is stored on a single database page. If the
133132** database page-size is so large that more than RTREE_MAXCELLS entries
133133** would fit in a single node, use a smaller node-size.
133134*/
133135static int getNodeSize(
133136  sqlite3 *db,                    /* Database handle */
133137  Rtree *pRtree,                  /* Rtree handle */
133138  int isCreate                    /* True for xCreate, false for xConnect */
133139){
133140  int rc;
133141  char *zSql;
133142  if( isCreate ){
133143    int iPageSize = 0;
133144    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
133145    rc = getIntFromStmt(db, zSql, &iPageSize);
133146    if( rc==SQLITE_OK ){
133147      pRtree->iNodeSize = iPageSize-64;
133148      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
133149        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
133150      }
133151    }
133152  }else{
133153    zSql = sqlite3_mprintf(
133154        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
133155        pRtree->zDb, pRtree->zName
133156    );
133157    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
133158  }
133159
133160  sqlite3_free(zSql);
133161  return rc;
133162}
133163
133164/*
133165** This function is the implementation of both the xConnect and xCreate
133166** methods of the r-tree virtual table.
133167**
133168**   argv[0]   -> module name
133169**   argv[1]   -> database name
133170**   argv[2]   -> table name
133171**   argv[...] -> column names...
133172*/
133173static int rtreeInit(
133174  sqlite3 *db,                        /* Database connection */
133175  void *pAux,                         /* One of the RTREE_COORD_* constants */
133176  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
133177  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
133178  char **pzErr,                       /* OUT: Error message, if any */
133179  int isCreate                        /* True for xCreate, false for xConnect */
133180){
133181  int rc = SQLITE_OK;
133182  Rtree *pRtree;
133183  int nDb;              /* Length of string argv[1] */
133184  int nName;            /* Length of string argv[2] */
133185  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
133186
133187  const char *aErrMsg[] = {
133188    0,                                                    /* 0 */
133189    "Wrong number of columns for an rtree table",         /* 1 */
133190    "Too few columns for an rtree table",                 /* 2 */
133191    "Too many columns for an rtree table"                 /* 3 */
133192  };
133193
133194  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
133195  if( aErrMsg[iErr] ){
133196    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
133197    return SQLITE_ERROR;
133198  }
133199
133200  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
133201
133202  /* Allocate the sqlite3_vtab structure */
133203  nDb = (int)strlen(argv[1]);
133204  nName = (int)strlen(argv[2]);
133205  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
133206  if( !pRtree ){
133207    return SQLITE_NOMEM;
133208  }
133209  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
133210  pRtree->nBusy = 1;
133211  pRtree->base.pModule = &rtreeModule;
133212  pRtree->zDb = (char *)&pRtree[1];
133213  pRtree->zName = &pRtree->zDb[nDb+1];
133214  pRtree->nDim = (argc-4)/2;
133215  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
133216  pRtree->eCoordType = eCoordType;
133217  memcpy(pRtree->zDb, argv[1], nDb);
133218  memcpy(pRtree->zName, argv[2], nName);
133219
133220  /* Figure out the node size to use. */
133221  rc = getNodeSize(db, pRtree, isCreate);
133222
133223  /* Create/Connect to the underlying relational database schema. If
133224  ** that is successful, call sqlite3_declare_vtab() to configure
133225  ** the r-tree table schema.
133226  */
133227  if( rc==SQLITE_OK ){
133228    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
133229      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
133230    }else{
133231      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
133232      char *zTmp;
133233      int ii;
133234      for(ii=4; zSql && ii<argc; ii++){
133235        zTmp = zSql;
133236        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
133237        sqlite3_free(zTmp);
133238      }
133239      if( zSql ){
133240        zTmp = zSql;
133241        zSql = sqlite3_mprintf("%s);", zTmp);
133242        sqlite3_free(zTmp);
133243      }
133244      if( !zSql ){
133245        rc = SQLITE_NOMEM;
133246      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
133247        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
133248      }
133249      sqlite3_free(zSql);
133250    }
133251  }
133252
133253  if( rc==SQLITE_OK ){
133254    *ppVtab = (sqlite3_vtab *)pRtree;
133255  }else{
133256    rtreeRelease(pRtree);
133257  }
133258  return rc;
133259}
133260
133261
133262/*
133263** Implementation of a scalar function that decodes r-tree nodes to
133264** human readable strings. This can be used for debugging and analysis.
133265**
133266** The scalar function takes two arguments, a blob of data containing
133267** an r-tree node, and the number of dimensions the r-tree indexes.
133268** For a two-dimensional r-tree structure called "rt", to deserialize
133269** all nodes, a statement like:
133270**
133271**   SELECT rtreenode(2, data) FROM rt_node;
133272**
133273** The human readable string takes the form of a Tcl list with one
133274** entry for each cell in the r-tree node. Each entry is itself a
133275** list, containing the 8-byte rowid/pageno followed by the
133276** <num-dimension>*2 coordinates.
133277*/
133278static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
133279  char *zText = 0;
133280  RtreeNode node;
133281  Rtree tree;
133282  int ii;
133283
133284  UNUSED_PARAMETER(nArg);
133285  memset(&node, 0, sizeof(RtreeNode));
133286  memset(&tree, 0, sizeof(Rtree));
133287  tree.nDim = sqlite3_value_int(apArg[0]);
133288  tree.nBytesPerCell = 8 + 8 * tree.nDim;
133289  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
133290
133291  for(ii=0; ii<NCELL(&node); ii++){
133292    char zCell[512];
133293    int nCell = 0;
133294    RtreeCell cell;
133295    int jj;
133296
133297    nodeGetCell(&tree, &node, ii, &cell);
133298    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
133299    nCell = (int)strlen(zCell);
133300    for(jj=0; jj<tree.nDim*2; jj++){
133301      sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
133302      nCell = (int)strlen(zCell);
133303    }
133304
133305    if( zText ){
133306      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
133307      sqlite3_free(zText);
133308      zText = zTextNew;
133309    }else{
133310      zText = sqlite3_mprintf("{%s}", zCell);
133311    }
133312  }
133313
133314  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
133315}
133316
133317static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
133318  UNUSED_PARAMETER(nArg);
133319  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
133320   || sqlite3_value_bytes(apArg[0])<2
133321  ){
133322    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
133323  }else{
133324    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
133325    sqlite3_result_int(ctx, readInt16(zBlob));
133326  }
133327}
133328
133329/*
133330** Register the r-tree module with database handle db. This creates the
133331** virtual table module "rtree" and the debugging/analysis scalar
133332** function "rtreenode".
133333*/
133334SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
133335  const int utf8 = SQLITE_UTF8;
133336  int rc;
133337
133338  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
133339  if( rc==SQLITE_OK ){
133340    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
133341  }
133342  if( rc==SQLITE_OK ){
133343    void *c = (void *)RTREE_COORD_REAL32;
133344    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
133345  }
133346  if( rc==SQLITE_OK ){
133347    void *c = (void *)RTREE_COORD_INT32;
133348    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
133349  }
133350
133351  return rc;
133352}
133353
133354/*
133355** A version of sqlite3_free() that can be used as a callback. This is used
133356** in two places - as the destructor for the blob value returned by the
133357** invocation of a geometry function, and as the destructor for the geometry
133358** functions themselves.
133359*/
133360static void doSqlite3Free(void *p){
133361  sqlite3_free(p);
133362}
133363
133364/*
133365** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
133366** scalar user function. This C function is the callback used for all such
133367** registered SQL functions.
133368**
133369** The scalar user functions return a blob that is interpreted by r-tree
133370** table MATCH operators.
133371*/
133372static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
133373  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
133374  RtreeMatchArg *pBlob;
133375  int nBlob;
133376
133377  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
133378  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
133379  if( !pBlob ){
133380    sqlite3_result_error_nomem(ctx);
133381  }else{
133382    int i;
133383    pBlob->magic = RTREE_GEOMETRY_MAGIC;
133384    pBlob->xGeom = pGeomCtx->xGeom;
133385    pBlob->pContext = pGeomCtx->pContext;
133386    pBlob->nParam = nArg;
133387    for(i=0; i<nArg; i++){
133388      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
133389    }
133390    sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
133391  }
133392}
133393
133394/*
133395** Register a new geometry function for use with the r-tree MATCH operator.
133396*/
133397SQLITE_API int sqlite3_rtree_geometry_callback(
133398  sqlite3 *db,
133399  const char *zGeom,
133400  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
133401  void *pContext
133402){
133403  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
133404
133405  /* Allocate and populate the context object. */
133406  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
133407  if( !pGeomCtx ) return SQLITE_NOMEM;
133408  pGeomCtx->xGeom = xGeom;
133409  pGeomCtx->pContext = pContext;
133410
133411  /* Create the new user-function. Register a destructor function to delete
133412  ** the context object when it is no longer required.  */
133413  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
133414      (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
133415  );
133416}
133417
133418#if !SQLITE_CORE
133419SQLITE_API int sqlite3_extension_init(
133420  sqlite3 *db,
133421  char **pzErrMsg,
133422  const sqlite3_api_routines *pApi
133423){
133424  SQLITE_EXTENSION_INIT2(pApi)
133425  return sqlite3RtreeInit(db);
133426}
133427#endif
133428
133429#endif
133430
133431/************** End of rtree.c ***********************************************/
133432/************** Begin file icu.c *********************************************/
133433/*
133434** 2007 May 6
133435**
133436** The author disclaims copyright to this source code.  In place of
133437** a legal notice, here is a blessing:
133438**
133439**    May you do good and not evil.
133440**    May you find forgiveness for yourself and forgive others.
133441**    May you share freely, never taking more than you give.
133442**
133443*************************************************************************
133444** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
133445**
133446** This file implements an integration between the ICU library
133447** ("International Components for Unicode", an open-source library
133448** for handling unicode data) and SQLite. The integration uses
133449** ICU to provide the following to SQLite:
133450**
133451**   * An implementation of the SQL regexp() function (and hence REGEXP
133452**     operator) using the ICU uregex_XX() APIs.
133453**
133454**   * Implementations of the SQL scalar upper() and lower() functions
133455**     for case mapping.
133456**
133457**   * Integration of ICU and SQLite collation seqences.
133458**
133459**   * An implementation of the LIKE operator that uses ICU to
133460**     provide case-independent matching.
133461*/
133462
133463#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
133464
133465/* Include ICU headers */
133466#include <unicode/utypes.h>
133467#include <unicode/uregex.h>
133468#include <unicode/ustring.h>
133469#include <unicode/ucol.h>
133470
133471/* #include <assert.h> */
133472
133473#ifndef SQLITE_CORE
133474  SQLITE_EXTENSION_INIT1
133475#else
133476#endif
133477
133478/*
133479** Maximum length (in bytes) of the pattern in a LIKE or GLOB
133480** operator.
133481*/
133482#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
133483# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
133484#endif
133485
133486/*
133487** Version of sqlite3_free() that is always a function, never a macro.
133488*/
133489static void xFree(void *p){
133490  sqlite3_free(p);
133491}
133492
133493/*
133494** Compare two UTF-8 strings for equality where the first string is
133495** a "LIKE" expression. Return true (1) if they are the same and
133496** false (0) if they are different.
133497*/
133498static int icuLikeCompare(
133499  const uint8_t *zPattern,   /* LIKE pattern */
133500  const uint8_t *zString,    /* The UTF-8 string to compare against */
133501  const UChar32 uEsc         /* The escape character */
133502){
133503  static const int MATCH_ONE = (UChar32)'_';
133504  static const int MATCH_ALL = (UChar32)'%';
133505
133506  int iPattern = 0;       /* Current byte index in zPattern */
133507  int iString = 0;        /* Current byte index in zString */
133508
133509  int prevEscape = 0;     /* True if the previous character was uEsc */
133510
133511  while( zPattern[iPattern]!=0 ){
133512
133513    /* Read (and consume) the next character from the input pattern. */
133514    UChar32 uPattern;
133515    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
133516    assert(uPattern!=0);
133517
133518    /* There are now 4 possibilities:
133519    **
133520    **     1. uPattern is an unescaped match-all character "%",
133521    **     2. uPattern is an unescaped match-one character "_",
133522    **     3. uPattern is an unescaped escape character, or
133523    **     4. uPattern is to be handled as an ordinary character
133524    */
133525    if( !prevEscape && uPattern==MATCH_ALL ){
133526      /* Case 1. */
133527      uint8_t c;
133528
133529      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
133530      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
133531      ** test string.
133532      */
133533      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
133534        if( c==MATCH_ONE ){
133535          if( zString[iString]==0 ) return 0;
133536          U8_FWD_1_UNSAFE(zString, iString);
133537        }
133538        iPattern++;
133539      }
133540
133541      if( zPattern[iPattern]==0 ) return 1;
133542
133543      while( zString[iString] ){
133544        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
133545          return 1;
133546        }
133547        U8_FWD_1_UNSAFE(zString, iString);
133548      }
133549      return 0;
133550
133551    }else if( !prevEscape && uPattern==MATCH_ONE ){
133552      /* Case 2. */
133553      if( zString[iString]==0 ) return 0;
133554      U8_FWD_1_UNSAFE(zString, iString);
133555
133556    }else if( !prevEscape && uPattern==uEsc){
133557      /* Case 3. */
133558      prevEscape = 1;
133559
133560    }else{
133561      /* Case 4. */
133562      UChar32 uString;
133563      U8_NEXT_UNSAFE(zString, iString, uString);
133564      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
133565      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
133566      if( uString!=uPattern ){
133567        return 0;
133568      }
133569      prevEscape = 0;
133570    }
133571  }
133572
133573  return zString[iString]==0;
133574}
133575
133576/*
133577** Implementation of the like() SQL function.  This function implements
133578** the build-in LIKE operator.  The first argument to the function is the
133579** pattern and the second argument is the string.  So, the SQL statements:
133580**
133581**       A LIKE B
133582**
133583** is implemented as like(B, A). If there is an escape character E,
133584**
133585**       A LIKE B ESCAPE E
133586**
133587** is mapped to like(B, A, E).
133588*/
133589static void icuLikeFunc(
133590  sqlite3_context *context,
133591  int argc,
133592  sqlite3_value **argv
133593){
133594  const unsigned char *zA = sqlite3_value_text(argv[0]);
133595  const unsigned char *zB = sqlite3_value_text(argv[1]);
133596  UChar32 uEsc = 0;
133597
133598  /* Limit the length of the LIKE or GLOB pattern to avoid problems
133599  ** of deep recursion and N*N behavior in patternCompare().
133600  */
133601  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
133602    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
133603    return;
133604  }
133605
133606
133607  if( argc==3 ){
133608    /* The escape character string must consist of a single UTF-8 character.
133609    ** Otherwise, return an error.
133610    */
133611    int nE= sqlite3_value_bytes(argv[2]);
133612    const unsigned char *zE = sqlite3_value_text(argv[2]);
133613    int i = 0;
133614    if( zE==0 ) return;
133615    U8_NEXT(zE, i, nE, uEsc);
133616    if( i!=nE){
133617      sqlite3_result_error(context,
133618          "ESCAPE expression must be a single character", -1);
133619      return;
133620    }
133621  }
133622
133623  if( zA && zB ){
133624    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
133625  }
133626}
133627
133628/*
133629** This function is called when an ICU function called from within
133630** the implementation of an SQL scalar function returns an error.
133631**
133632** The scalar function context passed as the first argument is
133633** loaded with an error message based on the following two args.
133634*/
133635static void icuFunctionError(
133636  sqlite3_context *pCtx,       /* SQLite scalar function context */
133637  const char *zName,           /* Name of ICU function that failed */
133638  UErrorCode e                 /* Error code returned by ICU function */
133639){
133640  char zBuf[128];
133641  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
133642  zBuf[127] = '\0';
133643  sqlite3_result_error(pCtx, zBuf, -1);
133644}
133645
133646/*
133647** Function to delete compiled regexp objects. Registered as
133648** a destructor function with sqlite3_set_auxdata().
133649*/
133650static void icuRegexpDelete(void *p){
133651  URegularExpression *pExpr = (URegularExpression *)p;
133652  uregex_close(pExpr);
133653}
133654
133655/*
133656** Implementation of SQLite REGEXP operator. This scalar function takes
133657** two arguments. The first is a regular expression pattern to compile
133658** the second is a string to match against that pattern. If either
133659** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
133660** is 1 if the string matches the pattern, or 0 otherwise.
133661**
133662** SQLite maps the regexp() function to the regexp() operator such
133663** that the following two are equivalent:
133664**
133665**     zString REGEXP zPattern
133666**     regexp(zPattern, zString)
133667**
133668** Uses the following ICU regexp APIs:
133669**
133670**     uregex_open()
133671**     uregex_matches()
133672**     uregex_close()
133673*/
133674static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
133675  UErrorCode status = U_ZERO_ERROR;
133676  URegularExpression *pExpr;
133677  UBool res;
133678  const UChar *zString = sqlite3_value_text16(apArg[1]);
133679
133680  (void)nArg;  /* Unused parameter */
133681
133682  /* If the left hand side of the regexp operator is NULL,
133683  ** then the result is also NULL.
133684  */
133685  if( !zString ){
133686    return;
133687  }
133688
133689  pExpr = sqlite3_get_auxdata(p, 0);
133690  if( !pExpr ){
133691    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
133692    if( !zPattern ){
133693      return;
133694    }
133695    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
133696
133697    if( U_SUCCESS(status) ){
133698      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
133699    }else{
133700      assert(!pExpr);
133701      icuFunctionError(p, "uregex_open", status);
133702      return;
133703    }
133704  }
133705
133706  /* Configure the text that the regular expression operates on. */
133707  uregex_setText(pExpr, zString, -1, &status);
133708  if( !U_SUCCESS(status) ){
133709    icuFunctionError(p, "uregex_setText", status);
133710    return;
133711  }
133712
133713  /* Attempt the match */
133714  res = uregex_matches(pExpr, 0, &status);
133715  if( !U_SUCCESS(status) ){
133716    icuFunctionError(p, "uregex_matches", status);
133717    return;
133718  }
133719
133720  /* Set the text that the regular expression operates on to a NULL
133721  ** pointer. This is not really necessary, but it is tidier than
133722  ** leaving the regular expression object configured with an invalid
133723  ** pointer after this function returns.
133724  */
133725  uregex_setText(pExpr, 0, 0, &status);
133726
133727  /* Return 1 or 0. */
133728  sqlite3_result_int(p, res ? 1 : 0);
133729}
133730
133731/*
133732** Implementations of scalar functions for case mapping - upper() and
133733** lower(). Function upper() converts its input to upper-case (ABC).
133734** Function lower() converts to lower-case (abc).
133735**
133736** ICU provides two types of case mapping, "general" case mapping and
133737** "language specific". Refer to ICU documentation for the differences
133738** between the two.
133739**
133740** To utilise "general" case mapping, the upper() or lower() scalar
133741** functions are invoked with one argument:
133742**
133743**     upper('ABC') -> 'abc'
133744**     lower('abc') -> 'ABC'
133745**
133746** To access ICU "language specific" case mapping, upper() or lower()
133747** should be invoked with two arguments. The second argument is the name
133748** of the locale to use. Passing an empty string ("") or SQL NULL value
133749** as the second argument is the same as invoking the 1 argument version
133750** of upper() or lower().
133751**
133752**     lower('I', 'en_us') -> 'i'
133753**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
133754**
133755** http://www.icu-project.org/userguide/posix.html#case_mappings
133756*/
133757static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
133758  const UChar *zInput;
133759  UChar *zOutput;
133760  int nInput;
133761  int nOutput;
133762
133763  UErrorCode status = U_ZERO_ERROR;
133764  const char *zLocale = 0;
133765
133766  assert(nArg==1 || nArg==2);
133767  if( nArg==2 ){
133768    zLocale = (const char *)sqlite3_value_text(apArg[1]);
133769  }
133770
133771  zInput = sqlite3_value_text16(apArg[0]);
133772  if( !zInput ){
133773    return;
133774  }
133775  nInput = sqlite3_value_bytes16(apArg[0]);
133776
133777  nOutput = nInput * 2 + 2;
133778  zOutput = sqlite3_malloc(nOutput);
133779  if( !zOutput ){
133780    return;
133781  }
133782
133783  if( sqlite3_user_data(p) ){
133784    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
133785  }else{
133786    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
133787  }
133788
133789  if( !U_SUCCESS(status) ){
133790    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
133791    return;
133792  }
133793
133794  sqlite3_result_text16(p, zOutput, -1, xFree);
133795}
133796
133797/*
133798** Collation sequence destructor function. The pCtx argument points to
133799** a UCollator structure previously allocated using ucol_open().
133800*/
133801static void icuCollationDel(void *pCtx){
133802  UCollator *p = (UCollator *)pCtx;
133803  ucol_close(p);
133804}
133805
133806/*
133807** Collation sequence comparison function. The pCtx argument points to
133808** a UCollator structure previously allocated using ucol_open().
133809*/
133810static int icuCollationColl(
133811  void *pCtx,
133812  int nLeft,
133813  const void *zLeft,
133814  int nRight,
133815  const void *zRight
133816){
133817  UCollationResult res;
133818  UCollator *p = (UCollator *)pCtx;
133819  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
133820  switch( res ){
133821    case UCOL_LESS:    return -1;
133822    case UCOL_GREATER: return +1;
133823    case UCOL_EQUAL:   return 0;
133824  }
133825  assert(!"Unexpected return value from ucol_strcoll()");
133826  return 0;
133827}
133828
133829/*
133830** Implementation of the scalar function icu_load_collation().
133831**
133832** This scalar function is used to add ICU collation based collation
133833** types to an SQLite database connection. It is intended to be called
133834** as follows:
133835**
133836**     SELECT icu_load_collation(<locale>, <collation-name>);
133837**
133838** Where <locale> is a string containing an ICU locale identifier (i.e.
133839** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
133840** collation sequence to create.
133841*/
133842static void icuLoadCollation(
133843  sqlite3_context *p,
133844  int nArg,
133845  sqlite3_value **apArg
133846){
133847  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
133848  UErrorCode status = U_ZERO_ERROR;
133849  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
133850  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
133851  UCollator *pUCollator;    /* ICU library collation object */
133852  int rc;                   /* Return code from sqlite3_create_collation_x() */
133853
133854  assert(nArg==2);
133855  zLocale = (const char *)sqlite3_value_text(apArg[0]);
133856  zName = (const char *)sqlite3_value_text(apArg[1]);
133857
133858  if( !zLocale || !zName ){
133859    return;
133860  }
133861
133862  pUCollator = ucol_open(zLocale, &status);
133863  if( !U_SUCCESS(status) ){
133864    icuFunctionError(p, "ucol_open", status);
133865    return;
133866  }
133867  assert(p);
133868
133869  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
133870      icuCollationColl, icuCollationDel
133871  );
133872  if( rc!=SQLITE_OK ){
133873    ucol_close(pUCollator);
133874    sqlite3_result_error(p, "Error registering collation function", -1);
133875  }
133876}
133877
133878/*
133879** Register the ICU extension functions with database db.
133880*/
133881SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
133882  struct IcuScalar {
133883    const char *zName;                        /* Function name */
133884    int nArg;                                 /* Number of arguments */
133885    int enc;                                  /* Optimal text encoding */
133886    void *pContext;                           /* sqlite3_user_data() context */
133887    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
133888  } scalars[] = {
133889    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
133890
133891    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
133892    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
133893    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
133894    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
133895
133896    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
133897    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
133898    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
133899    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
133900
133901    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
133902    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
133903
133904    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
133905  };
133906
133907  int rc = SQLITE_OK;
133908  int i;
133909
133910  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
133911    struct IcuScalar *p = &scalars[i];
133912    rc = sqlite3_create_function(
133913        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
133914    );
133915  }
133916
133917  return rc;
133918}
133919
133920#if !SQLITE_CORE
133921SQLITE_API int sqlite3_extension_init(
133922  sqlite3 *db,
133923  char **pzErrMsg,
133924  const sqlite3_api_routines *pApi
133925){
133926  SQLITE_EXTENSION_INIT2(pApi)
133927  return sqlite3IcuInit(db);
133928}
133929#endif
133930
133931#endif
133932
133933/************** End of icu.c *************************************************/
133934/************** Begin file fts3_icu.c ****************************************/
133935/*
133936** 2007 June 22
133937**
133938** The author disclaims copyright to this source code.  In place of
133939** a legal notice, here is a blessing:
133940**
133941**    May you do good and not evil.
133942**    May you find forgiveness for yourself and forgive others.
133943**    May you share freely, never taking more than you give.
133944**
133945*************************************************************************
133946** This file implements a tokenizer for fts3 based on the ICU library.
133947*/
133948#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
133949#ifdef SQLITE_ENABLE_ICU
133950
133951/* #include <assert.h> */
133952/* #include <string.h> */
133953
133954#include <unicode/ubrk.h>
133955/* #include <unicode/ucol.h> */
133956/* #include <unicode/ustring.h> */
133957#include <unicode/utf16.h>
133958
133959typedef struct IcuTokenizer IcuTokenizer;
133960typedef struct IcuCursor IcuCursor;
133961
133962struct IcuTokenizer {
133963  sqlite3_tokenizer base;
133964  char *zLocale;
133965};
133966
133967struct IcuCursor {
133968  sqlite3_tokenizer_cursor base;
133969
133970  UBreakIterator *pIter;      /* ICU break-iterator object */
133971  int nChar;                  /* Number of UChar elements in pInput */
133972  UChar *aChar;               /* Copy of input using utf-16 encoding */
133973  int *aOffset;               /* Offsets of each character in utf-8 input */
133974
133975  int nBuffer;
133976  char *zBuffer;
133977
133978  int iToken;
133979};
133980
133981/*
133982** Create a new tokenizer instance.
133983*/
133984static int icuCreate(
133985  int argc,                            /* Number of entries in argv[] */
133986  const char * const *argv,            /* Tokenizer creation arguments */
133987  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
133988){
133989  IcuTokenizer *p;
133990  int n = 0;
133991
133992  if( argc>0 ){
133993    n = strlen(argv[0])+1;
133994  }
133995  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
133996  if( !p ){
133997    return SQLITE_NOMEM;
133998  }
133999  memset(p, 0, sizeof(IcuTokenizer));
134000
134001  if( n ){
134002    p->zLocale = (char *)&p[1];
134003    memcpy(p->zLocale, argv[0], n);
134004  }
134005
134006  *ppTokenizer = (sqlite3_tokenizer *)p;
134007
134008  return SQLITE_OK;
134009}
134010
134011/*
134012** Destroy a tokenizer
134013*/
134014static int icuDestroy(sqlite3_tokenizer *pTokenizer){
134015  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
134016  sqlite3_free(p);
134017  return SQLITE_OK;
134018}
134019
134020/*
134021** Prepare to begin tokenizing a particular string.  The input
134022** string to be tokenized is pInput[0..nBytes-1].  A cursor
134023** used to incrementally tokenize this string is returned in
134024** *ppCursor.
134025*/
134026static int icuOpen(
134027  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
134028  const char *zInput,                    /* Input string */
134029  int nInput,                            /* Length of zInput in bytes */
134030  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
134031){
134032  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
134033  IcuCursor *pCsr;
134034
134035  const int32_t opt = U_FOLD_CASE_DEFAULT;
134036  UErrorCode status = U_ZERO_ERROR;
134037  int nChar;
134038
134039  UChar32 c;
134040  int iInput = 0;
134041  int iOut = 0;
134042
134043  *ppCursor = 0;
134044
134045  if( nInput<0 ){
134046    nInput = strlen(zInput);
134047  }
134048  nChar = nInput+1;
134049  pCsr = (IcuCursor *)sqlite3_malloc(
134050      sizeof(IcuCursor) +                /* IcuCursor */
134051      nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
134052      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
134053  );
134054  if( !pCsr ){
134055    return SQLITE_NOMEM;
134056  }
134057  memset(pCsr, 0, sizeof(IcuCursor));
134058  pCsr->aChar = (UChar *)&pCsr[1];
134059  pCsr->aOffset = (int *)&pCsr->aChar[nChar];
134060
134061  pCsr->aOffset[iOut] = iInput;
134062  U8_NEXT(zInput, iInput, nInput, c);
134063  while( c>0 ){
134064    int isError = 0;
134065    c = u_foldCase(c, opt);
134066    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
134067    if( isError ){
134068      sqlite3_free(pCsr);
134069      return SQLITE_ERROR;
134070    }
134071    pCsr->aOffset[iOut] = iInput;
134072
134073    if( iInput<nInput ){
134074      U8_NEXT(zInput, iInput, nInput, c);
134075    }else{
134076      c = 0;
134077    }
134078  }
134079
134080  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
134081  if( !U_SUCCESS(status) ){
134082    sqlite3_free(pCsr);
134083    return SQLITE_ERROR;
134084  }
134085  pCsr->nChar = iOut;
134086
134087  ubrk_first(pCsr->pIter);
134088  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
134089  return SQLITE_OK;
134090}
134091
134092/*
134093** Close a tokenization cursor previously opened by a call to icuOpen().
134094*/
134095static int icuClose(sqlite3_tokenizer_cursor *pCursor){
134096  IcuCursor *pCsr = (IcuCursor *)pCursor;
134097  ubrk_close(pCsr->pIter);
134098  sqlite3_free(pCsr->zBuffer);
134099  sqlite3_free(pCsr);
134100  return SQLITE_OK;
134101}
134102
134103/*
134104** Extract the next token from a tokenization cursor.
134105*/
134106static int icuNext(
134107  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
134108  const char **ppToken,               /* OUT: *ppToken is the token text */
134109  int *pnBytes,                       /* OUT: Number of bytes in token */
134110  int *piStartOffset,                 /* OUT: Starting offset of token */
134111  int *piEndOffset,                   /* OUT: Ending offset of token */
134112  int *piPosition                     /* OUT: Position integer of token */
134113){
134114  IcuCursor *pCsr = (IcuCursor *)pCursor;
134115
134116  int iStart = 0;
134117  int iEnd = 0;
134118  int nByte = 0;
134119
134120  while( iStart==iEnd ){
134121    UChar32 c;
134122
134123    iStart = ubrk_current(pCsr->pIter);
134124    iEnd = ubrk_next(pCsr->pIter);
134125    if( iEnd==UBRK_DONE ){
134126      return SQLITE_DONE;
134127    }
134128
134129    while( iStart<iEnd ){
134130      int iWhite = iStart;
134131      U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
134132      if( u_isspace(c) ){
134133        iStart = iWhite;
134134      }else{
134135        break;
134136      }
134137    }
134138    assert(iStart<=iEnd);
134139  }
134140
134141  do {
134142    UErrorCode status = U_ZERO_ERROR;
134143    if( nByte ){
134144      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
134145      if( !zNew ){
134146        return SQLITE_NOMEM;
134147      }
134148      pCsr->zBuffer = zNew;
134149      pCsr->nBuffer = nByte;
134150    }
134151
134152    u_strToUTF8(
134153        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
134154        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
134155        &status                                  /* Output success/failure */
134156    );
134157  } while( nByte>pCsr->nBuffer );
134158
134159  *ppToken = pCsr->zBuffer;
134160  *pnBytes = nByte;
134161  *piStartOffset = pCsr->aOffset[iStart];
134162  *piEndOffset = pCsr->aOffset[iEnd];
134163  *piPosition = pCsr->iToken++;
134164
134165  return SQLITE_OK;
134166}
134167
134168/*
134169** The set of routines that implement the simple tokenizer
134170*/
134171static const sqlite3_tokenizer_module icuTokenizerModule = {
134172  0,                           /* iVersion */
134173  icuCreate,                   /* xCreate  */
134174  icuDestroy,                  /* xCreate  */
134175  icuOpen,                     /* xOpen    */
134176  icuClose,                    /* xClose   */
134177  icuNext,                     /* xNext    */
134178};
134179
134180/*
134181** Set *ppModule to point at the implementation of the ICU tokenizer.
134182*/
134183SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
134184  sqlite3_tokenizer_module const**ppModule
134185){
134186  *ppModule = &icuTokenizerModule;
134187}
134188
134189#endif /* defined(SQLITE_ENABLE_ICU) */
134190#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
134191
134192/************** End of fts3_icu.c ********************************************/
134193